当前位置: 首页>>代码示例>>Python>>正文


Python ssl.PROTOCOL_TLS属性代码示例

本文整理汇总了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() 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:26,代码来源:test_ftplib.py

示例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()) 
开发者ID:juju,项目名称:python-libjuju,代码行数:27,代码来源:test_connection.py

示例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,
    ) 
开发者ID:jellyfin,项目名称:jellyfin-kodi,代码行数:22,代码来源:websocket.py

示例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 
开发者ID:panagiks,项目名称:RSPET,代码行数:22,代码来源:rspet_server.py

示例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) 
开发者ID:DataDog,项目名称:integrations-core,代码行数:27,代码来源:utils.py

示例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) 
开发者ID:Yelp,项目名称:threat_intel,代码行数:9,代码来源:http.py

示例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) 
开发者ID:Yelp,项目名称:threat_intel,代码行数:9,代码来源:http.py

示例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 
开发者ID:remg427,项目名称:misp42splunk,代码行数:16,代码来源:ssl_.py

示例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() 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:29,代码来源:test_ftplib.py

示例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 
开发者ID:m-click,项目名称:requests_pkcs12,代码行数:15,代码来源:requests_pkcs12.py

示例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 
开发者ID:PacktPublishing,项目名称:Mastering-Elasticsearch-7.0,代码行数:16,代码来源:ssl_.py

示例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) 
开发者ID:lanmaster53,项目名称:recon-ng-marketplace,代码行数:37,代码来源:ssl_scan.py

示例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 
开发者ID:CedricGuillemet,项目名称:Imogen,代码行数:14,代码来源:ftplib.py

示例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 
开发者ID:aliyun,项目名称:aliyun-log-python-sdk,代码行数:28,代码来源:syslogclient.py


注:本文中的ssl.PROTOCOL_TLS属性示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。