Python ssl.PROTOCOL_TLSv1_2() Examples

The following are 30 code examples of ssl.PROTOCOL_TLSv1_2(). 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: stream.py    From kawaii-player with GNU General Public License v3.0 7 votes vote down vote up
def run(self):
        global httpd, ui_player
        print('starting server...')
        server_address = ('', self.port)
        server_start = False
        try:
            httpd = ThreadedHTTPServer(server_address, testHTTPServer_RequestHandler)
            if self.https_allow and self.cert_file:
                if os.path.exists(self.cert_file):
                    httpd.socket = ssl.wrap_socket(
                        httpd.socket, certfile=self.cert_file, 
                        ssl_version=ssl.PROTOCOL_TLSv1_2)
            server_start = True
        except Exception as err:
            print(err, '----->error')
            txt = 'Your local IP changed..or port is blocked\n..Trying to find new IP'
            send_notification(txt)
            self.ip = get_lan_ip()
            txt = 'Your New Address is '+self.ip + '\n Please restart the player'
            send_notification(txt)
        if server_start:
            print('running server...at..'+self.ip+':'+str(self.port))
            httpd.serve_forever()
        else:
            print('server..not..started..') 
Example #2
Source File: cell_socket.py    From torpy with Apache License 2.0 6 votes vote down vote up
def connect(self):
        if self._socket:
            raise Exception('Already connected')

        self._socket = ssl.wrap_socket(
            socket.socket(socket.AF_INET, socket.SOCK_STREAM), ssl_version=ssl.PROTOCOL_TLSv1_2
        )
        logger.debug('Connecting socket to %s relay...', self._router)
        try:
            self._socket.settimeout(15.0)
            self._socket.connect((self._router.ip, self._router.tor_port))

            handshake = TorHandshake(self, self._protocol)
            handshake.initiate()
        except Exception as e:
            logger.error(e)
            raise TorSocketConnectError(e) 
Example #3
Source File: compatiblity_tests.py    From amqpstorm with MIT License 6 votes vote down vote up
def test_compatibility_no_supported_ssl_version(self):
        """This tests mimics the behavior of a Python build without
        support for TLS v1, v1_1 or v1_2.
        """
        restore_tls_v1_2 = sys.modules['ssl'].PROTOCOL_TLSv1_2
        restore_tls_v1_1 = sys.modules['ssl'].PROTOCOL_TLSv1_1
        restore_tls_v1 = sys.modules['ssl'].PROTOCOL_TLSv1
        try:
            del sys.modules['ssl'].PROTOCOL_TLSv1_2
            del sys.modules['ssl'].PROTOCOL_TLSv1_1
            del sys.modules['ssl'].PROTOCOL_TLSv1
            imp.reload(compatibility)
            self.assertIsNone(compatibility.DEFAULT_SSL_VERSION)
            self.assertFalse(compatibility.SSL_SUPPORTED)
            self.assertFalse(compatibility.SSL_CERT_MAP)
            self.assertFalse(compatibility.SSL_VERSIONS)
        finally:
            sys.modules['ssl'].PROTOCOL_TLSv1_2 = restore_tls_v1_2
            sys.modules['ssl'].PROTOCOL_TLSv1_1 = restore_tls_v1_1
            sys.modules['ssl'].PROTOCOL_TLSv1 = restore_tls_v1
            imp.reload(compatibility) 
Example #4
Source File: main.py    From Seth with MIT License 6 votes vote down vote up
def get_ssl_version(sock):
        # Seth behaves differently depeding on the TLS protocol
        # https://bugs.python.org/issue31453
        # This is an ugly hack (as if the rest of this wasn't...)
    versions = [
        ssl.PROTOCOL_TLSv1,
        ssl.PROTOCOL_TLSv1_1,
        ssl.PROTOCOL_TLSv1_2,
        ]
    firstbytes = sock.recv(16, socket.MSG_PEEK)
    try:
        return versions[firstbytes[10]-1]
    except IndexError:
        print("Unexpected SSL version: %s" % hexlify(firstbytes))
        return versions[-1]


#  def launch_rdp_client():
#      time.sleep(1)
#      p = subprocess.Popen(
#          ["xfreerdp",
#           "/v:%s:%d" % (args.bind_ip, consts.RELAY_PORT),
#           "/u:%s\\%s" % (domain, user),
#          ],
#      ) 
Example #5
Source File: compatiblity_tests.py    From amqpstorm with MIT License 6 votes vote down vote up
def test_compatibility_only_tls_v1_supported(self):
        """This tests mimics the behavior of Python 2.7.8 or earlier that
        only supported TLS v1 and SSLv23.
        """
        restore_tls_v1_2 = sys.modules['ssl'].PROTOCOL_TLSv1_2
        restore_tls_v1 = sys.modules['ssl'].PROTOCOL_TLSv1_1
        try:
            del sys.modules['ssl'].PROTOCOL_TLSv1_2
            del sys.modules['ssl'].PROTOCOL_TLSv1_1
            imp.reload(compatibility)
            self.assertEqual(compatibility.get_default_ssl_version(),
                             ssl.PROTOCOL_TLSv1)
        finally:
            sys.modules['ssl'].PROTOCOL_TLSv1_2 = restore_tls_v1_2
            sys.modules['ssl'].PROTOCOL_TLSv1_1 = restore_tls_v1
            imp.reload(compatibility) 
Example #6
Source File: server.py    From DeepPavlov with Apache License 2.0 6 votes vote down vote up
def get_ssl_params(server_params: dict,
                   https: Optional[bool],
                   ssl_key: Optional[str],
                   ssl_cert: Optional[str]) -> SSLConfig:
    https = https or server_params['https']
    if https:
        ssh_key_path = Path(ssl_key or server_params['https_key_path']).resolve()
        if not ssh_key_path.is_file():
            e = FileNotFoundError('Ssh key file not found: please provide correct path in --key param or '
                                  'https_key_path param in server configuration file')
            log.error(e)
            raise e

        ssh_cert_path = Path(ssl_cert or server_params['https_cert_path']).resolve()
        if not ssh_cert_path.is_file():
            e = FileNotFoundError('Ssh certificate file not found: please provide correct path in --cert param or '
                                  'https_cert_path param in server configuration file')
            log.error(e)
            raise e

        ssl_config = SSLConfig(version=PROTOCOL_TLSv1_2, keyfile=str(ssh_key_path), certfile=str(ssh_cert_path))
    else:
        ssl_config = SSLConfig(None, None, None)

    return ssl_config 
Example #7
Source File: utils.py    From nats.py with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        super().setUp()
        self.loop = asyncio.new_event_loop()

        # Make sure we are setting which loop we are using explicitly
        asyncio.set_event_loop(None)

        self.gnatsd = Gnatsd(port=4224, tls=True)
        start_gnatsd(self.gnatsd)

        self.ssl_ctx = ssl.create_default_context(
            purpose=ssl.Purpose.SERVER_AUTH
        )
        # self.ssl_ctx.protocol = ssl.PROTOCOL_TLSv1_2
        self.ssl_ctx.load_verify_locations('tests/certs/ca.pem')
        self.ssl_ctx.load_cert_chain(
            certfile='tests/certs/client-cert.pem',
            keyfile='tests/certs/client-key.pem'
        ) 
Example #8
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 #9
Source File: test_mqtt_transport.py    From azure-iot-sdk-python with MIT License 6 votes vote down vote up
def test_configures_tls_context(self, mocker):
        mock_mqtt_client = mocker.patch.object(mqtt, "Client").return_value
        mock_ssl_context_constructor = mocker.patch.object(ssl, "SSLContext")
        mock_ssl_context = mock_ssl_context_constructor.return_value

        MQTTTransport(client_id=fake_device_id, hostname=fake_hostname, username=fake_username)

        # Verify correctness of TLS/SSL Context
        assert mock_ssl_context_constructor.call_count == 1
        assert mock_ssl_context_constructor.call_args == mocker.call(protocol=ssl.PROTOCOL_TLSv1_2)
        assert mock_ssl_context.check_hostname is True
        assert mock_ssl_context.verify_mode == ssl.CERT_REQUIRED

        # Verify context has been set
        assert mock_mqtt_client.tls_set_context.call_count == 1
        assert mock_mqtt_client.tls_set_context.call_args == mocker.call(context=mock_ssl_context) 
Example #10
Source File: int_ssl.py    From pysslscan with GNU Lesser General Public License v3.0 6 votes vote down vote up
def convert_version2method(protocol_version):
    """
    Convert internal protocol version ID to Python SSL method.

    :param Integer protocol_version: Version ID
    :return: OpenSSL method or None if not found
    :rtype: OpenSSL method or None
    """
    if protocol_version == flextls.registry.version.SSLv2:
        return ssl.PROTOCOL_SSLv2
    if protocol_version == flextls.registry.version.SSLv3:
        return ssl.PROTOCOL_SSLv3
    if protocol_version == flextls.registry.version.TLSv10:
        return ssl.PROTOCOL_TLSv1
    if protocol_version == flextls.registry.version.TLSv11:
        return ssl.PROTOCOL_TLSv1_1
    if protocol_version == flextls.registry.version.TLSv12:
        return ssl.PROTOCOL_TLSv1_2

    return None 
Example #11
Source File: mqtt_locust.py    From mqtt-locust with MIT License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(Locust, self).__init__(*args, **kwargs)
        if self.host is None:
            raise LocustError("You must specify a host")

        #TODO: Current implementation sets an empty client_id when the connection is initialized,
        #      which Paho handles by creating a random client_id. 
        #		Ideally we want to control the client_id that is set in Paho. Each client_id
        #		should match a thing_id in the AWS IoT Thing Registry
        #self.client = MQTTClient(self.client_id)
        self.client = MQTTClient()
        try:
            [host, port] = self.host.split(":")
        except:
            host, port = self.host, 8883

        try:
          self.client.tls_set(self.ca_cert, self.iot_cert, self.iot_private_key, tls_version=ssl.PROTOCOL_TLSv1_2)
          #It is important to do an asynchronous connect, given that we will have
          #multiple connections happening in a single server during a Locust test
          self.client.connect_async(host, port)
          self.client.loop_start()
        except Exception as e:
            fire_locust_failure(
                request_type=REQUEST_TYPE,
                name='connect',
                response_time=time_delta(start_time, time.time()),
                exception=ConnectError("Could not connect to host:["+host+"]")
            ) 
Example #12
Source File: mqtt_locust.py    From mqtt-locust with MIT License 6 votes vote down vote up
def tls_set(self, ca_certs, certfile=None, keyfile=None, cert_reqs=ssl.CERT_REQUIRED, 
            tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None):
        start_time = time.time()
        try:
            super(MQTTClient,self).tls_set(ca_certs,
            certfile,
                keyfile,
                cert_reqs, 
                tls_version,
                ciphers)
        except Exception as e:
            fire_locust_failure(
                request_type=REQUEST_TYPE,
                name='tls_set',
                response_time=time_delta(start_time, time.time()),
                exception=e)

    #retry is not used at the time since this implementation only supports QoS 0 
Example #13
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 #14
Source File: mqtt_transport.py    From azure-iot-sdk-python-preview with MIT License 6 votes vote down vote up
def _create_ssl_context(self):
        """
        This method creates the SSLContext object used by Paho to authenticate the connection.
        """
        logger.info("creating a SSL context")
        ssl_context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLSv1_2)

        if self._ca_cert:
            ssl_context.load_verify_locations(cadata=self._ca_cert)
        else:
            ssl_context.load_default_certs()
        ssl_context.verify_mode = ssl.CERT_REQUIRED
        ssl_context.check_hostname = True

        if self._x509_cert is not None:
            logger.info("configuring SSL context with client-side certificate and key")
            ssl_context.load_cert_chain(
                self._x509_cert.certificate_file,
                self._x509_cert.key_file,
                self._x509_cert.pass_phrase,
            )

        return ssl_context 
Example #15
Source File: test_mqtt_transport.py    From azure-iot-sdk-python-preview with MIT License 6 votes vote down vote up
def test_configures_tls_context(self, mocker):
        mock_mqtt_client = mocker.patch.object(mqtt, "Client").return_value
        mock_ssl_context_constructor = mocker.patch.object(ssl, "SSLContext")
        mock_ssl_context = mock_ssl_context_constructor.return_value

        MQTTTransport(client_id=fake_device_id, hostname=fake_hostname, username=fake_username)

        # Verify correctness of TLS/SSL Context
        assert mock_ssl_context_constructor.call_count == 1
        assert mock_ssl_context_constructor.call_args == mocker.call(protocol=ssl.PROTOCOL_TLSv1_2)
        assert mock_ssl_context.check_hostname is True
        assert mock_ssl_context.verify_mode == ssl.CERT_REQUIRED

        # Verify context has been set
        assert mock_mqtt_client.tls_set_context.call_count == 1
        assert mock_mqtt_client.tls_set_context.call_args == mocker.call(context=mock_ssl_context) 
Example #16
Source File: channelhandler.py    From python-sdk with MIT License 6 votes vote down vote up
def initTLSContext(self, ca_file, node_crt_file, node_key_file,
                       protocol=ssl.PROTOCOL_TLSv1_2,
                       verify_mode=ssl.CERT_REQUIRED):
        try:
            context = ssl.SSLContext(protocol)
            context.check_hostname = False
            context.load_verify_locations(ca_file)

            context.load_cert_chain(node_crt_file, node_key_file)
            # print(context.get_ca_certs())
            context.set_ecdh_curve(self.ECDH_curve)
            context.verify_mode = verify_mode
            self.context = context
        except Exception as e:
            raise ChannelException(("init ssl context failed,"
                                    " please check the certificatsreason: {}").
                                   format(e)) 
Example #17
Source File: psk-frontend.py    From tuya-convert with MIT License 6 votes vote down vote up
def new_client(self, s1):
		try:
			ssl_sock = sslpsk.wrap_socket(s1,
				server_side = True,
				ssl_version=ssl.PROTOCOL_TLSv1_2,
				ciphers='PSK-AES128-CBC-SHA256',
				psk=lambda identity: gen_psk(identity, self.hint),
				hint=self.hint)

			s2 = client(self.host, self.port)
			self.sessions.append((ssl_sock, s2))
		except ssl.SSLError as e:
			print("could not establish sslpsk socket:", e)
			if "NO_SHARED_CIPHER" in e.reason or "WRONG_VERSION_NUMBER" in e.reason or "WRONG_SSL_VERSION" in e.reason:
				print("don't panic this is probably just your phone!")
		except Exception as e:
			print(e) 
Example #18
Source File: base.py    From ws-backend-community with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, ip_address=None, port=None, ssl_version=ssl.PROTOCOL_TLSv1_2):
        self.ssl_version = ssl_version
        super(BaseSslTcpFingerprinter, self).__init__(ip_address=ip_address, port=port)

    # Static Methods

    # Class Methods

    # Public Methods 
Example #19
Source File: api.py    From mygeotab-python with Apache License 2.0 5 votes vote down vote up
def init_poolmanager(self, connections, maxsize, block=False, **pool_kwargs):
        self.poolmanager = urllib3.poolmanager.PoolManager(
            num_pools=connections, maxsize=maxsize, block=block, ssl_version=ssl.PROTOCOL_TLSv1_2, **pool_kwargs
        ) 
Example #20
Source File: utils_http.py    From motu-client-python with GNU Lesser General Public License v3.0 5 votes vote down vote up
def connect(self):
        """Overrides HTTPSConnection.connect to specify TLS version"""
        # Standard implementation from HTTPSConnection, which is not
        # designed for extension, unfortunately
        sock = socket.create_connection((self.host, self.port),
                self.timeout, self.source_address)
        if getattr(self, '_tunnel_host', None):
            self.sock = sock
            self._tunnel()
 
        # This is the only difference; default wrap_socket uses SSLv23
        self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,
                ssl_version=ssl.PROTOCOL_TLSv1_2) 
Example #21
Source File: tls_adapter.py    From pixelated-user-agent with GNU Affero General Public License v3.0 5 votes vote down vote up
def latest_available_ssl_version():
    try:
        return ssl.PROTOCOL_TLSv1_2
    except AttributeError:
        return ssl.PROTOCOL_TLSv1 
Example #22
Source File: tsocks.py    From tsocks with GNU Affero General Public License v3.0 5 votes vote down vote up
def reverse_socks5_hand(self,daddr,dport):#reverse socks5 mode handsheak
		global DEBUG
		global SSL
		#global CERT
		try:
			s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			if SSL:
				s2 = ssl.wrap_socket(s2,
										ssl_version=ssl.PROTOCOL_TLSv1_2,
										#ca_certs=CERT,
										#cert_reqs=ssl.CERT_REQUIRED
										)
				if DEBUG:
					print "[*]Cipher :",s2.cipher()
			s2.connect((daddr,dport))
			if DEBUG:
				print "[*]New socket start..."
			s2.recv(BUF_SIZE)
			s2.send(b"\x05\x00")
			data = s2.recv(BUF_SIZE)
			if data:
				mode = ord(data[1])
				addrtype = ord(data[3])
				if addrtype == 1:       # IPv4
					addr = socket.inet_ntoa(data[4:8])
					port = (struct.unpack('!H', data[8:]))[0]
				elif addrtype == 3:     # Domain name
					length = struct.unpack('B', data[4:5])[0]
					addr = data[5:5 + length]
					port = (struct.unpack('!H', data[5 + length:]))[0]
				r = self.remote(addr,port,mode,s2)#forward requests
				self.exchange_data(s2,r)
			else:
				#s2.shutdown(socket.SHUT_RDWR)
				s2.close()
		except Exception,e:
			if DEBUG:
				print e
			#s2.shutdown(socket.SHUT_RDWR)
			s2.close() 
Example #23
Source File: tsocks.py    From tsocks with GNU Affero General Public License v3.0 5 votes vote down vote up
def reverse_socks5_main(self,daddr,dport):#reverse socks5 mode main
		global BUF_SIZE
		global FLAG
		global CMD
		global DEBUG
		global SSL
		#global CERT
		try:
			s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			if SSL:
				s1 = ssl.wrap_socket(s1,
										ssl_version=ssl.PROTOCOL_TLSv1_2,
										#cert_reqs=ssl.CERT_REQUIRED,
										#ca_certs=CERT
										)
				if DEBUG:
					print "[*]Cipher :",s1.cipher()
			s1.connect((daddr,dport))
			print "[*]Connected to relay server success:", daddr,dport
			while True:#loop and recv forward server send a cmd and product a new socket to do with socks5 proxy
				flag =s1.recv(BUF_SIZE)
				if flag==CMD:
					threading.Thread(target=self.reverse_socks5_hand,args=(daddr,dport)).start()
		except Exception,e:
			if DEBUG:
				print e
			print "[-]Connect  relay server fail..."
			#s1.shutdown(socket.SHUT_RDWR)
			s1.close()
			sys.exit(1) 
Example #24
Source File: compatiblity_tests.py    From amqpstorm with MIT License 5 votes vote down vote up
def test_compatibility_default_ssl_version(self):
        self.assertTrue(compatibility.SSL_SUPPORTED)
        if hasattr(ssl, 'PROTOCOL_TLSv1_2'):
            self.assertEqual(compatibility.DEFAULT_SSL_VERSION,
                             ssl.PROTOCOL_TLSv1_2)
        else:
            self.assertEqual(compatibility.DEFAULT_SSL_VERSION,
                             ssl.PROTOCOL_TLSv1) 
Example #25
Source File: vterm.py    From pypowervm with Apache License 2.0 5 votes vote down vote up
def _enable_x509_authentication(self, client_socket, server_socket):
        """Enables and Handshakes VeNCrypt using X509 Authentication.

        :param client_socket:  The client-side socket to receive data from.
        :param server_socket:  The server-side socket to forward data to.
        :return ssl_socket:  A client-side socket wrappered for SSL or None
                             if there is an error.
        """
        try:
            # First perform the RFB Version negotiation between client/server
            self._version_negotiation(client_socket, server_socket)
            # Next perform the Security Authentication Type Negotiation
            if not self._auth_type_negotiation(client_socket):
                return None
            # Next perform the Security Authentication SubType Negotiation
            if not self._auth_subtype_negotiation(client_socket):
                return None
            # Now that the VeNCrypt handshake is done, do the SSL wrapper
            ca_certs = self.x509_certs.get('ca_certs')
            server_key = self.x509_certs.get('server_key')
            server_cert = self.x509_certs.get('server_cert')
            return ssl.wrap_socket(
                client_socket, server_side=True, ca_certs=ca_certs,
                certfile=server_cert, keyfile=server_key,
                ssl_version=ssl.PROTOCOL_TLSv1_2, cert_reqs=ssl.CERT_REQUIRED)
        # If we got an error, log and handle to not take down the thread
        except Exception as exc:
            LOG.warning(_("Error negotiating SSL for VNC Repeater: %s") % exc)
            LOG.exception(exc)
            return None 
Example #26
Source File: mqtt.py    From aqara-mqtt with Apache License 2.0 5 votes vote down vote up
def _get_tls_version(self,tlsString):
        switcher = {
            "tlsv1": ssl.PROTOCOL_TLSv1,
            "tlsv1.1": ssl.PROTOCOL_TLSv1_1,
            "tlsv1.2": ssl.PROTOCOL_TLSv1_2
        }
        return switcher.get(tlsString,ssl.PROTOCOL_TLSv1_2) 
Example #27
Source File: compatibility.py    From amqpstorm with MIT License 5 votes vote down vote up
def get_default_ssl_version():
    """Get the highest support TLS version, if none is available, return None.

    :rtype: bool,None
    """
    if hasattr(ssl, 'PROTOCOL_TLSv1_2'):
        return ssl.PROTOCOL_TLSv1_2
    elif hasattr(ssl, 'PROTOCOL_TLSv1_1'):
        return ssl.PROTOCOL_TLSv1_1
    elif hasattr(ssl, 'PROTOCOL_TLSv1'):
        return ssl.PROTOCOL_TLSv1
    return None 
Example #28
Source File: mqtt.py    From broadlink-mqtt with MIT License 5 votes vote down vote up
def __init__(self, filename=CONFIG, custom_filename=CONFIG_CUSTOM):
        self.config = {}
        exec(compile(open(filename, "rb").read(), filename, 'exec'), self.config)
        if os.path.isfile(custom_filename):
            exec(compile(open(custom_filename, "rb").read(), custom_filename, 'exec'), self.config)

        if self.config.get('ca_certs', None) is not None:
            self.config['tls'] = True

        tls_version = self.config.get('tls_version', None)
        if tls_version is not None:
            if not HAVE_TLS:
                logging.error("TLS parameters set but no TLS available (SSL)")
                sys.exit(2)

            if tls_version == 'tlsv1':
                self.config['tls_version'] = ssl.PROTOCOL_TLSv1
            if tls_version == 'tlsv1.2':
                # TLS v1.2 is available starting from python 2.7.9 and requires openssl version 1.0.1+.
                if sys.version_info >= (2, 7, 9):
                    self.config['tls_version'] = ssl.PROTOCOL_TLSv1_2
                else:
                    logging.error("TLS version 1.2 not available but 'tlsv1.2' is set.")
                    sys.exit(2)
            if tls_version == 'sslv3':
                self.config['tls_version'] = ssl.PROTOCOL_SSLv3 
Example #29
Source File: tb_device_mqtt.py    From thingsboard-gateway with Apache License 2.0 5 votes vote down vote up
def connect(self, callback=None, min_reconnect_delay=1, timeout=120, tls=False, ca_certs=None, cert_file=None, key_file=None, keepalive=60):
        if tls:
            self._client.tls_set(ca_certs=ca_certs,
                                 certfile=cert_file,
                                 keyfile=key_file,
                                 cert_reqs=ssl.CERT_REQUIRED,
                                 tls_version=ssl.PROTOCOL_TLSv1_2,
                                 ciphers=None)
            self._client.tls_insecure_set(False)
        self._client.connect(self.__host, self.__port, keepalive=keepalive)
        self.reconnect_delay_set(min_reconnect_delay, timeout)
        self._client.loop_start()
        self.__connect_callback = callback 
Example #30
Source File: __init__.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def loadCipherSuite(self):
        if self.cipherSuite:
            return self.cipherSuite

        self.cipherSuite = ''

        if hasattr(ssl, 'PROTOCOL_TLS'):
            ciphers = [
                'ECDHE-ECDSA-AES128-GCM-SHA256', 'ECDHE-RSA-AES128-GCM-SHA256', 'ECDHE-ECDSA-AES256-GCM-SHA384',
                'ECDHE-RSA-AES256-GCM-SHA384', 'ECDHE-ECDSA-CHACHA20-POLY1305-SHA256', 'ECDHE-RSA-CHACHA20-POLY1305-SHA256',
                'ECDHE-RSA-AES128-CBC-SHA', 'ECDHE-RSA-AES256-CBC-SHA', 'RSA-AES128-GCM-SHA256', 'RSA-AES256-GCM-SHA384',
                'ECDHE-RSA-AES128-GCM-SHA256', 'RSA-AES256-SHA', '3DES-EDE-CBC'
            ]

            if hasattr(ssl, 'PROTOCOL_TLSv1_3'):
                ciphers.insert(0, ['GREASE_3A', 'GREASE_6A', 'AES128-GCM-SHA256', 'AES256-GCM-SHA256', 'AES256-GCM-SHA384', 'CHACHA20-POLY1305-SHA256'])

            ctx = ssl.SSLContext(getattr(ssl, 'PROTOCOL_TLSv1_3', ssl.PROTOCOL_TLSv1_2))

            for cipher in ciphers:
                try:
                    ctx.set_ciphers(cipher)
                    self.cipherSuite = '{}:{}'.format(self.cipherSuite, cipher).rstrip(':')
                except ssl.SSLError:
                    pass

        return self.cipherSuite

    ##########################################################################################################################################################