Python ssl.PROTOCOL_TLS Examples

The following are 30 code examples of ssl.PROTOCOL_TLS(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ssl , or try the search function .
Example #1
Source File: rspet_server.py    From RSPET with MIT License 6 votes vote down vote up
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 
Example #2
Source File: websocket.py    From jellyfin-kodi with GNU General Public License v3.0 6 votes vote down vote up
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,
    ) 
Example #3
Source File: test_connection.py    From python-libjuju with Apache License 2.0 6 votes vote down vote up
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()) 
Example #4
Source File: http.py    From threat_intel with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: test_ftplib.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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() 
Example #6
Source File: subrake.py    From Subrake with GNU General Public License v3.0 5 votes vote down vote up
def request(self, _subdomain, _port):
		'''
		_req = "GET / HTTP/1.1\r\nHost: %s\r\nUser-Agent: %s\r\nOrigin: http://%s\r\n\r\n" % (_subdomain, roll.AGENT, _subdomain)
		
		_s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
		_s.settimeout( 10 )

		try:
			if _port == 443:
				_s =  ssl.wrap_socket(_s, ssl_version=ssl.PROTOCOL_TLS)

			_s.connect((_subdomain, _port))
			_s.send( _req )

			resp, toadd, datalength = "", _s.recv( 2048 ), 1

			while datalength:
				datalength = len( toadd )
				resp += toadd
				if (datalength < 2048) or ("\r\n\r\n" in data):
					break
				toadd = _s.recv( 2048 )

			_s.close()
		except:
			resp = ""
		'''
		httpath = ("http://%s" % _subdomain) if _port == 80 else ("https://%s" % _subdomain)
		try:
			r = requests.get(httpath, headers=self.HEADERS, allow_redirects=False, timeout=10, verify=False)
			code = r.status_code
			headers = r.headers
		except:
			code = None
			headers = {}
			if _subdomain not in self.ERRORSUB:
				self.ERRORCOU += 1
				self.ERRORSUB.append(_subdomain)

		return roll.seperator( code, headers ) 
Example #7
Source File: ftplib.py    From android_universal with MIT License 5 votes vote down vote up
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 
Example #8
Source File: ssl_utils.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_insecure_ssl_client_context():
    """Creates an insecure ssl context for integration that requires to use TLS without checking
    the host authenticity.

    :rtype ssl.Context
    """
    context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS)
    context.verify_mode = ssl.CERT_NONE
    return context 
Example #9
Source File: test_api.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_ssl_verify_false(realtime_instance):
    realtime_instance['ssl_verify'] = False

    with patch('datadog_checks.vsphere.api.connect') as connect, patch(
        'ssl.SSLContext.load_verify_locations'
    ) as load_verify_locations:
        smart_connect = connect.SmartConnect

        config = VSphereConfig(realtime_instance, MagicMock())
        VSphereAPI(config, MagicMock())

        actual_context = smart_connect.call_args.kwargs['sslContext']  # type: ssl.SSLContext
        assert actual_context.protocol == ssl.PROTOCOL_TLS
        assert actual_context.verify_mode == ssl.CERT_NONE
        load_verify_locations.assert_not_called() 
Example #10
Source File: utils.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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) 
Example #11
Source File: tls.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tls_context(self):
        if self._tls_context is None:
            # https://docs.python.org/3/library/ssl.html#ssl.SSLContext
            # https://docs.python.org/3/library/ssl.html#ssl.PROTOCOL_TLS
            self._tls_context = ssl.SSLContext(protocol=PROTOCOL_TLS_CLIENT)

            # Run our own validation later on if need be
            # https://docs.python.org/3/library/ssl.html#ssl.SSLContext.check_hostname
            #
            # IMPORTANT: This must be set before verify_mode in Python 3.7+, see:
            # https://docs.python.org/3/library/ssl.html#ssl.SSLContext.check_hostname
            self._tls_context.check_hostname = False

            # https://docs.python.org/3/library/ssl.html#ssl.SSLContext.verify_mode
            self._tls_context.verify_mode = ssl.CERT_REQUIRED if self._validate_cert else ssl.CERT_NONE

            # https://docs.python.org/3/library/ssl.html#ssl.SSLContext.load_verify_locations
            if self._cafile or self._capath:  # no cov
                self._tls_context.load_verify_locations(self._cafile, self._capath, None)

            # https://docs.python.org/3/library/ssl.html#ssl.SSLContext.load_default_certs
            else:
                self._tls_context.load_default_certs(ssl.Purpose.SERVER_AUTH)

            # https://docs.python.org/3/library/ssl.html#ssl.SSLContext.load_cert_chain
            if self._cert:  # no cov
                self._tls_context.load_cert_chain(self._cert, keyfile=self._private_key)

            # https://docs.python.org/3/library/ssl.html#ssl.create_default_context
            if 'SSLv3' in self._allowed_versions:  # no cov
                self._tls_context.options &= ~ssl.OP_NO_SSLv3

        return self._tls_context 
Example #12
Source File: rsyslog.py    From journalpump with Apache License 2.0 5 votes vote down vote up
def __init__(self, *, server, port, rfc,
                 max_msg=2048, protocol=None, cacerts=None, keyfile=None, certfile=None, log_format=None):
        self.socket = None
        self.server = server
        self.port = port
        self.max_msg = max_msg
        self.socket_proto = socket.SOCK_STREAM
        self.ssl_params = None
        if rfc == "RFC5424":
            self.formatter = _rfc_5424_formatter
        elif rfc == "RFC3164":
            self.formatter = _rfc_3164_formatter
        elif rfc == "CUSTOM":
            if log_format is None:
                raise ValueError("log_format must be given when using CUSTOM format")
            self.formatter = partial(_custom_formatter, _generate_format(log_format))
        else:
            raise ValueError('Unknown message format "{}" requested'.format(rfc))
        if protocol is None:
            protocol = 'PLAINTEXT'
        if cacerts is not None or protocol == "SSL":
            self.ssl_params = {
                "ssl_version": ssl.PROTOCOL_TLS,  # pylint: disable=no-member
                "cert_reqs": ssl.CERT_REQUIRED,
                "keyfile": keyfile,
                "certfile": certfile,
                "ca_certs": cacerts,
            }
        self._connect() 
Example #13
Source File: ssl_.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
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 
Example #14
Source File: ftplib.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #15
Source File: ssl_.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
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 
Example #16
Source File: ssl_.py    From quickstart-redhat-openshift with Apache License 2.0 5 votes vote down vote up
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 
Example #17
Source File: ssl_.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
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 
Example #18
Source File: ssl_.py    From CogAlg with MIT License 5 votes vote down vote up
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 
Example #19
Source File: ssl_.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #20
Source File: ssl_.py    From MIA-Dictionary-Addon with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #21
Source File: test_config.py    From deck-chores with ISC License 5 votes vote down vote up
def test_default_config(monkeypatch):
    def docker_api_version(self):
        return '1.37'

    def every_file_exists(*args, **kwargs):
        return True

    monkeypatch.setenv('DEBUG', '0')
    monkeypatch.setattr(deck_chores.config, 'exists', every_file_exists)
    monkeypatch.setattr(
        docker.client.APIClient, '_retrieve_server_version', docker_api_version
    )

    generate_config()
    result = cfg.__dict__.copy()
    assert isinstance(result.pop('client'), docker.client.DockerClient)
    assert result == {
        'assert_hostname': False,
        'client_timeout': DEFAULT_TIMEOUT_SECONDS,
        'docker_host': 'unix://var/run/docker.sock',
        'debug': False,
        'default_max': 1,
        'default_flags': ('image', 'service'),
        'job_executor_pool_size': 10,
        'label_ns': 'deck-chores.',
        'logformat': '{asctime}|{levelname:8}|{message}',
        'service_identifiers': (
            'com.docker.compose.project',
            'com.docker.compose.service',
        ),
        'ssl_version': ssl.PROTOCOL_TLS,
        'timezone': 'UTC',
    } 
Example #22
Source File: ftplib.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #23
Source File: ssl_.py    From Cloudmare with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #24
Source File: http.py    From threat_intel with MIT License 5 votes vote down vote up
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) 
Example #25
Source File: ssl_.py    From CudaText with Mozilla Public License 2.0 5 votes vote down vote up
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 
Example #26
Source File: ssl_.py    From CudaText with Mozilla Public License 2.0 5 votes vote down vote up
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 
Example #27
Source File: ssl_.py    From luci-py with Apache License 2.0 5 votes vote down vote up
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 
Example #28
Source File: ssl_.py    From rules_pip with MIT License 5 votes vote down vote up
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 
Example #29
Source File: test_ftplib.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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() 
Example #30
Source File: ssl_.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
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