Python ssl.PROTOCOL_TLSv1() Examples

The following are 30 code examples of ssl.PROTOCOL_TLSv1(). 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: utils.py    From youtube-dl-GUI with MIT License 6 votes vote down vote up
def make_HTTPS_handler(params, **kwargs):
    opts_no_check_certificate = params.get('nocheckcertificate', False)
    if hasattr(ssl, 'create_default_context'):  # Python >= 3.4 or 2.7.9
        context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
        if opts_no_check_certificate:
            context.check_hostname = False
            context.verify_mode = ssl.CERT_NONE
        try:
            return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
        except TypeError:
            # Python 2.7.8
            # (create_default_context present but HTTPSHandler has no context=)
            pass

    if sys.version_info < (3, 2):
        return YoutubeDLHTTPSHandler(params, **kwargs)
    else:  # Python < 3.4
        context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        context.verify_mode = (ssl.CERT_NONE
                               if opts_no_check_certificate
                               else ssl.CERT_REQUIRED)
        context.set_default_verify_paths()
        return YoutubeDLHTTPSHandler(params, context=context, **kwargs) 
Example #2
Source File: streamtls.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def _make_tls_connection(self):
        """Initiate TLS connection.

        [initiating entity only]
        """
        logger.debug("Preparing TLS connection")
        if self.settings["tls_verify_peer"]:
            cert_reqs = ssl.CERT_REQUIRED
        else:
            cert_reqs = ssl.CERT_NONE
        self.stream.transport.starttls(
                    keyfile = self.settings["tls_key_file"],
                    certfile = self.settings["tls_cert_file"],
                    server_side = not self.stream.initiator,
                    cert_reqs = cert_reqs,
                    ssl_version = ssl.PROTOCOL_TLSv1,
                    ca_certs = self.settings["tls_cacert_file"],
                    do_handshake_on_connect = False,
                    ) 
Example #3
Source File: test_ftplib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_context(self):
        self.client.quit()
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        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()
        with self.client.transfercmd('list') as sock:
            self.assertIs(sock.context, ctx)
            self.assertIsInstance(sock, ssl.SSLSocket) 
Example #4
Source File: UcsBase.py    From UcsPythonSDK with Apache License 2.0 6 votes vote down vote up
def loadUcsConfig():
	from ConfigParser import SafeConfigParser

	configFile = os.path.join(os.path.dirname(__file__),"UcsConfig.cfg")
	parser = SafeConfigParser()
	parser.read(configFile)

	sslProtocol = parser.get('ssl_connection', 'ssl_protocol').strip('"')
	isVerifyCertificate = parser.getboolean('ssl_connection', 'verify_certificate')

	if not sys.version_info < (2, 6):
		from functools import partial
		import ssl

		sslProtocolDict = {'TLSv1': ssl.PROTOCOL_TLSv1}

		ssl.wrap_socket = partial(ssl.wrap_socket, ssl_version=sslProtocolDict[sslProtocol])

		if not sys.version_info < (2, 7, 9) and not isVerifyCertificate:
			ssl._create_default_https_context = ssl._create_unverified_context 
Example #5
Source File: controller.py    From ryu with Apache License 2.0 6 votes vote down vote up
def server_loop(self):
        if CONF.ctl_privkey is not None and CONF.ctl_cert is not None:
            if CONF.ca_certs is not None:
                server = StreamServer((CONF.ofp_listen_host,
                                       CONF.ofp_ssl_listen_port),
                                      datapath_connection_factory,
                                      keyfile=CONF.ctl_privkey,
                                      certfile=CONF.ctl_cert,
                                      cert_reqs=ssl.CERT_REQUIRED,
                                      ca_certs=CONF.ca_certs,
                                      ssl_version=ssl.PROTOCOL_TLSv1)
            else:
                server = StreamServer((CONF.ofp_listen_host,
                                       CONF.ofp_ssl_listen_port),
                                      datapath_connection_factory,
                                      keyfile=CONF.ctl_privkey,
                                      certfile=CONF.ctl_cert,
                                      ssl_version=ssl.PROTOCOL_TLSv1)
        else:
            server = StreamServer((CONF.ofp_listen_host,
                                   CONF.ofp_tcp_listen_port),
                                  datapath_connection_factory)

        # LOG.debug('loop')
        server.serve_forever() 
Example #6
Source File: le_cloudwatch.py    From le-aws-cloudwatch with MIT License 6 votes vote down vote up
def create_socket():
    logger.info('Creating SSL socket')
    s_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s = ssl.wrap_socket(
        sock=s_,
        keyfile=None,
        certfile=None,
        server_side=False,
        cert_reqs=ssl.CERT_REQUIRED,
        ssl_version=getattr(
            ssl,
            'PROTOCOL_TLSv1_2',
            ssl.PROTOCOL_TLSv1
        ),
        ca_certs=certifi.where(),
        do_handshake_on_connect=True,
        suppress_ragged_eofs=True,
    )
    try:
        logger.info('Connecting to {}:{}'.format(ENDPOINT, PORT))
        s.connect((ENDPOINT, PORT))
        return s
    except socket.error, exc:
        logger.error('Exception socket.error : {}'.format(exc)) 
Example #7
Source File: test_ftplib.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_context(self):
        self.client.quit()
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        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()
        with self.client.transfercmd('list') as sock:
            self.assertIs(sock.context, ctx)
            self.assertIsInstance(sock, ssl.SSLSocket) 
Example #8
Source File: Request.py    From SharPyShell with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, url, user_agent, cookies_string=False, custom_header=False, insecure_ssl='false', proxy=False):
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
        self.__url = url
        self.__headers = dict()
        self.__headers['User-Agent'] = self.__default_user_agent if user_agent == 'default' else user_agent
        if cookies_string:
            self.__headers['Cookie'] = cookies_string
        if custom_header:
            self.__parse_custom_header(custom_header)
        self.__verify = 'CERT_REQUIRED' if insecure_ssl == 'false' else 'CERT_NONE'
        if proxy:
            proxy_type = proxy.split('://')[0]
            if proxy_type == 'http' or proxy_type == 'https':
                self.__request_obj = urllib3.ProxyManager(proxy, ssl_version=ssl.PROTOCOL_TLSv1,
                                                          timeout=self.__request_timeout, cert_reqs=self.__verify)
            else:
                self.__request_obj = SOCKSProxyManager(proxy, ssl_version=ssl.PROTOCOL_TLSv1,
                                                       timeout=self.__request_timeout, cert_reqs=self.__verify)
        else:
            self.__request_obj = urllib3.PoolManager(ssl_version=ssl.PROTOCOL_TLSv1, timeout=self.__request_timeout,
                                                     cert_reqs=self.__verify)
        # print (vars(self)) 
Example #9
Source File: le_lambda.py    From le_lambda with MIT License 6 votes vote down vote up
def create_socket():
    logger.info('Creating SSL socket')
    s_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s = ssl.wrap_socket(
        sock=s_,
        keyfile=None,
        certfile=None,
        server_side=False,
        cert_reqs=ssl.CERT_REQUIRED,
        ssl_version=getattr(
            ssl,
            'PROTOCOL_TLSv1_2',
            ssl.PROTOCOL_TLSv1
        ),
        ca_certs=certifi.where(),
        do_handshake_on_connect=True,
        suppress_ragged_eofs=True,
    )
    try:
        logger.info('Connecting to {}:{}'.format(ENDPOINT, PORT))
        s.connect((ENDPOINT, PORT))
        return s
    except socket.error, exc:
        logger.error('Exception socket.error : {}'.format(exc))
        raise SystemExit 
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: test_ftplib.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_context(self):
        self.client.quit()
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        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()
        with self.client.transfercmd('list') as sock:
            self.assertIs(sock.context, ctx)
            self.assertIsInstance(sock, ssl.SSLSocket) 
Example #12
Source File: cassandra_utils.py    From cassandra-medusa with Apache License 2.0 6 votes vote down vote up
def __init__(self, ip_addresses, cassandra_config):
        self._ip_addresses = ip_addresses
        self._auth_provider = None
        self._ssl_context = None
        self._cassandra_config = cassandra_config

        if cassandra_config.cql_username is not None and cassandra_config.cql_password is not None:
            auth_provider = PlainTextAuthProvider(username=cassandra_config.cql_username,
                                                  password=cassandra_config.cql_password)
            self._auth_provider = auth_provider

        if cassandra_config.certfile is not None and cassandra_config.usercert is not None and \
           cassandra_config.userkey is not None:
            ssl_context = SSLContext(PROTOCOL_TLSv1)
            ssl_context.load_verify_locations(cassandra_config.certfile)
            ssl_context.verify_mode = CERT_REQUIRED
            ssl_context.load_cert_chain(
                certfile=cassandra_config.usercert,
                keyfile=cassandra_config.userkey)
            self._ssl_context = ssl_context

        load_balancing_policy = WhiteListRoundRobinPolicy(ip_addresses)
        self._execution_profiles = {
            'local': ExecutionProfile(load_balancing_policy=load_balancing_policy)
        } 
Example #13
Source File: utils.py    From youtube-dl-GUI with MIT License 6 votes vote down vote up
def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
    # Working around python 2 bug (see http://bugs.python.org/issue17849) by limiting
    # expected HTTP responses to meet HTTP/1.0 or later (see also
    # https://github.com/rg3/youtube-dl/issues/6727)
    if sys.version_info < (3, 0):
        kwargs[b'strict'] = True
    hc = http_class(*args, **kwargs)
    source_address = ydl_handler._params.get('source_address')
    if source_address is not None:
        sa = (source_address, 0)
        if hasattr(hc, 'source_address'):  # Python 2.7+
            hc.source_address = sa
        else:  # Python 2.6
            def _hc_connect(self, *args, **kwargs):
                sock = compat_socket_create_connection(
                    (self.host, self.port), self.timeout, sa)
                if is_https:
                    self.sock = ssl.wrap_socket(
                        sock, self.key_file, self.cert_file,
                        ssl_version=ssl.PROTOCOL_TLSv1)
                else:
                    self.sock = sock
            hc.connect = functools.partial(_hc_connect, hc)

    return hc 
Example #14
Source File: utils.py    From tvalacarta with GNU General Public License v3.0 6 votes vote down vote up
def make_HTTPS_handler(params, **kwargs):
    opts_no_check_certificate = params.get('nocheckcertificate', False)
    if hasattr(ssl, 'create_default_context'):  # Python >= 3.4 or 2.7.9
        context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
        if opts_no_check_certificate:
            context.check_hostname = False
            context.verify_mode = ssl.CERT_NONE
        try:
            return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
        except TypeError:
            # Python 2.7.8
            # (create_default_context present but HTTPSHandler has no context=)
            pass

    if sys.version_info < (3, 2):
        return YoutubeDLHTTPSHandler(params, **kwargs)
    else:  # Python < 3.4
        context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        context.verify_mode = (ssl.CERT_NONE
                               if opts_no_check_certificate
                               else ssl.CERT_REQUIRED)
        context.set_default_verify_paths()
        return YoutubeDLHTTPSHandler(params, context=context, **kwargs) 
Example #15
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 #16
Source File: websocketserver.py    From opsbro with MIT License 5 votes vote down vote up
def __init__(self, host, port, websocketclass, certfile, keyfile, version=PROTOCOL_TLSv1):
        SimpleWebSocketServer.__init__(self, host, port, websocketclass)
        
        self.cerfile = certfile
        self.keyfile = keyfile
        self.version = version 
Example #17
Source File: vulns.py    From bane with MIT License 5 votes vote down vote up
def build_post(u,p,timeout=5,size=10000):
 s =socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 s.settimeout(timeout)
 s.connect((u,p))
 if ((p==443 ) or (p==8443)):
  s=ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1)
 s.send("POST {} HTTP/1.1\r\nUser-Agent: {}\r\nAccept-language: en-US,en,q=0.5\r\nConnection: keep-alive\r\nKeep-Alive: {}\r\nContent-Length: {}\r\nContent-Type: application/x-www-form-urlencoded\r\nHost: {}\r\n\r\n".format(random.choice(paths),random.choice(ua),random.randint(300,1000),size,u).encode("utf-8"))
 return s 
Example #18
Source File: ssl_checker.py    From ssl-checker with GNU General Public License v3.0 5 votes vote down vote up
def get_cert(self, host, port, user_args):
        """Connection to the host."""
        if user_args.socks:
            import socks
            if user_args.verbose:
                print('{}Socks proxy enabled{}\n'.format(Clr.YELLOW, Clr.RST))

            socks_host, socks_port = self.filter_hostname(user_args.socks)
            socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, socks_host, int(socks_port), True)
            socket.socket = socks.socksocket

        if user_args.verbose:
            print('{}Connecting to socket{}\n'.format(Clr.YELLOW, Clr.RST))

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        osobj = SSL.Context(PROTOCOL_TLSv1)
        sock.connect((host, int(port)))
        oscon = SSL.Connection(osobj, sock)
        oscon.set_tlsext_host_name(host.encode())
        oscon.set_connect_state()
        oscon.do_handshake()
        cert = oscon.get_peer_certificate()
        sock.close()
        if user_args.verbose:
            print('{}Closing socket{}\n'.format(Clr.YELLOW, Clr.RST))

        return cert 
Example #19
Source File: vulns.py    From bane with MIT License 5 votes vote down vote up
def build_get(u,p,timeout=5):
    s =socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(timeout)
    s.connect((u,p))
    if ((p==443 ) or (p==8443)):
     s=ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1)
    s.send("GET {} HTTP/1.1\r\n".format(random.choice(paths)).encode("utf-8"))
    s.send("User-Agent: {}\r\n".format(random.choice(ua)).encode("utf-8"))
    s.send("Accept-language: en-US,en,q=0.5\r\n".encode("utf-8"))
    s.send("Connection: keep-alive\r\n".encode("utf-8"))
    return s 
Example #20
Source File: SimpleWebSocketServer.py    From lightbulb-framework with MIT License 5 votes vote down vote up
def __init__(self, host, port, websocketclass, parentconn, conn, myport, certfile,
                keyfile, version = ssl.PROTOCOL_TLSv1, selectInterval = 0.1):

      SimpleWebSocketServer.__init__(self, host, port,
                                        websocketclass, selectInterval)

      self.context = ssl.SSLContext(version)
      self.context.load_cert_chain(certfile, keyfile)
      self.parentconn = parentconn
      self.conn = conn
      self.myport = myport 
Example #21
Source File: test_client.py    From PyKMIP with Apache License 2.0 5 votes vote down vote up
def test_init(self):
        """
        Test that a ProxyKmipClient can be constructed with valid arguments.
        """
        ProxyKmipClient(
            hostname='127.0.0.1',
            port=5696,
            cert='/example/path/to/cert',
            key='/example/path/to/key',
            ca='/example/path/to/ca',
            ssl_version=ssl.PROTOCOL_TLSv1,
            username='username',
            password='password',
            config='test') 
Example #22
Source File: test_auth.py    From PyKMIP with Apache License 2.0 5 votes vote down vote up
def test_protocol(self):
        suite = auth.BasicAuthenticationSuite()
        protocol = suite.protocol

        self.assertIsInstance(protocol, int)
        self.assertEqual(ssl.PROTOCOL_TLSv1, suite.protocol) 
Example #23
Source File: connection.py    From scaleio-py with Apache License 2.0 5 votes vote down vote up
def init_poolmanager(self, connections, maxsize, block=False):
        self.poolmanager = PoolManager(num_pools=connections,
                                       maxsize=maxsize,
                                       block=block,
                                       ssl_version=ssl.PROTOCOL_TLSv1) 
Example #24
Source File: Plugwise-2-web.py    From Plugwise-2-py with GNU General Public License v3.0 5 votes vote down vote up
def main():
    try:
        server = ThreadedHTTPServer(('', port), PW2PYwebHandler)
        server.daemon_threads = True
        server.auth = b64encode(credentials)
        if secure:
            if sys.hexversion < 0x02071000:
                #server.socket = ssl.wrap_socket (server.socket, certfile='./server.pem', server_side=True, ssl_version=ssl.PROTOCOL_TLSv1_2)
                server.socket = ssl.wrap_socket (server.socket, certfile='./server.pem', server_side=True, ssl_version=ssl.PROTOCOL_TLSv1)
            else:
                ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
                ctx.load_cert_chain(certfile="./server.pem")
                ctx.options |= ssl.OP_NO_TLSv1
                ctx.options |= ssl.OP_NO_TLSv1_1
                ctx.options |= ssl.OP_CIPHER_SERVER_PREFERENCE
                ctx.set_ciphers('ECDHE-RSA-AES256-GCM-SHA384 ECDHE-RSA-AES256-SHA384 ECDHE-RSA-AES256-SHA')
                server.socket = ctx.wrap_socket(server.socket, server_side=True)
            
            info('started secure https server at port %d' % (port,))
        else: 
            info('started http server at port %d' % (port,))
        server.serve_forever()
    except KeyboardInterrupt:
        print('^C received, shutting down server')
        server.shutdown()
        print "exit after server.shutdown()" 
Example #25
Source File: find_service.py    From w9scan with GNU General Public License v2.0 5 votes vote down vote up
def sockHttp(host, port, timeout=5):
    socketObj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    if port == 443:
        if not _https:
            raise "Not support SSL"
        try:
            socketObj = ssl.wrap_socket(socketObj, ssl_version=ssl.PROTOCOL_TLSv1)
        except ssl.SSLError as error:
            socketObj = ssl.wrap_socket(socketObj, ssl_version=ssl.PROTOL_SSLv23)

    socketObj.settimeout(timeout)
    socketObj.connect((host, port))
    return socketObj 
Example #26
Source File: status.py    From squadron with MIT License 5 votes vote down vote up
def report_status(session, server, apikey, secret, nonce, verify, **kwargs):
    """
    Reports status via the HTTPS API. Given the server, API key and
    secret, this method generates the hash_result of a nonce.

    Pass hostname, status, and info in the kwargs. Raises an exception
    when a non-200 result code is returned.

    Keyword arguments:
        session -- a requests session object
        server -- The server to report status to. Can be host:port
        apikey -- The API key to use
        secret -- The API secret associated with this API key
        nonce -- a random string only to be used once
        verify -- Whether or not to verify the SSL connection
        hostname -- The hostname to identify this server by
        status -- OK or ERROR
        info -- Dictionary of more information
    """
    raw_secret = secret.decode('hex')

    hash_result = hmac.new(raw_secret, nonce, hashlib.sha256).hexdigest()

    log.debug("Got body: {}".format(kwargs))

    # Requests doesn't handle TLSv1 by default
    session.mount('https://', SSLAdapter(ssl.PROTOCOL_TLSv1))

    resp = session.post('https://{}/update/{}/{}'.format(server, apikey, hash_result),
                data=json.dumps(kwargs),
                headers={
                    'Content-Type':'application/json',
                    'X-Nonce':nonce},
                verify=verify)

    resp.raise_for_status() 
Example #27
Source File: broadlink-thermostat.py    From broadlink-thermostat with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, filename=CONFIG):
        self.config = {}
        self.config['ca_certs']     = None
        self.config['tls_version']  = None
        self.config['certfile']     = None
        self.config['keyfile']      = None
        self.config['tls_insecure'] = False
        self.config['tls']          = False
        execfile(filename, self.config)

        if HAVE_TLS == False:
            logging.error("TLS parameters set but no TLS available (SSL)")
            sys.exit(2)

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

        if self.config.get('tls_version') is not None:
            if self.config.get('tls_version') == 'tlsv1':
                self.config['tls_version'] = ssl.PROTOCOL_TLSv1
            if self.config.get('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 self.config.get('tls_version') == 'sslv3':
                self.config['tls_version'] = ssl.PROTOCOL_SSLv3 
Example #28
Source File: test.py    From django_mqtt with GNU General Public License v2.0 5 votes vote down vote up
def test_publish_websock(self):
        secure = SecureConf.objects.create(ca_certs=self.ca_cert_file,
                                           cert_reqs=ssl.CERT_REQUIRED,
                                           tls_version=ssl.PROTOCOL_TLSv1,
                                           ciphers=None)
        Server.objects.create(host='test.mosquitto.org', port=8080)
        Server.objects.create(host='test.mosquitto.org', port=8081, secure=secure)
        # TODO 
Example #29
Source File: test_ftplib.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_check_hostname(self):
        self.client.quit()
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        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):
            with self.client.transfercmd("list") as sock:
                pass
        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()
        with self.client.transfercmd("list") as sock:
            pass 
Example #30
Source File: im.py    From scaleio-py with Apache License 2.0 5 votes vote down vote up
def init_poolmanager(self, connections, maxsize, block=False):
        self.poolmanager = PoolManager(num_pools=connections,
                                       maxsize=maxsize,
                                       block=block,
                                       ssl_version=ssl.PROTOCOL_TLSv1)