Python ssl.get_server_certificate() Examples
The following are 29
code examples of ssl.get_server_certificate().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
ssl
, or try the search function
.
Example #1
Source File: cert.py From netpwn with GNU General Public License v3.0 | 7 votes |
def ssl_cert(): """Get the ssl cert of a website.""" print colored('Enter a URL to get its SSL cert', 'green') target_url = raw_input(colored('(netpwn: ssl_cert) > ', 'red')) try: cert = ssl.get_server_certificate((target_url, 443)) ctx = ssl.create_default_context() socks = socket.socket() sock = ctx.wrap_socket(socks, server_hostname=target_url) sock.connect((target_url, 443)) certs = sock.getpeercert() subject = dict(x[0] for x in certs['subject']) country = subject['countryName'] issued_to = subject['commonName'] organization = subject['organizationName'] location = subject['stateOrProvinceName'] issuer = dict(x[0] for x in certs['issuer']) issued_by = issuer['commonName'] print colored(cert, 'green') print colored('Country: ' + country, 'green') print colored('Issued to: ' + issued_to, 'green') print colored('Organization: ' + organization, 'green') print colored('Province: ' + location, 'green') print colored('Issued by: ' + issued_by, 'green') print ' ' except socket.error: print colored('Unknown host: ' + target_url, 'yellow') except KeyError: print colored('No SSL cert', 'yellow')
Example #2
Source File: detect_tls.py From roca with MIT License | 7 votes |
def process_host(self, host_spec, name, line_idx=0): """ One host spec processing :param host_spec: :param name: :param line_idx: :return: """ try: parts = host_spec.split(':', 1) host = parts[0].strip() port = parts[1] if len(parts) > 1 else 443 pem_cert = self.get_server_certificate(host, port) if pem_cert: sub = self.roca.process_pem_cert(pem_cert, name, line_idx) return sub except Exception as e: logger.error('Error in file processing %s (%s) : %s' % (host_spec, name, e)) self.roca.trace_logger.log(e)
Example #3
Source File: hosthunter.py From AttackSurfaceMapper with GNU General Public License v3.0 | 7 votes |
def ssl_grabber(resolved_ip, port): try: cert = ssl.get_server_certificate((resolved_ip.address, port)) x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) cert_hostname = x509.get_subject().CN # Add New HostNames to List for host in cert_hostname.split('\n'): # print(host) if (host == "") or (host in resolved_ip.hostname): pass else: try: resolved_ip.hostname.append(host) except: pass except (urllib3.exceptions.ReadTimeoutError, requests.ConnectionError, urllib3.connection.ConnectionError, urllib3.exceptions.MaxRetryError, urllib3.exceptions.ConnectTimeoutError, urllib3.exceptions.TimeoutError, socket.error, socket.timeout) as e: pass # r_dns Function
Example #4
Source File: hosthunter.py From HostHunter with MIT License | 7 votes |
def sslGrabber(hostx,port): try: cert=ssl.get_server_certificate((hostx.address, port)) x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) cert_hostname=x509.get_subject().CN # Add New HostNames to List if cert_hostname is not None: for host in cert_hostname.split('\n'): if (host=="") or (host in hostx.hname): pass else: hostx.hname.append(host) except (urllib3.exceptions.ReadTimeoutError,requests.ConnectionError,urllib3.connection.ConnectionError,urllib3.exceptions.MaxRetryError,urllib3.exceptions.ConnectTimeoutError,urllib3.exceptions.TimeoutError,socket.error,socket.timeout) as e: pass # queryAPI Function
Example #5
Source File: transports.py From pyxcli with Apache License 2.0 | 7 votes |
def _certificate_required(cls, hostname, port=XCLI_DEFAULT_PORT, ca_certs=None, validate=None): ''' returns true if connection should verify certificate ''' if not ca_certs: return False xlog.debug("CONNECT SSL %s:%s, cert_file=%s", hostname, port, ca_certs) certificate = ssl.get_server_certificate((hostname, port), ca_certs=None) # handle XIV pre-defined certifications # if a validation function was given - we let the user check # the certificate himself, with the user's own validate function. # if the validate returned True - the user checked the cert # and we don't need check it, so we return false. if validate: return not validate(certificate) return True
Example #6
Source File: network.py From ws-backend-community with GNU General Public License v3.0 | 6 votes |
def get_ssl_certificate(self, ssl_version=None): """ Get an OpenSSL cryptographic PEM certificate from the endpoint using the specified SSL version. :param ssl_version: The SSL version to connect with. If None, then let OpenSSL negotiate which protocol to use. :return: A tuple containing (1) the certificate string and (2) an OpenSSL cryptographic PEM certificate from the endpoint. """ try: if ssl_version is not None: cert = ssl.get_server_certificate((self.address, self.port), ssl_version=getattr(ssl, ssl_version)) else: cert = ssl.get_server_certificate((self.address, self.port)) return cert, OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) except ssl.SSLError as e: raise SslCertificateRetrievalFailedError( message="SSL error thrown when retrieving SSL certificate: %s." % (e,) ) # Protected Methods # Private Methods
Example #7
Source File: sslscan.py From NoobSec-Toolkit with GNU General Public License v2.0 | 6 votes |
def getcert(a): """Get SSL Cert CN""" refPorts = open('config/ports.txt', 'r').readlines() for port in refPorts: # Make sure we don't have any extra characters like \n or \r port = port.rstrip() try: # time to connect! cert = ssl.get_server_certificate((a, port)) except Exception, e: # If it can't connect go to the next iteration so we don't waste time continue try: # use openssl to pull cert information c = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) subj = c.get_subject() comp = subj.get_components() for data in comp: if 'CN' in data: out[a] = a,data[1] elif 'CN' not in data: continue else: continue except Exception,e: # if openssl fails to get information, return nothing continue
Example #8
Source File: sslscan.py From NoobSec-Toolkit with GNU General Public License v2.0 | 5 votes |
def getcert(a): """Get SSL Cert CN""" refPorts = open('config/ports.txt', 'r').readlines() for port in refPorts: # Make sure we don't have any extra characters like \n or \r port = port.rstrip() try: # time to connect! cert = ssl.get_server_certificate((a, port)) except Exception, e: # If it can't connect go to the next iteration so we don't waste time continue try: # use openssl to pull cert information c = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) subj = c.get_subject() comp = subj.get_components() for data in comp: if 'CN' in data: out[a] = a,data[1] elif 'CN' not in data: continue else: continue except Exception,e: # if openssl fails to get information, return nothing continue
Example #9
Source File: certificates.py From kube-hunter with Apache License 2.0 | 5 votes |
def execute(self): try: logger.debug("Passive hunter is attempting to get server certificate") addr = (str(self.event.host), self.event.port) cert = ssl.get_server_certificate(addr) except ssl.SSLError: # If the server doesn't offer SSL on this port we won't get a certificate return self.examine_certificate(cert)
Example #10
Source File: __init__.py From runbook with Apache License 2.0 | 5 votes |
def _check(jdata, logger): """Checks server SSL certificate for expiry.""" hostname = jdata['data']['hostname'] port = int(jdata['data'].get('port', 443)) num_days = int(jdata['data'].get('num_days', 7)) cert = ssl.get_server_certificate( (hostname, port), ssl_version=ssl.PROTOCOL_TLSv1) x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) expiry_date = x509.get_notAfter() assert expiry_date, "Cert doesn't have an expiry date." expiry = datetime.datetime.strptime(expiry_date[:8], '%Y%m%d') now = datetime.datetime.now() days_left = (expiry - now).days logger.debug('Days left in cert expiry: %d' % days_left) return days_left > num_days
Example #11
Source File: __init__.py From runbook with Apache License 2.0 | 5 votes |
def _check(jdata, logger): """Checks server SSL certificate for correct CN.""" host = jdata['data']['host'] port = int(jdata['data'].get('port', 443)) expected_hostname = jdata['data']['expected_hostname'] cert = ssl.get_server_certificate( (host, port), ssl_version=ssl.PROTOCOL_TLSv1) x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) actual_hostname = x509.get_subject().CN logger.debug('Hostname in certificate: %s' % actual_hostname) assert actual_hostname == expected_hostname, "Hostname doesn't match." return True
Example #12
Source File: verification.py From ODIN with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_certificate(target): """Attempt to collect SSL/TLS certificate information for the given host. Parameters: target The domain name to be used for certificate collection """ # Attempt to connect over port 443 try: cert = ssl.get_server_certificate((target,443)) # If it can't connect, return nothing/fail except: return None # Try to use OpenSSL to pull certificate information try: certificate = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,cert) subj = certificate.get_subject() comp = subj.get_components() for i in comp: if 'CN' in i[0].decode("utf-8"): return i[1].decode("utf-8") elif 'CN' not in i[0].decode("utf-8"): continue else: return None # If OpenSSL fails to get information, return nothing/fail except: return None
Example #13
Source File: localToRemoteConnectManger.py From DDDProxy with Apache License 2.0 | 5 votes |
def fetchRemoteCert(self, remoteServerHost, remoteServerPort): ok = False remoteServerConnecter._createCertLock.acquire() certPath = self.SSLLocalCertPath(remoteServerHost, remoteServerPort) try: if not os.path.exists(certPath): cert = ssl.get_server_certificate(addr=(remoteServerHost, remoteServerPort)) f = open(certPath, "wt") f.write(cert) f.close() ok = True except: log.log(3, remoteServerHost, remoteServerPort) remoteServerConnecter._createCertLock.release() return ok
Example #14
Source File: connection.py From scalyr-agent-2 with Apache License 2.0 | 5 votes |
def _validate_chain_openssl(self): """Validate server certificate chain using openssl system callout""" # fetch end-entity certificate and write to tempfile end_entity_pem = ssl.get_server_certificate((self._host, self._port)) try: end_entity_pem_tempfile_fd, end_entity_pem_tempfile_path = mkstemp() # NOTE: We close the fd here because we open it again below. This way file deletion at # the end works correctly on Windows. os.close(end_entity_pem_tempfile_fd) with os.fdopen(end_entity_pem_tempfile_fd, "w") as fp: fp.write(end_entity_pem) # invoke openssl # root_certs = '/usr/share/scalyr-agent-2/certs/ca_certs.crt' # intermediate_certs = '/usr/share/scalyr-agent-2/certs/intermediate_certs.pem' cmd = [ "openssl", "verify", "-CAfile", self._ca_file, "-untrusted", self._intermediate_certs_file, end_entity_pem_tempfile_path, ] log.debug("Validating server certificate chain via: %s" % cmd) proc = subprocess.Popen( args=" ".join(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, ) out, err = proc.communicate() returncode = proc.returncode if returncode != 0: raise CertValidationError(err.strip()) log.info("Scalyr server cert chain successfully validated via openssl") finally: # delete temp file os.remove(end_entity_pem_tempfile_path)
Example #15
Source File: __init__.py From lokey with GNU General Public License v3.0 | 5 votes |
def tls(ctx, domain_name): """Get the TLS certificate for a domain. Example: $ lokey fetch tls gliderlabs.com """ try: cert = stdlib_ssl.get_server_certificate((domain_name, 443)) click.echo(cert) except: msg =("Unable to fetch key from {}, " "is that domain configured for TLS?").format(domain_name) raise click.ClickException(msg)
Example #16
Source File: ssl_scan.py From recon-ng-marketplace with GNU General Public License v3.0 | 5 votes |
def module_run(self, hosts): cn_regex_pat = r'.*CN=(.+?)(,|$)' dn_regex_pat = r'^(?!:\/\/)([a-zA-Z0-9-_]+\.)*[a-zA-Z0-9][a-zA-Z0-9-_]+\.[a-zA-Z]{2,11}?$' for host in hosts: setdefaulttimeout(10) ip, port = host.split(':') try: cert = ssl.get_server_certificate((ip, port), ssl_version=ssl.PROTOCOL_TLS) except (ssl.SSLError, ConnectionResetError, ConnectionRefusedError, ssl.SSLEOFError, OSError): self.alert(f"This is not a proper HTTPS service: {ip}:{port}") continue except timeout: self.alert(f"Timed out connecting to host {ip}:{port}") continue x509 = M2Crypto.X509.load_cert_string(cert) regex = re.compile(cn_regex_pat) commonname = regex.search(x509.get_subject().as_text()).group(1).lower() if re.match(dn_regex_pat, commonname): self.output(f"Updating ports table for {ip} to include host {commonname}") self.query('UPDATE ports SET ip_address=?, host=?, port=?, protocol=? WHERE ip_address=?', (ip, commonname, port, 'tcp', ip)) else: self.alert(f"Not a valid Common Name: {commonname}") try: subaltname = x509.get_ext('subjectAltName').get_value().split(',') except LookupError: continue for san in subaltname: san = san.split(':')[1].lower() if re.match(dn_regex_pat, san): self.insert_hosts(host=san)
Example #17
Source File: ssl.py From og-miner with MIT License | 5 votes |
def process(self, profile, state, vertex): if 'type' not in vertex: return { 'error' : "No vertex type defined!" } properties = dict() if vertex['type'] == "domain": try: begin = time.time() properties['content'] = ssl.get_server_certificate((vertex['id'], self.ssl_port)) properties['time'] = time.time() - begin except Exception as e: properties['error'] = str(e) return { "properties": properties, "neighbors" : [] }
Example #18
Source File: hosthunter.py From AttackSurfaceMapper with GNU General Public License v3.0 | 5 votes |
def org_finder(hostx): target = hostx.primary_domain try: cert = ssl.get_server_certificate((target, 443)) x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) orgName = x509.get_subject().organizationName unit = x509.get_subject().organizationalUnitName hostx.orgName = str(orgName) except: pass # dnsloopkup Function
Example #19
Source File: cert.py From certmon with GNU General Public License v2.0 | 5 votes |
def fetch(self): self.certinfo = ssl.get_server_certificate((self.ip, self.port))
Example #20
Source File: interface.py From encompass with GNU General Public License v3.0 | 5 votes |
def get_socket(self): if self.use_ssl: cert_path = os.path.join( self.config.path, 'certs', self.host) if not os.path.exists(cert_path): is_new = True s = self.get_simple_socket() if s is None: return # try with CA first try: s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv23, cert_reqs=ssl.CERT_REQUIRED, ca_certs=ca_path, do_handshake_on_connect=True) except ssl.SSLError, e: s = None if s and self.check_host_name(s.getpeercert(), self.host): print_error("SSL certificate signed by CA:", self.host) return s # get server certificate. # Do not use ssl.get_server_certificate because it does not work with proxy s = self.get_simple_socket() try: s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv23, cert_reqs=ssl.CERT_NONE, ca_certs=None) except ssl.SSLError, e: print_error("SSL error retrieving SSL certificate:", self.host, e) return dercert = s.getpeercert(True) s.close() cert = ssl.DER_cert_to_PEM_cert(dercert) # workaround android bug cert = re.sub("([^\n])-----END CERTIFICATE-----","\\1\n-----END CERTIFICATE-----",cert) temporary_path = cert_path + '.temp' with open(temporary_path,"w") as f: f.write(cert)
Example #21
Source File: detect_tls.py From roca with MIT License | 5 votes |
def get_server_certificate(self, host, port): """ Gets the remote x.509 certificate :param host: :param port: :return: """ logger.info("Fetching server certificate from %s:%s" % (host,port)) try: return get_server_certificate((host, int(port))) except Exception as e: logger.error('Error getting server certificate from %s:%s: %s' % (host, port, e)) return False
Example #22
Source File: api_requestor.py From shippo-python-client with MIT License | 5 votes |
def _check_ssl_cert(self): """Preflight the SSL certificate presented by the backend. This isn't 100% bulletproof, in that we're not actually validating the transport used to communicate with Shippo, merely that the first attempt to does not use a revoked certificate. Unfortunately the interface to OpenSSL doesn't make it easy to check the certificate before sending potentially sensitive data on the wire. This approach raises the bar for an attacker significantly.""" from shippo.config import verify_ssl_certs if verify_ssl_certs and not self._CERTIFICATE_VERIFIED: uri = urllib.parse.urlparse(shippo.config.api_base) try: certificate = ssl.get_server_certificate( (uri.hostname, uri.port or 443)) der_cert = ssl.PEM_cert_to_DER_cert(certificate) except socket.error as e: raise error.APIConnectionError(e) except TypeError: # The Google App Engine development server blocks the C socket # module which causes a type error when using the SSL library if ('APPENGINE_RUNTIME' in os.environ and 'Dev' in os.environ.get('SERVER_SOFTWARE', '')): self._CERTIFICATE_VERIFIED = True warnings.warn( 'We were unable to verify Shippo\'s SSL certificate ' 'due to a bug in the Google App Engine development ' 'server. Please alert us immediately at ' 'suppgoshippo.compo.com if this message appears in your ' 'production logs.') return else: raise self._CERTIFICATE_VERIFIED = certificate_blacklist.verify( uri.hostname, der_cert)
Example #23
Source File: domain_utils.py From msticpy with MIT License | 5 votes |
def in_abuse_list(self, url_domain: str) -> Tuple: """ Validate if a domain or URL's SSL cert the abuse.ch SSL Abuse List. Parameters ---------- url_domain : str The url or domain to validate. Returns ------- result: True if valid in the list, False if not. """ try: cert = ssl.get_server_certificate((url_domain, 443)) backend = crypto.hazmat.backends.default_backend() # type: ignore x509 = crypto.x509.load_pem_x509_certificate( # type: ignore cert.encode("ascii"), backend ) cert_sha1 = x509.fingerprint( crypto.hazmat.primitives.hashes.SHA1() # type: ignore # nosec ) result = bool( self.ssl_abuse_list["SHA1"] .str.contains(cert_sha1.hex()) .any() # type: ignore ) except Exception: # pylint: disable=broad-except result = False x509 = None return result, x509
Example #24
Source File: __init__.py From kcli with Apache License 2.0 | 4 votes |
def console(self, name, tunnel=False, web=False): si = self.si dc = self.dc vcip = self.vcip vmFolder = dc.vmFolder vm = findvm(si, vmFolder, name) if vm is None: print("VM %s not found" % name) return elif vm.runtime.powerState == "poweredOff": print("VM down") return extraconfig = vm.config.extraConfig vncfound = False for extra in extraconfig: key, value = extra.key, extra.value if 'vnc' in key and 'port' in key: vncfound = True vncport = value break else: continue if vncfound: host = vm.runtime.host.name url = "vnc://%s:%s" % (host, vncport) consolecommand = "remote-viewer %s &" % (url) if web: return url if self.debug or os.path.exists("/i_am_a_container"): print(consolecommand) if not os.path.exists("/i_am_a_container"): os.popen(consolecommand) else: content = si.RetrieveContent() sgid = content.about.instanceUuid cert = get_server_certificate((self.vcip, 443)) cert_deserialize = x509.load_pem_x509_certificate(cert.encode(), default_backend()) finger_print = hexlify(cert_deserialize.fingerprint(hashes.SHA1())).decode('utf-8') sha1 = ":".join([finger_print[i: i + 2] for i in range(0, len(finger_print), 2)]) vcenter_data = content.setting vcenter_settings = vcenter_data.setting for item in vcenter_settings: key = getattr(item, 'key') if key == 'VirtualCenter.FQDN': fqdn = getattr(item, 'value') sessionmanager = si.content.sessionManager session = sessionmanager.AcquireCloneTicket() vmid = vm._moId vmurl = "https://%s/ui/webconsole.html?" % vcip vmurl += "vmId=%s&vmName=%s&serverGuid=%s&host=%s&sessionTicket=%s&thumbprint=%s" % (vmid, name, sgid, fqdn, session, sha1) if web: return vmurl if self.debug or os.path.exists("/i_am_a_container"): msg = "Open the following url:\n%s" % vmurl if os.path.exists("/i_am_a_container") else vmurl common.pprint(msg) else: common.pprint("Opening url %s" % vmurl) webbrowser.open(vmurl, new=2, autoraise=True)
Example #25
Source File: test_proxy.py From the-littlest-jupyterhub with BSD 3-Clause "New" or "Revised" License | 4 votes |
def test_manual_https(preserve_config): ssl_dir = "/etc/tljh-ssl-test" key = ssl_dir + "/ssl.key" cert = ssl_dir + "/ssl.cert" os.makedirs(ssl_dir, exist_ok=True) os.chmod(ssl_dir, 0o600) # generate key and cert check_call( [ "openssl", "req", "-nodes", "-newkey", "rsa:2048", "-keyout", key, "-x509", "-days", "1", "-out", cert, "-subj", "/CN=tljh.jupyer.org", ] ) set_config_value(CONFIG_FILE, "https.enabled", True) set_config_value(CONFIG_FILE, "https.tls.key", key) set_config_value(CONFIG_FILE, "https.tls.cert", cert) reload_component("proxy") for i in range(10): time.sleep(i) try: server_cert = ssl.get_server_certificate(("127.0.0.1", 443)) except Exception as e: print(e) else: break with open(cert) as f: file_cert = f.read() # verify that our certificate was loaded by traefik assert server_cert == file_cert # verify that we can still connect to the hub resp = send_request( url="https://127.0.0.1/hub/api", max_sleep=10, validate_cert=False ) assert resp.code == 200 # cleanup shutil.rmtree(ssl_dir) set_config_value(CONFIG_FILE, "https.enabled", False) reload_component("proxy")
Example #26
Source File: signer_certificate.py From ibmsecurity with Apache License 2.0 | 4 votes |
def _check_load(isamAppliance, kdb_id, label, server, port): """ Checks if certificate to be loaded on the Appliance exists and if so, whether it is different from the one on the remote host. If the certificate exists on the Appliance, but has a different label, we return True, so that load() takes no action. If the requested label matches an existing label on the appliance, but the certs are different, check to see if cert is expired. If so, replace cert. If not, do not replace. """ import ssl remote_cert_pem = ssl.get_server_certificate((server, port)) # Look for remote_cert_pem on in the signer certs on the appliance ret_obj = get_all(isamAppliance, kdb_id) for cert_data in ret_obj['data']: cert_id = cert_data['id'] cert_pem = get(isamAppliance, kdb_id, cert_id)['data']['contents'] if cert_id == label: # label exists on appliance already logger.debug("Comparing certificates: appliance[{0}] remote[{1}].".format(cert_pem,remote_cert_pem)) if cert_pem == remote_cert_pem: # certificate data is the same logger.debug("The certificate already exits on the appliance with the same label name and same content.") return True # both the labels and certificates match else: # Labels match, but the certs are different, so we need to update it. # However, you cannot load a cert with the same label name onto the appliance, since you get # CTGSK2021W A duplicate certificate already exists in the database. # We delete the cert from the appliance and return False to the load() function, # so that we can load the new one ret_obj = delete(isamAppliance, kdb_id, cert_id) logger.debug("Labels match, but the certs are different, so we need to update it.") return False else: if cert_pem == remote_cert_pem: # cert on the appliance, but with a different name logger.info( "The certifcate is already on the appliance, but it has a different label name. " "The existing label name is {label} and requested label name is {cert_id}".format( label=label, cert_id=cert_id)) return True return False
Example #27
Source File: util.py From pypowervm with Apache License 2.0 | 4 votes |
def validate_certificate(host, port, certpath, certext): hostname = re.sub('[:.]', '_', host) cert_file = '%s%s%s' % (certpath, hostname, certext) try: with open(cert_file, 'r') as f: # Retrieve previously trusted certificate trusted_cert = ssl.PEM_cert_to_DER_cert(f.read()) except Exception: # found no trusted certificate return False # Read current certificate from host conn = None try: # workaround for http://bugs.python.org/issue11811 # should go back to using get_server_certificate when fixed # (Issue is resolved as of python 3.3. Workaround still needed for # python 2.7 support.) # rawcert = ssl.get_server_certificate((host, port)) # current_cert = ssl.PEM_cert_to_DER_cert(rawcert) conn = socket.create_connection((host, port)) sock = ssl.wrap_socket(conn) current_cert = sock.getpeercert(True) except Exception: # couldn't get certificate from host return False finally: if conn is not None: conn.shutdown(socket.SHUT_RDWR) conn.close() # Verify certificate finger prints are the same if not (hashlib.sha1(trusted_cert).digest() == hashlib.sha1(current_cert).digest()): return False # check certificate expiration try: cert = der_decoder.decode(current_cert, asn1Spec=rfc2459.Certificate())[0] tbs = cert.getComponentByName('tbsCertificate') validity = tbs.getComponentByName('validity') not_after = validity.getComponentByName('notAfter').getComponent() not_after = dt.datetime.strptime(str(not_after), '%y%m%d%H%M%SZ') if dt.datetime.utcnow() >= not_after: LOG.warning(_('Certificate has expired.')) return False except Exception: LOG.exception('error parsing cert for expiration check') return False return True
Example #28
Source File: sslinfo.py From FinalRecon with MIT License | 4 votes |
def cert(hostname, output, data): result = {} pair = {} print ('\n' + Y + '[!]' + Y + ' SSL Certificate Information : ' + W + '\n') ctx = ssl.create_default_context() s = ctx.wrap_socket(socket.socket(), server_hostname=hostname) try: try: s.connect((hostname, 443)) info = s.getpeercert() except: info = ssl.get_server_certificate((hostname, 443)) f = open('{}.pem'.format(hostname), 'w') f.write(info) f.close() cert_dict = ssl._ssl._test_decode_cert('{}.pem'.format(hostname)) info = cert_dict os.remove('{}.pem'.format(hostname)) def unpack(v, pair): convert = False for item in v: if isinstance(item, tuple): for subitem in item: if isinstance(subitem, tuple): for elem in subitem: if isinstance(elem, tuple): unpack(elem) else: convert = True pass if convert == True: pair.update(dict([subitem])) else: pass else: print(G + '[+]' + C + ' {} : '.format(str(k)) + W + str(item)) if output != 'None': result.update({k:v}) for k, v in info.items(): if isinstance(v, tuple): unpack(v, pair) for k,v in pair.items(): print(G + '[+]' + C + ' {} : '.format(str(k)) + W + str(v)) if output != 'None': result.update({k:v}) pair.clear() else: print(G + '[+]' + C + ' {} : '.format(str(k)) + W + str(v)) if output != 'None': result.update({k:v}) except: print (R + '[-]' + C + ' SSL is not Present on Target URL...Skipping...' + W) if output != 'None': result.update({'Error':'SSL is not Present on Target URL'}) if output != 'None': cert_output(output, data, result)
Example #29
Source File: generate_html5_console.py From pyvmomi-community-samples with Apache License 2.0 | 4 votes |
def main(): """ Simple command-line program to generate a URL to open HTML5 Console in Web browser """ args = get_args() try: si = SmartConnect(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) except Exception as e: print 'Could not connect to vCenter host' print repr(e) sys.exit(1) atexit.register(Disconnect, si) content = si.RetrieveContent() vm = get_vm(content, args.name) vm_moid = vm._moId vcenter_data = content.setting vcenter_settings = vcenter_data.setting console_port = '7331' for item in vcenter_settings: key = getattr(item, 'key') if key == 'VirtualCenter.FQDN': vcenter_fqdn = getattr(item, 'value') session_manager = content.sessionManager session = session_manager.AcquireCloneTicket() vc_cert = ssl.get_server_certificate((args.host, int(args.port))) vc_pem = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, vc_cert) vc_fingerprint = vc_pem.digest('sha1') print "Open the following URL in your browser to access the " \ "Remote Console.\n" \ "You have 60 seconds to open the URL, or the session" \ "will be terminated.\n" print "http://" + args.host + ":" + console_port + "/console/?vmId=" \ + str(vm_moid) + "&vmName=" + args.name + "&host=" + vcenter_fqdn \ + "&sessionTicket=" + session + "&thumbprint=" + vc_fingerprint print "Waiting for 60 seconds, then exit" time.sleep(60) # Start program