Advertisement
Guest User

Untitled

a guest
Oct 19th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.63 KB | None | 0 0
  1. import argparse
  2. from textwrap import dedent
  3. import re
  4. from collections import namedtuple
  5. from urllib.request import urlopen
  6.  
  7. from scapy.all import *
  8.  
  9.  
  10. class ScannerStatus(object):
  11. OPEN = "Open"
  12. CLOSED = "Closed"
  13. FILTERED = "Filtered"
  14.  
  15.  
  16. class Scanner(object):
  17. def __init__(self, timeout):
  18. self.timeout = timeout
  19.  
  20. def arp_ping(self, subnet):
  21. """ARP Pings entire subnet returns found in subnet."""
  22. conf.verb = 0
  23. answered, unanswered = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=subnet), timeout=self.timeout, verbose=False, inter=0.1)
  24. return [rcv.sprintf(r"%Ether.src% - %ARP.psrc%") for snd, rcv in answered]
  25.  
  26. def _tcp_default(self, dst_ip, dst_port, src_port):
  27. """Default TCP Scan."""
  28. default_scan = sr1(IP(dst=dst_ip)/TCP(sport=src_port, dport=dst_port, flags="S"), timeout=self.timeout)
  29. if default_scan is not None:
  30. if default_scan.getlayer(TCP).flags == 0x12:
  31. send_rst = sr(IP(dst=dst_ip)/TCP(sport=src_port, dport=dst_port, flags="AR"), timeout=self.timeout)
  32. return ScannerStatus.OPEN
  33. return ScannerStatus.CLOSED
  34.  
  35. def _tcp_stealth(self, dst_ip, dst_port, src_port):
  36. """Stealthy TCP Scan"""
  37. stealth_scan = sr1(IP(dst=dst_ip)/TCP(sport=src_port, dport=dst_port, flags="S"), timeout=self.timeout)
  38. if stealth_scan is not None:
  39. if stealth_scan.getlayer(TCP).flags == 0x12:
  40. send_rst = sr(IP(dst=dst_ip)/TCP(sport=src_port, dport=dst_port, flags="R"), timeout=self.timeout)
  41. return ScannerStatus.OPEN
  42. elif stealth_scan.getlayer(TCP).flags == 0x14:
  43. return ScannerStatus.CLOSED
  44. return ScannerStatus.FILTERED
  45.  
  46. def tcp(self, dst_ip, dst_port, stealth=False):
  47. """Scan TCP port for availability"""
  48. src_port = RandShort()
  49. fn = self._tcp_stealth if stealth else self._tcp_default
  50. return fn(dst_ip, dst_port, src_port)
  51.  
  52. def udp(self, dst_ip, dst_port):
  53. """Scan UDP port for availability"""
  54. udp_scan = sr1(IP(dst=dst_ip)/UDP(dport=dst_port), timeout=self.timeout)
  55. if udp_scan is not None:
  56. if udp_scan.haslayer(UDP):
  57. return 'Open'
  58. elif int(udp_scan.getlayer(ICMP).type) == 3 and int(udp_scan.getlayer(ICMP).code) == 3:
  59. return 'Closed'
  60. return 'Filtered'
  61.  
  62.  
  63. def get_ports():
  64. """Get ports from etc/services/
  65. yields a namedtuple(name, port, type)"""
  66. ports, Port = [], namedtuple('Port', ['name', 'port', 'type'])
  67. with open('/etc/services') as ports_file:
  68. lines = ports_file.readlines()
  69. for line in lines:
  70. if not line.startswith('#') and line.rstrip():
  71. _name, _port, _type = re.split('[s/]+', line.split('#', 1)[0])[:3]
  72. yield Port(_name, _port, _type)
  73.  
  74.  
  75. def parse_arguments():
  76. """Arguments parser."""
  77. parser = argparse.ArgumentParser(usage='%(prog)s [options] <subnet>',
  78. description='port scanning tool @Ludisposed',
  79. formatter_class=argparse.RawDescriptionHelpFormatter,
  80. epilog=dedent('''
  81. Examples:
  82. python port_scan.py "192.168.1.0/24" -s
  83. python port_scan.py "192.168.1.0/24" --timeout 10
  84. python port_scan.py "192.168.1.0/24 -l -s"'''))
  85. parser.add_argument('-s', '--stealth', default=False, action="store_true", help='Stealthy TCP scan')
  86. parser.add_argument('--timeout', type=int, default=2, help='Timeout parameter of scans')
  87. parser.add_argument('-l', '--log', type=str, default='', help="Log the data to a file")
  88. parser.add_argument('subnet', type=str, help='subnet in from of [ip]/[bitmask]')
  89. parser.add_argument('-O', '--os', default=False, action="store_true", help="Make fingerprint and try scan OS")
  90. return parser.parse_args()
  91.  
  92.  
  93. def main():
  94. def save_log(data):
  95. if args.log:
  96. with open(log, 'a+') as f:
  97. f.write(data + 'n')
  98.  
  99. args = parse_arguments()
  100. scanner = Scanner(args.timeout)
  101. scan_type = 'stealth' if args.stealth else 'default'
  102.  
  103. # Os - detection setup
  104. load_module("nmap")
  105. if not os.path.isfile('nmap-os-fingerprints'):
  106. open('nmap-os-fingerprints', 'wb').write(urlopen('https://raw.githubusercontent.com/nmap/nmap/9efe1892/nmap-os-fingerprints').read())
  107. conf.nmap_base = 'nmap-os-fingerprints'
  108.  
  109. network = scanner.arp_ping(args.ip_range)
  110. for connection in network:
  111. mac, ip = connection.split(' - ')
  112. print('n[!] Trying port scan of current connection with mac={} and ip={}n'.format(mac, ip))
  113.  
  114. for port in get_ports():
  115. data = ''
  116.  
  117. if port.type == 'tcp':
  118. status = scanner.tcp(ip, int(port.port), args.stealth)
  119. if status == 'Open':
  120. data = '[*] TCP {} scan: dest_ip={} port={}, service={}, status={}'.format(scan_type, ip, port.port, port.name, status)
  121. if port.type == 'udp':
  122. status = scanner.udp(ip, int(port.port))
  123. if status == 'Open':
  124. data = '[*] UDP scan: dest_ip={} port={}, service{}, status={}'.format(ip, port.port, port.name, status)
  125.  
  126. if data:
  127. save_log(data)
  128. print(data)
  129.  
  130. if args.os:
  131. data = re.findall(r"['(.*)']", nmap_fp(target))[0]
  132. if data:
  133. save_log("nOS detected: {}".format(data))
  134. print("nOS detected: {}".format(data))
  135.  
  136. if __name__ == '__main__':
  137. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement