本文整理汇总了Python中ssl.get_server_certificate函数的典型用法代码示例。如果您正苦于以下问题:Python get_server_certificate函数的具体用法?Python get_server_certificate怎么用?Python get_server_certificate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_server_certificate函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:changyc,项目名称:Overlord,代码行数:32,代码来源:ovl.py
示例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)
开发者ID:kracekumar,项目名称:clay,代码行数:7,代码来源:http.py
示例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
开发者ID:jakubd,项目名称:centinel,代码行数:59,代码来源:tls.py
示例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)
开发者ID:ParvJain,项目名称:uber-api-client,代码行数:8,代码来源:uberapi.py
示例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)
开发者ID:kewisch,项目名称:lightning-connector-automation,代码行数:8,代码来源:certificates.py
示例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")
开发者ID:ptzimmerman,项目名称:certsym,代码行数:56,代码来源:CertUtility_v0.3.py
示例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))
开发者ID:msurovcak,项目名称:pulp,代码行数:11,代码来源:urllib2_utils.py
示例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')
开发者ID:dam09fr,项目名称:updatengine-client,代码行数:12,代码来源:uecommunication.py
示例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)
开发者ID:Kallerami,项目名称:jambot,代码行数:33,代码来源:tools.py
示例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
开发者ID:chrismaddalena,项目名称:viper,代码行数:27,代码来源:verification.py
示例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!"
开发者ID:marcinguy,项目名称:pscanner-nc,代码行数:27,代码来源:pscanner-nc.py
示例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
开发者ID:mushorg,项目名称:glastopf,代码行数:27,代码来源:rfi.py
示例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
开发者ID:nocl,项目名称:calculate-3-console,代码行数:35,代码来源:client_class.py
示例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
开发者ID:421662093,项目名称:koudaizhuanjia,代码行数:35,代码来源:api_requestor.py
示例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')
开发者ID:skamithi,项目名称:pywikibot-core,代码行数:28,代码来源:http_tests.py
示例16: main
def main(argv):
if len(argv) != 1 and len(argv) != 2:
print "Usage: pin.py [<certificate_path> | <host> <port>]"
return
if (len(argv) == 1):
cert = X509.load_cert(argv[0])
else:
peerCert = ssl.get_server_certificate((argv[0], int(argv[1])))
cert = X509.load_cert_string(peerCert)
pubkey = cert.get_pubkey().as_der()
digest = hashlib.sha256()
digest.update(pubkey)
sha256 = digest.digest()
print "Calculating PIN for certificate: " + cert.get_subject().as_text()
print "\n"
print "Public Key Pins:"
print "----------------"
print "SHA256:" + binascii.hexlify(sha256)
print "PLAIN:" + binascii.hexlify(pubkey)
print "\n"
print "Certificate Pins:"
print "-----------------"
print "CERTSHA256:" + cert.get_fingerprint('sha256')
print "CERTPLAIN:" + binascii.hexlify(cert.as_der())
开发者ID:Flowdalic,项目名称:java-pinning,代码行数:27,代码来源:pin.py
示例17: 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:
sys.exit()
else:
import time
time.sleep(1)
try:
self.sock = ssl.wrap_socket(
sock,
certfile=self.cert_file,
keyfile=self.key_file,
ca_certs=root_cert,
ssl_version=ssl.PROTOCOL_SSLv23,
cert_reqs=ssl.CERT_REQUIRED,
)
dercert_after_connect = self.sock.getpeercert(True)
cert_after_connect = ssl.DER_cert_to_PEM_cert(dercert_after_connect)
if not server_cert == cert_after_connect:
print "\n" + _("WARNING! %s trying to replace the certificate!") % self.host + "\n"
self.sock.close()
return 2
return 0
except:
return 1
开发者ID:nocl,项目名称:calculate-3-core,代码行数:35,代码来源:client_class.py
示例18: check_virtual_host_certificate
def check_virtual_host_certificate(step):
for host_hash in step.hashes:
obj = getattr(world, host_hash['source_name'])
cert_key = DEFAULT_SSL_CERTS.get(host_hash['key'])
# hostname handler
if host_hash['source'] == 'domain':
key = cert_key.get('key_name')
url = 'https://%s' % obj.name
for _ in xrange(10):
try:
res = requests.get(url, verify=key)
LOG.debug('Remote host %s request result: %s' % (url, res.text))
break
except exceptions.SSLError as e:
raise RuntimeError('Can not verify remote cert with local key: %s\n%s' % (key, e.message))
except Exception as e:
LOG.error('%s' % e.message)
time.sleep(3)
else:
raise AssertionError('Can not retrieve content from remote host: %s.' % url)
# ip handler
elif host_hash['source'] == 'server':
server_cert = ssl.get_server_certificate((obj.public_ip, 443))
LOG.debug('Server %s SSL certifacate: %s' % (obj.public_ip, server_cert))
assert server_cert == cert_key.get('cert'), 'Sever %s certificate do not match local' % obj.public_ip
开发者ID:Scalr,项目名称:revizor-tests,代码行数:25,代码来源:common_steps.py
示例19: install_trusted_ca
def install_trusted_ca(self):
'''
Add the CA that signed the certificate for self.url as trusted.
'''
import ssl
import subprocess
# parse the url
res = urlparse(self.url)
if res.scheme.lower() != "https":
return
port = res.port or 443
# get the PEM-encoded certificate
cert = ssl.get_server_certificate((res.hostname, port))
# the returned cert maybe messed up because of python-ssl bug Issue8086
if not cert.endswith("\n-----END CERTIFICATE-----\n"):
cert = cert.replace("-----END CERTIFICATE-----",
"\n-----END CERTIFICATE-----\n")
# dump it in the directory, and run make
with open(os.path.join(settings.XMLRPC_TRUSTED_CA_PATH,
res.hostname+"-ca.crt"),
'w') as cert_file:
cert_file.write(cert)
# TODO: Don't run make here. Do the linking manually.
subprocess.Popen(['make', '-C', settings.XMLRPC_TRUSTED_CA_PATH],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
开发者ID:CarolinaFernandez,项目名称:ocf-expedient-ro,代码行数:34,代码来源:models.py
示例20: test_revoked_cert_is_revoked
def test_revoked_cert_is_revoked(self):
hostname = "revoked.stripe.com"
cert = ssl.get_server_certificate((hostname, 444))
der_cert = ssl.PEM_cert_to_DER_cert(cert)
self.assertRaises(APIError,
lambda: certificate_blacklist.verify(
hostname, der_cert))
开发者ID:ApertureTS,项目名称:360ISS,代码行数:7,代码来源:test_blacklist.py
注:本文中的ssl.get_server_certificate函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论