當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。