本文整理汇总了Python中ssl.OP_NO_SSLv3方法的典型用法代码示例。如果您正苦于以下问题:Python ssl.OP_NO_SSLv3方法的具体用法?Python ssl.OP_NO_SSLv3怎么用?Python ssl.OP_NO_SSLv3使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ssl
的用法示例。
在下文中一共展示了ssl.OP_NO_SSLv3方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _create_ssl_ctx
# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import OP_NO_SSLv3 [as 别名]
def _create_ssl_ctx(self, sslp):
if isinstance(sslp, ssl.SSLContext):
return sslp
ca = sslp.get('ca')
capath = sslp.get('capath')
hasnoca = ca is None and capath is None
ctx = ssl.create_default_context(cafile=ca, capath=capath)
ctx.check_hostname = not hasnoca and sslp.get('check_hostname', True)
ctx.verify_mode = ssl.CERT_NONE if hasnoca else ssl.CERT_REQUIRED
if 'cert' in sslp:
ctx.load_cert_chain(sslp['cert'], keyfile=sslp.get('key'))
if 'cipher' in sslp:
ctx.set_ciphers(sslp['cipher'])
ctx.options |= ssl.OP_NO_SSLv2
ctx.options |= ssl.OP_NO_SSLv3
return ctx
示例2: __init__
# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import OP_NO_SSLv3 [as 别名]
def __init__(self, *args, **kwargs):
self.ssl_context = kwargs.pop('ssl_context', None)
self.cipherSuite = kwargs.pop('cipherSuite', None)
self.source_address = kwargs.pop('source_address', None)
if self.source_address:
if isinstance(self.source_address, str):
self.source_address = (self.source_address, 0)
if not isinstance(self.source_address, tuple):
raise TypeError(
"source_address must be IP address string or (ip, port) tuple"
)
if not self.ssl_context:
self.ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
self.ssl_context.set_ciphers(self.cipherSuite)
self.ssl_context.set_ecdh_curve('prime256v1')
self.ssl_context.options |= (ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1)
super(CipherSuiteAdapter, self).__init__(**kwargs)
# ------------------------------------------------------------------------------- #
示例3: _create_transport_context
# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import OP_NO_SSLv3 [as 别名]
def _create_transport_context(server_side, server_hostname):
if server_side:
raise ValueError('Server side SSL needs a valid SSLContext')
# Client side may pass ssl=True to use a default
# context; in that case the sslcontext passed is None.
# The default is secure for client connections.
if hasattr(ssl, 'create_default_context'):
# Python 3.4+: use up-to-date strong settings.
sslcontext = ssl.create_default_context()
if not server_hostname:
sslcontext.check_hostname = False
else:
# Fallback for Python 3.3.
sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
sslcontext.options |= ssl.OP_NO_SSLv2
sslcontext.options |= ssl.OP_NO_SSLv3
sslcontext.set_default_verify_paths()
sslcontext.verify_mode = ssl.CERT_REQUIRED
return sslcontext
示例4: get_http2_ssl_context
# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import OP_NO_SSLv3 [as 别名]
def get_http2_ssl_context():
"""
This function creates an SSLContext object that is suitably configured for
HTTP/2. If you're working with Python TLS directly, you'll want to do the
exact same setup as this function does.
"""
# Get the basic context from the standard library.
ctx = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
# RFC 7540 Section 9.2: Implementations of HTTP/2 MUST use TLS version 1.2
# or higher. Disable TLS 1.1 and lower.
ctx.options |= (
ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1
)
# RFC 7540 Section 9.2.1: A deployment of HTTP/2 over TLS 1.2 MUST disable
# compression.
ctx.options |= ssl.OP_NO_COMPRESSION
# RFC 7540 Section 9.2.2: "deployments of HTTP/2 that use TLS 1.2 MUST
# support TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256". In practice, the
# blocklist defined in this section allows only the AES GCM and ChaCha20
# cipher suites with ephemeral key negotiation.
ctx.set_ciphers("ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20")
# We want to negotiate using NPN and ALPN. ALPN is mandatory, but NPN may
# be absent, so allow that. This setup allows for negotiation of HTTP/1.1.
ctx.set_alpn_protocols(["h2", "http/1.1"])
try:
ctx.set_npn_protocols(["h2", "http/1.1"])
except NotImplementedError:
pass
return ctx
示例5: get_http2_ssl_context
# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import OP_NO_SSLv3 [as 别名]
def get_http2_ssl_context():
"""
This function creates an SSLContext object that is suitably configured for
HTTP/2. If you're working with Python TLS directly, you'll want to do the
exact same setup as this function does.
"""
# Get the basic context from the standard library.
ctx = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH)
# RFC 7540 Section 9.2: Implementations of HTTP/2 MUST use TLS version 1.2
# or higher. Disable TLS 1.1 and lower.
ctx.options |= (
ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1
)
# RFC 7540 Section 9.2.1: A deployment of HTTP/2 over TLS 1.2 MUST disable
# compression.
ctx.options |= ssl.OP_NO_COMPRESSION
# RFC 7540 Section 9.2.2: "deployments of HTTP/2 that use TLS 1.2 MUST
# support TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256". In practice, the
# blocklist defined in this section allows only the AES GCM and ChaCha20
# cipher suites with ephemeral key negotiation.
ctx.set_ciphers("ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20")
# We want to negotiate using NPN and ALPN. ALPN is mandatory, but NPN may
# be absent, so allow that. This setup allows for negotiation of HTTP/1.1.
ctx.set_alpn_protocols(["h2", "http/1.1"])
try:
ctx.set_npn_protocols(["h2", "http/1.1"])
except NotImplementedError:
pass
return ctx
示例6: send_stats
# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import OP_NO_SSLv3 [as 别名]
def send_stats(version, uniqid, runtime):
#Because this is run as a subprocess we need to start logging again
logger_send_stats = setup_logging(logfilepath="logs/send_stats.log",loggername="send_stats")
destination="https://statscollector.rpisurv.net"
#SSL options
context = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH, cafile="core/util/statscollector.rpisurv.net.pem")
#Force TLS higher then 1.1
context.options |= ssl.OP_NO_SSLv2
context.options |= ssl.OP_NO_SSLv3
context.options |= ssl.OP_NO_TLSv1
context.options |= ssl.OP_NO_TLSv1_1
#Normally this has been set by ssl.Purpose.SERVER_AUTH but for safety in future explicitly set CERT_REQUIRED
context.verify_mode = ssl.CERT_REQUIRED
httpshandler = urllib2.HTTPSHandler(context=context)
opener = urllib2.build_opener(httpshandler)
opener.addheaders=[
('User-Agent', uniqid),
('Pragma', 'no-cache'),
('Cache-Control', 'no-cache')
]
#Extra info will be send via cookie headers
#opener.addheaders.append(('Cookie', 'runtime='+ runtime + ';reservedkey=reservedvalue'))
opener.addheaders.append(('Cookie', 'runtime='+ runtime + ';version='+ str(version) ))
urllib2.install_opener(opener)
#f = opener.open("http://httpbin.org/cookies")
logger_send_stats.debug("Start sending uniqid " + uniqid + ", runtime " + runtime + ", version " + str(version) + " to " + destination + " for updating stats rpisurv community")
try:
response = opener.open(destination, timeout=20)
except urllib2.HTTPError, e:
logger_send_stats.error("There was an error connecting to the statistics server at " + destination + ". Failed with code " + str(e.code))
示例7: test_create_ssl_context
# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import OP_NO_SSLv3 [as 别名]
def test_create_ssl_context() -> None:
path = os.path.join(os.path.dirname(__file__), "assets/config_ssl.py")
config = Config.from_pyfile(path)
context = config.create_ssl_context()
assert context.options & (
ssl.OP_NO_SSLv2
| ssl.OP_NO_SSLv3
| ssl.OP_NO_TLSv1
| ssl.OP_NO_TLSv1_1
| ssl.OP_NO_COMPRESSION
)
示例8: check_is_router
# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import OP_NO_SSLv3 [as 别名]
def check_is_router(cls, address: str, port: int, semaphore=Semaphore()) -> BaseIndustrialRouter:
"""
Check if a certain router is an industrial router, given the headers defined at class level.
:param address: IP address of the router to check.
:param port: Port of the web interface of the device to check.
:param semaphore: Asyncio semaphore to be used for concurrency limitation.
:return: A :class:`aztarna.industrialrouters.scanner.BaseIndustrialRouter` object if the checked device is a router.
None otherwise.
"""
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
context.options &= ~ssl.OP_NO_SSLv3
async with semaphore:
async with aiohttp.ClientSession(timeout=ClientTimeout(2)) as client:
uri = 'http://{}:{}'.format(address, port)
print('[+] Connecting to {}'.format(address))
async with client.get(uri, ssl=context) as response:
for field, values in cls.possible_headers:
if response.headers.get(field) in values:
router = cls.router_cls()
router.address = address
router.port = port
return router
else:
return None
示例9: check_default_password
# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import OP_NO_SSLv3 [as 别名]
def check_default_password(cls, router: BaseIndustrialRouter, semaphore=Semaphore()):
"""
Method for checking for default passwords on Moxa Routers.
:param router: Input router object to check the credentials for.
:param semaphore: Asyncio semaphore for limiting the concurrency leve.
"""
uri = '{}://{}:{}/{}'.format(router.protocol, router.address, router.port, cls.url_path)
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
context.options &= ~ssl.OP_NO_SSLv3
context.set_ciphers('HIGH:!DH:!aNULL')
async with semaphore:
async with aiohttp.ClientSession(timeout=ClientTimeout(20)) as client:
try:
logger.info('[+] Connecting to router at {}'.format(router.address))
async with client.request('GET', uri, ssl=context) as response:
router.alive = True
content = str(await response.content.read())
if cls.valid_login_text_moxahttp_2_2 in content or cls.valid_login_text_moxahttp_1_0 in content:
router.valid_credentials.append(('admin', 'no password'))
else:
if response.headers.get('Server') == 'MoxaHttp/1.0':
await cls.check_password_moxahttp_1_0(client, context, content, router)
elif response.headers.get('Server') == 'MoxaHttp/2.2':
await cls.check_password_moxahttp_2_2(client, context, content, router)
except:
logger.warning('[-] Connection to {} failed'.format(router.address))
示例10: _init_context
# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import OP_NO_SSLv3 [as 别名]
def _init_context(self, ssl_version):
if self._has_ssl_context:
self._context = ssl.SSLContext(ssl_version)
if self._context.protocol == ssl.PROTOCOL_SSLv23:
self._context.options |= ssl.OP_NO_SSLv2
self._context.options |= ssl.OP_NO_SSLv3
else:
self._context = None
self._ssl_version = ssl_version
示例11: create_urllib3_context
# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import OP_NO_SSLv3 [as 别名]
def create_urllib3_context(ssl_version=None, cert_reqs=None,
options=None, ciphers=None):
"""All arguments have the same meaning as ``ssl_wrap_socket``.
By default, this function does a lot of the same work that
``ssl.create_default_context`` does on Python 3.4+. It:
- Disables SSLv2, SSLv3, and compression
- Sets a restricted set of server ciphers
If you wish to enable SSLv3, you can do::
from urllib3.util import ssl_
context = ssl_.create_urllib3_context()
context.options &= ~ssl_.OP_NO_SSLv3
You can do the same to enable compression (substituting ``COMPRESSION``
for ``SSLv3`` in the last line above).
:param ssl_version:
The desired protocol version to use. This will default to
PROTOCOL_SSLv23 which will negotiate the highest protocol that both
the server and your installation of OpenSSL support.
:param cert_reqs:
Whether to require the certificate verification. This defaults to
``ssl.CERT_REQUIRED``.
:param options:
Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,
``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``.
:param ciphers:
Which cipher suites to allow the server to select.
:returns:
Constructed SSLContext object with specified options
:rtype: SSLContext
"""
context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23)
# Setting the default here, as we may have no ssl module on import
cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
if options is None:
options = 0
# SSLv2 is easily broken and is considered harmful and dangerous
options |= OP_NO_SSLv2
# SSLv3 has several problems and is now dangerous
options |= OP_NO_SSLv3
# Disable compression to prevent CRIME attacks for OpenSSL 1.0+
# (issue #309)
options |= OP_NO_COMPRESSION
context.options |= options
if getattr(context, 'supports_set_ciphers', True): # Platform-specific: Python 2.6
context.set_ciphers(ciphers or DEFAULT_CIPHERS)
context.verify_mode = cert_reqs
if getattr(context, 'check_hostname', None) is not None: # Platform-specific: Python 3.2
# We do our own verification, including fingerprints and alternative
# hostnames. So disable it here
context.check_hostname = False
return context
示例12: create_urllib3_context
# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import OP_NO_SSLv3 [as 别名]
def create_urllib3_context(ssl_version=None, cert_reqs=None,
options=None, ciphers=None):
"""All arguments have the same meaning as ``ssl_wrap_socket``.
By default, this function does a lot of the same work that
``ssl.create_default_context`` does on Python 3.4+. It:
- Disables SSLv2, SSLv3, and compression
- Sets a restricted set of server ciphers
If you wish to enable SSLv3, you can do::
from urllib3.util import ssl_
context = ssl_.create_urllib3_context()
context.options &= ~ssl_.OP_NO_SSLv3
You can do the same to enable compression (substituting ``COMPRESSION``
for ``SSLv3`` in the last line above).
:param ssl_version:
The desired protocol version to use. This will default to
PROTOCOL_SSLv23 which will negotiate the highest protocol that both
the server and your installation of OpenSSL support.
:param cert_reqs:
Whether to require the certificate verification. This defaults to
``ssl.CERT_REQUIRED``.
:param options:
Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,
``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``.
:param ciphers:
Which cipher suites to allow the server to select.
:returns:
Constructed SSLContext object with specified options
:rtype: SSLContext
"""
context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23)
context.set_ciphers(ciphers or DEFAULT_CIPHERS)
# Setting the default here, as we may have no ssl module on import
cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
if options is None:
options = 0
# SSLv2 is easily broken and is considered harmful and dangerous
options |= OP_NO_SSLv2
# SSLv3 has several problems and is now dangerous
options |= OP_NO_SSLv3
# Disable compression to prevent CRIME attacks for OpenSSL 1.0+
# (issue #309)
options |= OP_NO_COMPRESSION
context.options |= options
context.verify_mode = cert_reqs
if getattr(context, 'check_hostname', None) is not None: # Platform-specific: Python 3.2
# We do our own verification, including fingerprints and alternative
# hostnames. So disable it here
context.check_hostname = False
return context
示例13: check_secure_connection
# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import OP_NO_SSLv3 [as 别名]
def check_secure_connection(info):
# Guilty until proven innocent.
info.secure_connection_works = False
good_connection = info.new_check()
try:
addrs = socket.getaddrinfo(info.domain, 443, socket.AF_INET, proto=socket.IPPROTO_TCP)
except socket.gaierror:
good_connection.fail("DNS lookup failed.")
return
addr_info = random.choice(addrs)
sock = socket.socket(addr_info[0], addr_info[1], addr_info[2])
sock.settimeout(10)
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.options |= ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3
# Some platforms (OS X) do not have OP_NO_COMPRESSION
context.options |= getattr(ssl, "OP_NO_COMPRESSION", 0)
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
context.load_verify_locations(certifi.where())
secure_sock = context.wrap_socket(sock, server_hostname=info.domain)
try:
secure_sock.connect(addr_info[4])
except ConnectionRefusedError:
good_connection.fail("Nothing is listening on port 443.")
return
except socket.timeout:
good_connection.fail("<code>connect()</code> to port 443 times out.")
return
except ssl.SSLError as e:
if e.reason == "CERTIFICATE_VERIFY_FAILED":
desc = "Certificate not trusted by Mozilla cert store."
else:
desc = "A TLS-related error ({}) occurs when trying to connect.".format(e.reason)
good_connection.fail(desc)
return
except ssl.CertificateError:
good_connection.fail("Certificate hostname verification fails.")
return
except OSError as e:
error_name = errno.errorcode[e.errno]
good_connection.fail("<code>connect()</code> returns with error {}.".format(error_name))
return
finally:
secure_sock.close()
msg = "A verified TLS connection can be established. "
if info.ssllabs_grade is not None:
grade_msg = "<a href=\"https://www.ssllabs.com/ssltest/analyze.html?d={}\" target=\"_blank\">SSL Labs grade</a> is " + info.ssllabs_grade + "."
if info.ssllabs_grade == "F":
good_connection.fail(grade_msg.format(info.domain))
return
msg += grade_msg
else:
msg += "(<a href=\"https://www.ssllabs.com/ssltest/analyze.html?d={}\" target=\"_blank\">SSL Labs report</a>)"
info.secure_connection_works = True
good_connection.succeed(msg.format(info.domain))