initial commit
[cert-scanner.git] / scanner.py
1 #!/usr/bin/python
2
3 import time
4 import argparse
5 import ipcalc
6 from socket import *
7 import ssl
8 import M2Crypto
9 import OpenSSL
10 import csv
11 import sys
12 import threading
13
14 subnet=""
15 ports=""
16 host=""
17
18 parser = argparse.ArgumentParser(prog='Scanner.')
19 parser.add_argument('-s', action="store", help='subnet')
20 parser.add_argument('-host', action="store", help='host')
21 parser.add_argument('-p', action="store", help='ports')
22
23 args = parser.parse_args()
24 if len(sys.argv[1:])==0:
25         print "Choose a -s or -host"
26         print "-s for subnet"
27         print "-host for single host"
28         print "-p for ports"
29         exit()
30
31 subnet=args.s
32 host=args.host
33 ports=args.p.split(",")
34
35 setdefaulttimeout(3)
36
37 threads = []
38 maxcount=256
39 counter=0
40 threadcount=0
41
42 def scanner(host,port):
43         global threadcount
44         global writer
45         threadcount += 1
46         try:
47                 cert = ssl.get_server_certificate((str(host), int(port)))
48                 x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
49                 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())})
50         except (error, timeout) as err:
51                 a=error
52         threadcount -= 1
53
54 with open('hosts.csv', 'w') as hostfile:
55         fieldnames = ['HOST', 'PORT', 'EXPIRED', 'VALID FROM', 'VALID UNTIL']
56         writer = csv.DictWriter(hostfile, fieldnames=fieldnames)
57         writer.writeheader()
58
59         if subnet != None:
60                 for host in ipcalc.Network(subnet):
61                         for port in ports:
62                                 if counter<maxcount:
63                                         t = threading.Thread(target=scanner, args=(host,port,))
64                                         threads.append(t)
65                                         t.start()
66                                         counter += 1
67                                 else:
68                                         counter=0
69                                         time.sleep(5)
70         else:
71                 for port in ports:
72                         if counter<maxcount:
73                                 t = threading.Thread(target=scanner, args=(host,port,))
74                                 threads.append(t)
75                                 t.start()
76                                 counter += 1
77                         else:
78                                 counter=0
79                                 time.sleep(5)
80
81         while (t.isAlive()):
82                 print "waiting for %d threads to end" % threadcount
83                 time.sleep(1)