#!/usr/bin/python

import time
import argparse
import ipcalc
from socket import *
import ssl
import M2Crypto
import OpenSSL
import csv
import sys
import threading

subnet=""
ports=""
host=""

parser = argparse.ArgumentParser(prog='Scanner.')
parser.add_argument('-s', action="store", help='subnet')
parser.add_argument('-host', action="store", help='host')
parser.add_argument('-p', action="store", help='ports')

args = parser.parse_args()
if len(sys.argv[1:])==0:
	print "Choose a -s or -host"
	print "-s for subnet"
	print "-host for single host"
	print "-p for ports"
	exit()

subnet=args.s
host=args.host
ports=args.p.split(",")

setdefaulttimeout(3)

threads = []
maxcount=256
counter=0
threadcount=0

def scanner(host,port):
	global threadcount
	global writer
	threadcount += 1
	try:
		cert = ssl.get_server_certificate((str(host), int(port)))
		x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
		writer.writerow({'HOST': str(host), 'PORT': str(port), 'EXPIRED': format(x509.has_expired()), 'VALID FROM': format(x509.get_notBefore()), 'VALID UNTIL': format(x509.get_notAfter())})
	except (error, timeout) as err:
		a=error
	threadcount -= 1

with open('hosts.csv', 'w') as hostfile:
	fieldnames = ['HOST', 'PORT', 'EXPIRED', 'VALID FROM', 'VALID UNTIL']
	writer = csv.DictWriter(hostfile, fieldnames=fieldnames)
	writer.writeheader()

	if subnet != None:
		for host in ipcalc.Network(subnet):
			for port in ports:
				if counter<maxcount:
					t = threading.Thread(target=scanner, args=(host,port,))
					threads.append(t)
					t.start()
					counter += 1
				else:
					counter=0
					time.sleep(5)
	else:
		for port in ports:
			if counter<maxcount:
				t = threading.Thread(target=scanner, args=(host,port,))
				threads.append(t)
				t.start()
				counter += 1
			else:
				counter=0
				time.sleep(5)

	while (t.isAlive()):
		print "waiting for %d threads to end" % threadcount
		time.sleep(1)
