本文整理匯總了Python中ssl.get_server_certificate方法的典型用法代碼示例。如果您正苦於以下問題:Python ssl.get_server_certificate方法的具體用法?Python ssl.get_server_certificate怎麽用?Python ssl.get_server_certificate使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類ssl
的用法示例。
在下文中一共展示了ssl.get_server_certificate方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: process_host
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import get_server_certificate [as 別名]
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)
示例2: ssl_grabber
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import get_server_certificate [as 別名]
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
示例3: _certificate_required
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import get_server_certificate [as 別名]
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
示例4: sslGrabber
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import get_server_certificate [as 別名]
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
示例5: get_ssl_certificate
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import get_server_certificate [as 別名]
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
示例6: tls
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import get_server_certificate [as 別名]
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)
示例7: in_abuse_list
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import get_server_certificate [as 別名]
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
示例8: _check_ssl_cert
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import get_server_certificate [as 別名]
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)
示例9: get_server_certificate
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import get_server_certificate [as 別名]
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
示例10: get_socket
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import get_server_certificate [as 別名]
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)
示例11: fetch
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import get_server_certificate [as 別名]
def fetch(self):
self.certinfo = ssl.get_server_certificate((self.ip, self.port))
示例12: org_finder
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import get_server_certificate [as 別名]
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
示例13: process
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import get_server_certificate [as 別名]
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" : [] }
示例14: module_run
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import get_server_certificate [as 別名]
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)
示例15: getcert
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import get_server_certificate [as 別名]
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