本文整理汇总了Python中ssl.get_server_certificate函数的典型用法代码示例。如果您正苦于以下问题:Python get_server_certificate函数的具体用法?Python get_server_certificate怎么用?Python get_server_certificate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_server_certificate函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Connect
def Connect(self, host, port=_OVERLORD_HTTP_PORT, ssh_pid=None,
username=None, password=None, orig_host=None):
self._state.username = username
self._state.password = password
self._state.host = host
self._state.port = port
self._state.ssl = False
self._state.ssl_self_signed = False
self._state.orig_host = orig_host
self._state.ssh_pid = ssh_pid
self._state.selected_mid = None
tls_enabled = self._TLSEnabled()
if tls_enabled:
result = self._CheckTLSCertificate()
if not result:
if self._state.ssl_self_signed:
return ('SSLCertificateChanged', ssl.get_server_certificate(
(self._state.host, self._state.port)))
else:
return ('SSLVerifyFailed', ssl.get_server_certificate(
(self._state.host, self._state.port)))
try:
self._state.ssl = tls_enabled
UrlOpen(self._state, '%s:%d' % (host, port))
except urllib2.HTTPError as e:
return ('HTTPError', e.getcode(), str(e), e.read().strip())
except Exception as e:
return str(e)
else:
return True
示例2: https_open
def https_open(self, req):
ca_certs = config.get('http.ca_certs_file', DEFAULT_CA_CERTS)
if config.get('http.verify_server_certificates', True) and os.path.exists(ca_certs):
frags = urlparse.urlparse(req.get_full_url())
ssl.get_server_certificate((frags.hostname, frags.port or 443),
ca_certs=ca_certs)
return self.do_open(httplib.HTTPSConnection, req)
示例3: get_fingerprint
def get_fingerprint(host, port=443, external=None, log_prefix=''):
tls_error = None
fingerprint_error = None
cert = None
logging.debug("%sGetting TLS certificate "
"for %s:%d." % (log_prefix, host, port))
try:
cert = ssl.get_server_certificate((host, port),
ssl_version=ssl.PROTOCOL_TLSv1)
# if this fails, there's a possibility that SSLv3 handshake was
# attempted and rejected by the server. Use TLSv1 instead.
except ssl.SSLError:
# exception could also happen here
try:
cert = ssl.get_server_certificate((host, port),
ssl_version=ssl.PROTOCOL_SSLv23)
except Exception as exp:
tls_error = str(exp)
except Exception as exp:
tls_error = str(exp)
# this comes out as unicode, but m2crypto breaks if it gets
# something other than a string, so convert to ascii
if type(cert) == unicode:
cert = cert.encode('ascii', 'ignore')
if tls_error is None and m2crypto_imported:
try:
x509 = M2Crypto.X509.load_cert_string(cert,
M2Crypto.X509.FORMAT_PEM)
fingerprint = x509.get_fingerprint('sha1')
except Exception as exp:
fingerprint_error = str(exp)
if not m2crypto_imported:
fingerprint_error = "M2Crypto could not be imported."
# the external result is used when threading to store
# the results in the list container provided.
row = "%s:%s" % (host, port)
# handle return value based on exception types
if tls_error is None and fingerprint_error is None:
if external is not None and type(external) is dict:
external[row] = {"cert": cert,
"fingerprint": fingerprint.lower()}
return fingerprint.lower(), cert
elif tls_error is None and fingerprint_error is not None:
if external is not None and type(external) is dict:
external[row] = {"cert": cert,
"fingerprint_error": fingerprint_error}
return fingerprint_error, cert
else:
if external is not None and type(external) is dict:
external[row] = {"tls_error": tls_error,
"fingerprint_error": fingerprint_error}
return fingerprint_error, tls_error
示例4: https_open
def https_open(self, req):
ca_certs = self.SSL_CA_CERTS
frags = urlparse.urlparse(req.get_full_url())
ssl.get_server_certificate(
(frags.hostname, frags.port or 443),
ca_certs=ca_certs
)
return self.do_open(httplib.HTTPSConnection, req)
示例5: fromHost
def fromHost(host, port, certtype='U', ssl_version=None):
logging.info("Getting certificate from %s:%d" % (host, port))
if ssl_version is None:
cert = ssl.get_server_certificate((host, port))
else:
cert = ssl.get_server_certificate((host, port), ssl_version=ssl_version)
x509 = X509.load_cert_string(cert.encode('ascii', 'ignore'))
return CertOverrideEntry(host, port, x509=x509, certtype=certtype)
示例6: clickedLocal
def clickedLocal(self):
"""
docstring
"""
# Validate input and parse the URL
try:
if ( self.URLtext.get().isalpha() ) or \
( self.URLtext.get().isdigit() ):
raise ValueError
else:
self.parsedURL = urlparse(self.URLtext.get())
# print (self.parsedURL)
# print (self.parsedURL.geturl())
# print (self.parsedURL.port())
# obtain ceritificate through local interface
# this is pretty automagical, prob need to look at sockets
# how do we bind a stream to a specific interface?
print("Attempting to obtain cert on local interface "
"for %s\n" % (self.URLtext.get()))
try:
# if the user inputs www.url.com
self.cert = ssl.get_server_certificate(
(self.parsedURL.path,443))
print ("Obtained cert for %s on local interface\n" %
(self.URLtext.get()))
print (self.cert)
except:
# if the user inputs http://www.url.com
self.cert = ssl.get_server_certificate(
(self.parsedURL.netloc,443))
print ("Obtained cert for %s on local interface\n" %
(self.URLtext.get()))
print (self.cert)
# validate that the certificate has been signed by a CA?
global cert_Length
cert_Length = len(self.cert) #set global variable to length
print ("set cert_Length to ", len(self.cert))
# store cert in variable for checking
self.localcert = self.cert
# update the cert label in GUI
self.label2text.set(self.URLtext.get())
if self.vpncert:
self.certChecker()
except ValueError:
print("Input a valid URL\n")
except ConnectionRefusedError:
print("Connection refused. Check the URL.\n")
示例7: _validate_server_ssl_cert
def _validate_server_ssl_cert(self):
if not self.validate_host:
return
try:
ssl.get_server_certificate((self._real_host, self._real_port))
except ssl.SSLError:
raise InvalidHostSSLCertificate('Cannot verify host <%s> with ca cert: %s' %
(self._real_host, self.ca_cert_file))
示例8: check_ssl
def check_ssl(self, hostname, port, cafile_local):
try:
open(cafile_local,'r')
except :
print "Error in check_ssl (open function)"
raise
try:
ssl.get_server_certificate((hostname, port), ca_certs=cafile_local)
except ssl.SSLError:
print "Error in check_ssl (ssl.get_server_certificate function)"
raise ssl.SSLError('SSL cert of Host:'+str(hostname)+' Port:'+str(port)+' is invalid')
示例9: verify_ssl_cn
def verify_ssl_cn(server, port):
"""
*Availability: Must have the OpenSSL Python module installed.*
Verify the SSL certificate given by the ``server`` when connecting on the
given ``port``. This returns ``None`` if OpenSSL is not available or
'NoCertFound' if there was no certificate given. Otherwise, a two-tuple
containing a boolean of whether the certificate is valid and the
certificate information is returned.
"""
if not ssl:
return None
cert = None
for version in (ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23):
try:
cert = ssl.get_server_certificate((server, port), ssl_version=version)
break
except Exception as e:
pass
if cert is None:
return 'NoCertFound'
valid = False
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
cret_info = x509.get_subject().get_components()
cn = x509.get_subject().commonName
if cn == server:
valid = True
elif '*' in cn:
cn = cn.replace('*.', '')
if re.match('(.*)%s' % cn, server, re.IGNORECASE) is not None:
valid = True
return (valid, cret_info)
示例10: get_certificate
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
示例11: scan
def scan(d):
with term.location(*location):
print term.bold_red_on_bright_green("Scanning: "+d)
if(sslp=="yes"):
s_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = ssl.wrap_socket(s_, ca_certs='/usr/local/lib/python2.7/dist-packages/requests/cacert.pem',cert_reqs=ssl.CERT_OPTIONAL)
s.settimeout(0.1)
d=str(d)
try:
result = s.connect_ex((d, int(port)))
except Exception, e:
message = "Error: "+d.rstrip()+","+getrev(d)
message += str(e)
try:
cert = ssl.get_server_certificate((d, 443), ssl_version=ssl.PROTOCOL_TLSv1)
x509 = M2Crypto.X509.load_cert_string(cert)
r = x509.get_subject().as_text()
val = r.split(",")
for i, j in enumerate(val):
if j.find("CN=") != -1:
val[i]=j.replace("CN=","")
val[i]=val[i].strip()
message += ","+val[i]
return message
except Exception, e:
return d.rstrip()+","+getrev(d)+","+"CERT ERROR!"
示例12: download_file
def download_file(self, url):
injectd_url = self.extract_url(urllib2.unquote(url))
try:
req = urllib2.Request(injectd_url)
# Set User-Agent to look more credible
req.add_unredirected_header('User-Agent', '-')
# FIXME: We need a timeout on read here
injected_file = urllib2.urlopen(req, timeout=4).read()
# If the file is hosted on a SSL enabled host get the certificate
if re.match('^https', injectd_url, re.IGNORECASE):
proto, rest = urllib2.splittype(injectd_url)
host, rest = urllib2.splithost(rest)
host, port = urllib2.splitport(host)
if port is None:
port = 443
cert_file = ssl.get_server_certificate((host, int(port)))
cert_name = self.store_file(cert_file)
except IOError as e:
logger.exception("Failed to fetch injected file, I/O error: {0}".format(e))
# TODO: We want to handle the case where we can't download
# the injected file but pretend to be vulnerable.
file_name = None
else:
file_name, file_sha256 = self.store_file(injected_file)
return file_name, file_sha256
示例13: connect_trusted_root
def connect_trusted_root(self, sock, root_cert, crl_certs):
self.ca_path = self.cert_path + "ca/"
server_cert = ssl.get_server_certificate(addr=(self.host, self.port))
global flag
if self.cert_file:
f = verify(server_cert, crl_certs, flag)
if not f:
flag = 1
elif f == 1:
raise Exception(1)
else:
import time
time.sleep(0.1)
try:
if self.FORCE_SSL_VERSION:
add = {"ssl_version": self.FORCE_SSL_VERSION}
else:
add = {}
add["cert_reqs"] = ssl.CERT_REQUIRED
# try to use PyOpenSSL by default
if PYOPENSSL_AVAILABLE:
wrap_class = PyOpenSSLSocket
add["keyobj"] = self.keyobj
add["certobj"] = self.certobj
add["keyfile"] = self.key_file
add["certfile"] = self.cert_file
else:
wrap_class = ssl.SSLSocket
self.sock = wrap_class(sock, ca_certs=self.ca_certs, **add)
return 0
except:
return 1
示例14: _check_ssl_cert
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 Ping++, 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 pingpp import verify_ssl_certs
if verify_ssl_certs and not self._CERTIFICATE_VERIFIED:
uri = urlparse.urlparse(pingpp.api_base)
try:
certificate = ssl.get_server_certificate(
(uri.hostname, uri.port or 443), ssl_version=3)
der_cert = ssl.PEM_cert_to_DER_cert(certificate)
except socket.error, 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 util.is_appengine_dev():
self._CERTIFICATE_VERIFIED = True
warnings.warn(
'We were unable to verify Ping++\'s SSL certificate '
'due to a bug in the Google App Engine development '
'server. Please alert us immediately at '
'[email protected] if this message appears in your '
'production logs.')
return
else:
raise
示例15: test_https_cert_invalid
def test_https_cert_invalid(self):
"""Verify vikidia SSL certificate is invalid."""
try:
from pyasn1_modules import pem, rfc2459
from pyasn1.codec.der import decoder
except ImportError:
raise unittest.SkipTest('pyasn1 and pyasn1_modules not available.')
import ssl
import io
cert = ssl.get_server_certificate(addr=('en.vikidia.org', 443))
s = io.StringIO(unicode(cert))
substrate = pem.readPemFromFile(s)
cert = decoder.decode(substrate, asn1Spec=rfc2459.Certificate())[0]
tbs_cert = cert.getComponentByName('tbsCertificate')
issuer = tbs_cert.getComponentByName('issuer')
organisation = None
for rdn in issuer.getComponent():
for attr in rdn:
attr_type = attr.getComponentByName('type')
if attr_type == rfc2459.id_at_organizationName:
value, _ = decoder.decode(attr.getComponentByName('value'),
asn1Spec=rfc2459.X520name())
organisation = str(value.getComponent())
break
self.assertEqual(organisation, 'TuxFamily.org non-profit organization')