def x509_to_dict(x509): """Parse a x509 pyopenssl object to a dictionary with keys subject, subjectAltName and optional notAfter. """ from requests.packages.urllib3.contrib.pyopenssl import get_subj_alt_name res = { 'subject': ( (('commonName', x509.get_subject().CN),), ), 'subjectAltName': [ ('DNS', value) for value in get_subj_alt_name(x509) ] } notAfter = x509.get_notAfter() if notAfter is not None: parsedtime = asn1_generaltime_to_seconds(notAfter) if parsedtime is not None: res['notAfter'] = parsedtime.strftime('%b %d %H:%M:%S %Y') if parsedtime.tzinfo is None: res['notAfter'] += ' GMT' else: # give up parsing, just set the string res['notAfter'] = notAfter return res
def https_cert_subject_alt_names(host, port): try: x509 = reqs.OpenSSL.crypto.load_certificate( reqs.OpenSSL.crypto.FILETYPE_PEM, reqs.ssl.get_server_certificate((host, port)) ) return reqs.get_subj_alt_name(x509) except: return
def checkSSLCertAltName(certFilename, altName): with open(certFilename, 'r') as fh: certData = fh.read() x509 = pyopenssl.OpenSSL.crypto.load_certificate(pyopenssl.OpenSSL.crypto.FILETYPE_PEM, certData) altNames = pyopenssl.get_subj_alt_name(x509) for _, name in altNames: if altName == name: return True return False
def check_https_alt_names(self, domain): try: x509 = reqs.OpenSSL.crypto.load_certificate( reqs.OpenSSL.crypto.FILETYPE_PEM, reqs.ssl.get_server_certificate((domain, 443)) ) for item in reqs.get_subj_alt_name(x509): if item[0].upper() == 'DNS': name = item[1].lower() if name.endswith(self.domain): sub = name[:len(name) - len(self.domain) - 1] # new sub sub = sub.replace('*', '') sub = sub.strip('.') if sub and sub not in self.found_subs and \ sub not in self.normal_names_set and sub not in self.cert_subs: self.cert_subs.add(sub) self.queue.put((0, sub)) except Exception as e: pass
def x509_to_dict(x509): """Parse a x509 pyopenssl object to a dictionary with keys subject, subjectAltName and optional notAfter. """ from requests.packages.urllib3.contrib.pyopenssl import get_subj_alt_name res = { 'subject': ((('commonName', x509.get_subject().CN), ), ), 'subjectAltName': [('DNS', value) for value in get_subj_alt_name(x509)] } notAfter = x509.get_notAfter() if notAfter is not None: parsedtime = asn1_generaltime_to_seconds(notAfter) if parsedtime is not None: res['notAfter'] = parsedtime.strftime('%b %d %H:%M:%S %Y') if parsedtime.tzinfo is None: res['notAfter'] += ' GMT' else: # give up parsing, just set the string res['notAfter'] = notAfter return res
def parse_remote_certificate(self, host, port): cert = self.load_remote_certificate(host, port) dns = reqs.get_subj_alt_name(cert) # [('C', 'US'), # ('O', 'DigiCert Inc'), # ('OU', 'www.digicert.com'), # ('CN', 'DigiCert SHA2 High Assurance Server CA')] issuer = cert.get_issuer().get_components() # [('C', 'US'), # ('ST', 'CA'), # ('L', 'Sunnyvale'), # ('O', 'Yahoo! Inc.'), # ('CN', '*.www.yahoo.com')] subject = cert.get_subject().get_components() notBefore = cert.get_notBefore() # '20170920000000Z' notAfter = cert.get_notAfter() # '20180319120000Z' # pubkey = cert.get_pubkey() # pubkey.bits() # pubkey.type() serialnumber = cert.get_serial_number() algorithm = cert.get_signature_algorithm() # cert.get_version() record = { "issuer": issuer, "subject": subject, "notBefore": notBefore, "notAfter": notAfter, "serialnumber": serialnumber, "algorithm": algorithm, "dns": dns } return record
def reslove_func(self, filename): filename_base_name = os.path.basename(filename) try: with open(filename, "rb") as f: header = f.read(4) header = binascii.hexlify(header) except FileNotFoundError: input("\n[!] File not found!") sys.exit() if header != b'50726f74': input("\nERROR: make sure it is NstatLogger log file") sys.exit() ip_list = [] dns_alt_names = [] prog_name_lst = [] revers_lookup = {} not_found = '-' choice, choose_1, choose_2 = self.choice() with open(filename, 'r') as file_in: with open('Resolved-' + filename_base_name, 'w') as file_out_csv: # csv file out writer = csv.writer(file_out_csv) if choice == 1: writer.writerows(choose_1) elif choice == 2: writer.writerows(choose_2) print('Resolving...') line_counter = 0 for lines in file_in.readlines()[3:]: #maybe -2? try: ip_addr = lines.split(',')[2] # get the ip only without the port ip_addr = ip_addr.rsplit(':', 1)[0].strip() program_name = lines.split(',')[ 5] # get the program name except BaseException: continue if ip_addr in ip_list and program_name in prog_name_lst: continue if lines.split( ',' )[2] == '': # ignoring program names with no remote ip address (e.g udp) continue else: # append program names to the prog_name_lst prog_name_lst.append(program_name) # append ip addresses to the ip_list ip_list.append(ip_addr) line_counter += 1 loop = asyncio.get_event_loop() queue = asyncio.gather(*(self.query(ip, -1) for ip in ip_list), return_exceptions=True) rev_lookup_result = loop.run_until_complete(queue) threat_crowd_api = [ f"http://www.threatcrowd.org/searchApi/v2/ip/report/?ip={ip}" for ip in ip_list ] threat_crowd_response = loop.run_until_complete( self.fetch_all(threat_crowd_api, loop)) if self.vt_api_key is not None: vt_api = [ f"https://www.virustotal.com/vtapi/v2/ip-address/report?apikey={self.vt_api_key}&ip={ip}" for ip in ip_list ] vt_response = loop.run_until_complete( self.fetch_all(vt_api, loop)) else: vt_api = [not_found for ip in ip_list] for ip, prog, rev_resolve, tc, vt in zip( ip_list, prog_name_lst, rev_lookup_result, threat_crowd_response, vt_response): indx_tc = tc.find('resolutions') indx_start_vt = vt.find('resolutions') indx_end_vt = vt.find('hashes') try: revers_lookup.update( {ip: str(rev_resolve).split(",")[1]}) except (IndexError, OSError, ValueError, aiodns.error.DNSError): revers_lookup.update({ip: not_found}) if choice == 1: if self.vt_api_key is not None: try: writer.writerows([( prog, ip, revers_lookup[ip], "{" + tc[indx_tc:], vt[indx_start_vt:indx_end_vt], )]) except BaseException: pass else: try: writer.writerows([( prog, ip, revers_lookup[ip], tc[indx_tc:], '{}', )]) except KeyError: writer.writerows([( prog, ip, revers_lookup[ip], '{}', '{}', )]) continue elif choice == 2: try: x509 = reqs.OpenSSL.crypto.load_certificate( reqs.OpenSSL.crypto.FILETYPE_PEM, reqs.ssl.get_server_certificate((ip, 443))) dns_alt_names = reqs.get_subj_alt_name(x509) writer.writerows([(prog, ip, revers_lookup[ip], dns_alt_names)]) except (socket.gaierror, ssl.SSLError, TimeoutError, ConnectionRefusedError, OSError): writer.writerows([(prog, ip, revers_lookup[ip], '-')]) continue return revers_lookup