本文整理匯總了Python中ssl.PROTOCOL_TLS屬性的典型用法代碼示例。如果您正苦於以下問題:Python ssl.PROTOCOL_TLS屬性的具體用法?Python ssl.PROTOCOL_TLS怎麽用?Python ssl.PROTOCOL_TLS使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類ssl
的用法示例。
在下文中一共展示了ssl.PROTOCOL_TLS屬性的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_context
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import PROTOCOL_TLS [as 別名]
def test_context(self):
self.client.quit()
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS)
self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE,
context=ctx)
self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
context=ctx)
self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
keyfile=CERTFILE, context=ctx)
self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT)
self.client.connect(self.server.host, self.server.port)
self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
self.client.auth()
self.assertIs(self.client.sock.context, ctx)
self.assertIsInstance(self.client.sock, ssl.SSLSocket)
self.client.prot_p()
sock = self.client.transfercmd('list')
try:
self.assertIs(sock.context, ctx)
self.assertIsInstance(sock, ssl.SSLSocket)
finally:
sock.close()
示例2: __init__
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import PROTOCOL_TLS [as 別名]
def __init__(self, destination, loop):
self.destination = destination
self.loop = loop
self._start = asyncio.Event()
self._stop = asyncio.Event()
self._terminate = asyncio.Event()
self.running = asyncio.Event()
self.stopped = asyncio.Event()
self.terminated = asyncio.Event()
if hasattr(ssl, 'PROTOCOL_TLS_SERVER'):
# python 3.6+
protocol = ssl.PROTOCOL_TLS_SERVER
elif hasattr(ssl, 'PROTOCOL_TLS'):
# python 3.5.3+
protocol = ssl.PROTOCOL_TLS
else:
# python 3.5.2
protocol = ssl.PROTOCOL_TLSv1_2
self.ssl_context = ssl.SSLContext(protocol)
crt_file = Path(__file__).with_name('cert.pem')
key_file = Path(__file__).with_name('key.pem')
self.ssl_context.load_cert_chain(str(crt_file), str(key_file))
self.status = None
self.port = None
self._task = self.loop.create_task(self.run())
示例3: _wrap_sni_socket
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import PROTOCOL_TLS [as 別名]
def _wrap_sni_socket(sock, sslopt, hostname):
context = ssl.SSLContext(sslopt.get('ssl_version', ssl.PROTOCOL_TLS))
context.options |= ssl.OP_NO_SSLv2 # Explicitly disable SSLv2
context.options |= ssl.OP_NO_SSLv3 # Explicitly disable SSLv3
context.options |= ssl.OP_NO_TLSv1 # Explicitly disable TLSv1.0
context.options |= ssl.OP_NO_TLSv1_1 # Explicitly disable TLSv1.1
if sslopt.get('cert_reqs', ssl.CERT_NONE) != ssl.CERT_NONE:
capath = ssl.get_default_verify_paths().capath
context.load_verify_locations(
cafile=sslopt.get('ca_certs', None),
capath=sslopt.get('ca_cert_path', capath)
)
return context.wrap_socket(
sock,
do_handshake_on_connect=sslopt.get('do_handshake_on_connect', True),
suppress_ragged_eofs=sslopt.get('suppress_ragged_eofs', True),
server_hostname=hostname,
)
示例4: loop
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import PROTOCOL_TLS [as 別名]
def loop(self):
"""Main server loop for accepting connections. Better call it on its own thread"""
while True:
try:
(csock, (ipaddr, port)) = self.connection["sock"].accept()
self._log("L", "New connection from %s:%s" % (str(ipaddr),
str(port)))
except sock_error:
raise sock_error
try:
csock = ssl.wrap_socket(csock, server_side=True, certfile="server.crt",
keyfile="server.key",
ssl_version=ssl.PROTOCOL_TLSv1_2)
except AttributeError: # All PROTOCOL consts are merged on TLS in Python2.7.13
csock = ssl.wrap_socket(csock, server_side=True, certfile="server.crt",
keyfile="server.key",
ssl_version=ssl.PROTOCOL_TLS)
self.clients["hosts"][str(self.clients["serial"])] = Host(csock, ipaddr, port,
self.clients["serial"])
self.clients["serial"] += 1
示例5: download_cert
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import PROTOCOL_TLS [as 別名]
def download_cert(filepath, host, raw=False):
host = urlparse(host).hostname or host
context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS)
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
for _ in range(20):
try:
with closing(socket.create_connection((host, 443))) as sock:
with closing(context.wrap_socket(sock, server_hostname=host)) as secure_sock:
cert = secure_sock.getpeercert(binary_form=True)
except Exception: # no cov
time.sleep(3)
else:
break
else: # no cov
raise Exception('Unable to connect to {}'.format(host))
if raw:
with open(filepath, 'wb') as f:
f.write(cert)
else:
cert = ssl.DER_cert_to_PEM_cert(cert)
with open(filepath, 'w') as f:
f.write(cert)
示例6: init_poolmanager
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import PROTOCOL_TLS [as 別名]
def init_poolmanager(self, connections, maxsize, block=False, **pool_kwargs):
"""Called to initialize the HTTPAdapter when no proxy is used."""
try:
pool_kwargs['ssl_version'] = ssl.PROTOCOL_TLS
except AttributeError:
pool_kwargs['ssl_version'] = ssl.PROTOCOL_SSLv23
return super(SSLAdapter, self).init_poolmanager(connections, maxsize, block, **pool_kwargs)
示例7: proxy_manager_for
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import PROTOCOL_TLS [as 別名]
def proxy_manager_for(self, proxy, **proxy_kwargs):
"""Called to initialize the HTTPAdapter when a proxy is used."""
try:
proxy_kwargs['ssl_version'] = ssl.PROTOCOL_TLS
except AttributeError:
proxy_kwargs['ssl_version'] = ssl.PROTOCOL_SSLv23
return super(SSLAdapter, self).proxy_manager_for(proxy, **proxy_kwargs)
示例8: resolve_ssl_version
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import PROTOCOL_TLS [as 別名]
def resolve_ssl_version(candidate):
"""
like resolve_cert_reqs
"""
if candidate is None:
return PROTOCOL_TLS
if isinstance(candidate, str):
res = getattr(ssl, candidate, None)
if res is None:
res = getattr(ssl, "PROTOCOL_" + candidate)
return res
return candidate
示例9: test_check_hostname
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import PROTOCOL_TLS [as 別名]
def test_check_hostname(self):
self.client.quit()
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS)
ctx.verify_mode = ssl.CERT_REQUIRED
ctx.check_hostname = True
ctx.load_verify_locations(CAFILE)
self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT)
# 127.0.0.1 doesn't match SAN
self.client.connect(self.server.host, self.server.port)
with self.assertRaises(ssl.CertificateError):
self.client.auth()
# exception quits connection
self.client.connect(self.server.host, self.server.port)
self.client.prot_p()
with self.assertRaises(ssl.CertificateError):
self.client.transfercmd("list").close()
self.client.quit()
self.client.connect("localhost", self.server.port)
self.client.auth()
self.client.quit()
self.client.connect("localhost", self.server.port)
self.client.prot_p()
self.client.transfercmd("list").close()
示例10: create_ssl_context
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import PROTOCOL_TLS [as 別名]
def create_ssl_context(pkcs12_data, pkcs12_password_bytes):
p12 = load_pkcs12(pkcs12_data, pkcs12_password_bytes)
cert = p12.get_certificate()
check_cert_not_after(cert)
ssl_context = PyOpenSSLContext(ssl_protocol)
ssl_context._ctx.use_certificate(cert)
ca_certs = p12.get_ca_certificates()
if ca_certs:
for ca_cert in ca_certs:
check_cert_not_after(ca_cert)
ssl_context._ctx.add_extra_chain_cert(ca_cert)
ssl_context._ctx.use_privatekey(p12.get_privatekey())
return ssl_context
示例11: resolve_ssl_version
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import PROTOCOL_TLS [as 別名]
def resolve_ssl_version(candidate):
"""
like resolve_cert_reqs
"""
if candidate is None:
return PROTOCOL_TLS
if isinstance(candidate, str):
res = getattr(ssl, candidate, None)
if res is None:
res = getattr(ssl, 'PROTOCOL_' + candidate)
return res
return candidate
示例12: module_run
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import PROTOCOL_TLS [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)
示例13: auth
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import PROTOCOL_TLS [as 別名]
def auth(self):
'''Set up secure control connection by using TLS/SSL.'''
if isinstance(self.sock, ssl.SSLSocket):
raise ValueError("Already using TLS")
if self.ssl_version >= ssl.PROTOCOL_TLS:
resp = self.voidcmd('AUTH TLS')
else:
resp = self.voidcmd('AUTH SSL')
self.sock = self.context.wrap_socket(self.sock,
server_hostname=self.host)
self.file = self.sock.makefile(mode='r', encoding=self.encoding)
return resp
示例14: __init__
# 需要導入模塊: import ssl [as 別名]
# 或者: from ssl import PROTOCOL_TLS [as 別名]
def __init__(self, server, port, proto='udp', clientname=None,
maxMessageLength=1024, timeout=120, cert_path=None):
self.socket = None
self.server = server
self.port = port
self.proto = socket.SOCK_DGRAM
self.ssl_kwargs = None
self.maxMessageLength = maxMessageLength
self.timeout = timeout
if proto is not None:
if proto.upper() == 'UDP':
self.proto = socket.SOCK_DGRAM
elif proto.upper() == 'TCP':
self.proto = socket.SOCK_STREAM
elif proto.upper() == 'TLS':
self.proto = socket.SOCK_STREAM
self.ssl_kwargs ={
'cert_reqs': ssl.CERT_REQUIRED,
'ssl_version': ssl.PROTOCOL_TLS,
'ca_certs': cert_path,
}
self.clientname = clientname or socket.getfqdn() or socket.gethostname()
self.cert_path = cert_path