#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# A simple and fast sub domains brute tool for pentesters
# my[at]lijiejie.com (http://www.lijiejie.com)

import Queue
import sys
import dns.resolver
import threading
import time
import optparse
import os
from lib.consle_width import getTerminalSize

class DNSBrute:
    def __init__(self, target, names_file, ignore_intranet, threads_num, output):
        self.target = target.strip()
        self.names_file = names_file
        self.ignore_intranet = ignore_intranet
        self.thread_count = self.threads_num = threads_num
        self.scan_count = self.found_count = 0
        self.lock = threading.Lock()
        self.console_width = getTerminalSize()[0] - 2    # Cal terminal width when starts up
        self.resolvers = [dns.resolver.Resolver() for _ in range(threads_num)]
        self._load_dns_servers()
        self._load_sub_names()
        self._load_next_sub()
        outfile = target + '.txt' if not output else output
        self.outfile = open(outfile, 'w')   # won't close manually
        self.ip_dict = {}
        self.STOP_ME = False

def _load_dns_servers(self):
        dns_servers = []
        with open('dict/dns_servers.txt') as f:
            for line in f:
                server = line.strip()
                if server.count('.') == 3 and server not in dns_servers:
                    dns_servers.append(server)
        self.dns_servers = dns_servers
        self.dns_count = len(dns_servers)

def _load_sub_names(self):
        self.queue = Queue.Queue()
        file = 'dict/' + self.names_file if not os.path.exists(self.names_file) else self.names_file
        with open(file) as f:
            for line in f:
                sub = line.strip()
                if sub: self.queue.put(sub)

def _load_next_sub(self):
        next_subs = []
        with open('dict/next_sub.txt') as f:
            for line in f:
                sub = line.strip()
                if sub and sub not in next_subs:
                    next_subs.append(sub)
        self.next_subs = next_subs

def _update_scan_count(self):
        self.lock.acquire()
        self.scan_count += 1
        self.lock.release()

def _print_progress(self):
        self.lock.acquire()
        msg = '%s found | %s remaining | %s scanned in %.2f seconds' % (
            self.found_count, self.queue.qsize(), self.scan_count, time.time() - self.start_time)
        sys.stdout.write('\r' + ' ' * (self.console_width -len(msg)) + msg)
        sys.stdout.flush()
        self.lock.release()

@staticmethod
    def is_intranet(ip):
        ret = ip.split('.')
        if not len(ret) == 4:
            return True
        if ret[0] == '10':
            return True
        if ret[0] == '172' and 16 <= int(ret[1]) <= 32:
            return True
        if ret[0] == '192' and ret[1] == '168':
            return True
        return False

def _scan(self):
        thread_id = int( threading.currentThread().getName() )
        self.resolvers[thread_id].nameservers.insert(0, self.dns_servers[thread_id % self.dns_count])
        self.resolvers[thread_id].lifetime = self.resolvers[thread_id].timeout = 10.0
        while self.queue.qsize() > 0 and not self.STOP_ME and self.found_count < 40000:    # limit max found records to 40000
            sub = self.queue.get(timeout=1.0)
            for _ in range(3):
                try:
                    cur_sub_domain = sub + '.' + self.target
                    answers = d.resolvers[thread_id].query(cur_sub_domain)
                    is_wildcard_record = False
                    if answers:
                        for answer in answers:
                            self.lock.acquire()
                            if answer.address not in self.ip_dict:
                                self.ip_dict[answer.address] = 1
                            else:
                                self.ip_dict[answer.address] += 1
                                if self.ip_dict[answer.address] > 2:    # a wildcard DNS record
                                    is_wildcard_record = True
                            self.lock.release()
                        if is_wildcard_record:
                            self._update_scan_count()
                            self._print_progress()
                            continue
                        ips = ', '.join([answer.address for answer in answers])
                        if (not self.ignore_intranet) or (not DNSBrute.is_intranet(answers[0].address)):
                            self.lock.acquire()
                            self.found_count += 1
                            msg = cur_sub_domain.ljust(30) + ips
                            sys.stdout.write('\r' + msg + ' ' * (self.console_width- len(msg)) + '\n\r')
                            sys.stdout.flush()
                            self.outfile.write(cur_sub_domain.ljust(30) + '\t' + ips + '\n')
                            self.lock.release()
                            try:
                                d.resolvers[thread_id].query('*.' + cur_sub_domain)
                            except:
                                for i in self.next_subs:
                                    self.queue.put(i + '.' + sub)
                        break
                except dns.resolver.NoNameservers, e:
                    break
                except Exception, e:
                    pass
            self._update_scan_count()
            self._print_progress()
        self._print_progress()
        self.lock.acquire()
        self.thread_count -= 1
        self.lock.release()

def run(self):
        self.start_time = time.time()
        for i in range(self.threads_num):
            t = threading.Thread(target=self._scan, name=str(i))
            t.setDaemon(True)
            t.start()
        while self.thread_count > 1:
            try:
                time.sleep(1.0)
            except KeyboardInterrupt,e:
                msg = '[WARNING] User aborted, wait all slave threads to exit...'
                sys.stdout.write('\r' + msg + ' ' * (self.console_width- len(msg)) + '\n\r')
                sys.stdout.flush()
                self.STOP_ME = True

if __name__ == '__main__':
    parser = optparse.OptionParser('usage: %prog [options] target.com')
    parser.add_option('-t', '--threads', dest='threads_num',
              default=60, type='int',
              help='Number of threads. default = 60')
    parser.add_option('-f', '--file', dest='names_file', default='dict/subnames.txt',
              type='string', help='Dict file used to brute sub names')
    parser.add_option('-i', '--ignore-intranet', dest='i', default=False, action='store_true',
              help='Ignore domains pointed to private IPs')
    parser.add_option('-o', '--output', dest='output', default=None,
              type='string', help='Output file name. default is {target}.txt')

(options, args) = parser.parse_args()
    if len(args) < 1:
        parser.print_help()
        sys.exit(0)

d = DNSBrute(target=args[0], names_file=options.names_file,
                 ignore_intranet=options.i,
                 threads_num=options.threads_num,
                 output=options.output)
    d.run()
    while threading.activeCount() > 1:
        time.sleep(0.1)

摘自:李姐姐的博客

暴力枚举N级子域名的更多相关文章

  1. 51Nod 1158 全是1的最大子矩阵 —— 预处理 + 暴力枚举 or 单调栈

    题目链接:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1158 1158 全是1的最大子矩阵  基准时间限制:1 秒 空 ...

  2. [Unity3D]巧妙利用父级子级实现Camera场景平面漫游

    本文系作者原创,转载请注明出处 入门级的笔者想了一上午才搞懂那个欧拉角的Camera旋转..=.= 在调试场景的时候,每次都本能的按下W想前进,但是这是不可能的(呵呵) 于是便心血来潮想顺便添加个Ke ...

  3. CodeForces 742B Arpa’s obvious problem and Mehrdad’s terrible solution (暴力枚举)

    题意:求定 n 个数,求有多少对数满足,ai^bi = x. 析:暴力枚举就行,n的复杂度. 代码如下: #pragma comment(linker, "/STACK:1024000000 ...

  4. 2014牡丹江网络赛ZOJPretty Poem(暴力枚举)

    /* 将给定的一个字符串分解成ABABA 或者 ABABCAB的形式! 思路:暴力枚举A, B, C串! */ 1 #include<iostream> #include<cstri ...

  5. HNU 12886 Cracking the Safe(暴力枚举)

    题目链接:http://acm.hnu.cn/online/?action=problem&type=show&id=12886&courseid=274 解题报告:输入4个数 ...

  6. 51nod 1116 K进制下的大数 (暴力枚举)

    题目链接 题意:中文题. 题解:暴力枚举. #include <iostream> #include <cstring> using namespace std; ; ; ch ...

  7. Windows下Apache服务器中自动配置二级子域名

    今天我们介绍的这个办法,只需要简单修改 httpd-vhosts.conf 文件,配合 .htaccess 文件即可实现自动配置二级域名. 我们这里以 wpchina.com 为例,以下代码中的 wp ...

  8. Codeforces Round #349 (Div. 1) B. World Tour 最短路+暴力枚举

    题目链接: http://www.codeforces.com/contest/666/problem/B 题意: 给你n个城市,m条单向边,求通过最短路径访问四个不同的点能获得的最大距离,答案输出一 ...

  9. bzoj 1028 暴力枚举判断

    昨天梦到这道题了,所以一定要A掉(其实梦到了3道,有两道记不清了) 暴力枚举等的是哪张牌,将是哪张牌,然后贪心的判断就行了. 对于一个状态判断是否为胡牌,1-n扫一遍,然后对于每个牌,先mod 3, ...

随机推荐

  1. Linux简介及常用命令使用3--vi编辑器

    1.进入vi的命令 vi filename :打开或新建文件,并将光标置于第一行首 [新建文件]vi +n filename :打开文件,并将光标置于第n行首 [比如:某个shell报错的行数时使用] ...

  2. Silicon Labs电视调谐器 si2151

    随着数字电视与数模混合电视在全球范围内的逐步普及,人们对于电视机的功能要求也随之不断攀升,进而对整个电视芯片行业造成了在价格与功耗等方面的强烈冲击. 而中国作为连续四年取得全球电视出货量第一的“电视大 ...

  3. linux下的一些操作(持续更新)

    文件操作 创建文件夹: mkdir 文件夹名称 查看当前目录的文件夹及文件:ls 参看当前文件夹下的所有文件及信息: ls -l 删除空文件夹:rmdir 文件夹名称 删除非空文件夹:rm rf 文件 ...

  4. ANSYS17.0详细安装图文教程

    ANSYS 17.0是ANSYS的最新版.下面以图文方式详细描述该软件的安装过程. 1 安装前的准备 安装之前需要做的准备工作: 在硬盘上腾出30G的空间来.(视安装模块的多少,完全安装可能需要二十多 ...

  5. Linux吃掉我的内存

    在Windows下资源管理器查看内存使用的情况,如果使用率达到80%以上,再运行大程序就能感觉到系统不流畅了,因为在内存紧缺的情况下使用交换分区,频繁地从磁盘上换入换出页会极大地影响系统的性能.而当我 ...

  6. Bootstrap CSS 表单

    表单布局 Bootstrap 提供了下列类型的表单布局: 垂直表单(默认) 内联表单 水平表单 垂直或基本表单 基本的表单结构是 Bootstrap 自带的,个别的表单控件自动接收一些全局样式.下面列 ...

  7. es6学习笔记2-解构赋值

    解构赋值基本概论就按照一定的模式通过数组或者对象对一组变量进行赋值的过程. 1.通过数组对变量进行赋值: /*通过这种方式赋值要注意左右两边的结构模式要一样,在赋值的时候,根据位置进行赋值对应模式.* ...

  8. [tem]RMQ(st)

    倍增思想 代码中有两个测试 #include <iostream> #include <cmath> using namespace std; const int N=1e5; ...

  9. Log4j

    [1]从零开始 a). 新建Java Project>>新建package>>新建java类: b). import jar包(一个就够),这里我用的是log4j-1.2.14 ...

  10. 第1章 重构,第一个案例(2):分解并重组statement函数

    2. 分解并重组statement (1)提炼switch语句到独立函数(amountFor)和注意事项. ①先找出函数内的局部变量和参数:each和thisAmount,前者在switch语句内未被 ...