Exemplo n.º 1
0
 def __init__(self, parent=None):
     """
     Constructor
     
     @param parent reference to the parent object (QObject)
     """
     super(E5SslErrorHandler, self).__init__(parent)
     
     caList = self.__getSystemCaCertificates()
     if Preferences.Prefs.settings.contains("Help/CaCertificatesDict"):
         # port old entries stored under 'Help'
         certificateDict = Globals.toDict(
             Preferences.Prefs.settings.value("Help/CaCertificatesDict"))
         Preferences.Prefs.settings.setValue(
             "Ssl/CaCertificatesDict", certificateDict)
         Preferences.Prefs.settings.remove("Help/CaCertificatesDict")
     else:
         certificateDict = Globals.toDict(
             Preferences.Prefs.settings.value("Ssl/CaCertificatesDict"))
     for server in certificateDict:
         for cert in QSslCertificate.fromData(certificateDict[server]):
             if cert not in caList:
                 caList.append(cert)
     sslCfg = QSslConfiguration.defaultConfiguration()
     sslCfg.setCaCertificates(caList)
     sslCfg.setProtocol(QSsl.AnyProtocol)
     try:
         sslCfg.setSslOption(QSsl.SslOptionDisableCompression, True)
     except AttributeError:
         pass
     QSslConfiguration.setDefaultConfiguration(sslCfg)
Exemplo n.º 2
0
class WSClient(QObject):
    def __init__(self, parent):
        super().__init__(parent)
        self.client = QWebSocket("", QWebSocketProtocol.Version13, None)        
        self.client.error.connect(self.onError)
        self.client.connected.connect(self.onConnected)
        self.client.disconnected.connect(self.onDisconnected)
        self.ssl_config = QSslConfiguration()
        self.ssl_cert_file = QFile(":certs/server.pem")
        self.ssl_cert_file.open(QIODevice.ReadOnly)
        self.ssl_cert = QSslCertificate(self.ssl_cert_file)
        self.ssl_config.setCaCertificates([self.ssl_cert])
        self.client.setSslConfiguration(self.ssl_config)
        self.message_queue = []
        self.is_connected = False
        self.telemetry_connected = False
        self.websocket_url = "wss://localhost:8081"
        self.websocket_token = "aVerySecureToken"
        
        self.timer_connection_watchdog = QTimer(parent)
        self.timer_connection_watchdog.start(5000)
        self.timer_connection_watchdog.timeout.connect(self.connection_watchdog)

        self.timer_reconnect = QTimer(parent)
        self.timer_reconnect.start(500)
        self.timer_reconnect.timeout.connect(self.send_message)

    def onConnected(self):
        # print("WebSocket: connected")
        self.is_connected = True

    def onDisconnected(self):
        # print("WebSocket: disconnected -> " + self.client.errorString())
        self.is_connected = False
        self.client.abort()
    
    def onError(self):
        # print("WebSocket: error -> " + self.client.errorString())
        self.is_connected = False
        self.client.abort()
    

    def queue_message(self, message):
        self.message_queue.append(message)

    def send_message(self):
        if self.is_connected and len(self.message_queue) > 0:
            message = self.message_queue.pop(0)
            message['token'] = self.websocket_token
            if self.client.sendTextMessage(dumps(message, default=json_util.default)) <= 0:
                self.message_queue.append(message)

    def connection_watchdog(self):
        if self.is_connected == False and self.telemetry_connected == True:
            # print("WebSocket: connecting to -> " + self.websocket_url)
            c = self.client.open(QUrl(self.websocket_url))
        if self.is_connected == True and self.telemetry_connected == False:
            # print("WebSocket: disconnecting from -> " + self.websocket_url)
            self.client.close()
            self.is_connected = False
Exemplo n.º 3
0
    def __init__(self, parent):
        super().__init__(parent)
        self.client = QWebSocket("", QWebSocketProtocol.Version13, None)        
        self.client.error.connect(self.onError)
        self.client.connected.connect(self.onConnected)
        self.client.disconnected.connect(self.onDisconnected)
        self.ssl_config = QSslConfiguration()
        self.ssl_cert_file = QFile(":certs/server.pem")
        self.ssl_cert_file.open(QIODevice.ReadOnly)
        self.ssl_cert = QSslCertificate(self.ssl_cert_file)
        self.ssl_config.setCaCertificates([self.ssl_cert])
        self.client.setSslConfiguration(self.ssl_config)
        self.message_queue = []
        self.is_connected = False
        self.telemetry_connected = False
        self.websocket_url = "wss://localhost:8081"
        self.websocket_token = "aVerySecureToken"
        
        self.timer_connection_watchdog = QTimer(parent)
        self.timer_connection_watchdog.start(5000)
        self.timer_connection_watchdog.timeout.connect(self.connection_watchdog)

        self.timer_reconnect = QTimer(parent)
        self.timer_reconnect.start(500)
        self.timer_reconnect.timeout.connect(self.send_message)
Exemplo n.º 4
0
    def __init__(self, loglevel='WARNING', ifcName='wlan0'):
        QObject.__init__(self)

        self.logger = Logger(name='ratt.networker')
        self.logger.setLogLevelStr(loglevel)
        self.debug = self.logger.isDebug()

        self.mgr = QNetworkAccessManager()
        self.sslConfig = QSslConfiguration()
        self.sslSupported = QSslSocket.supportsSsl()

        self.setAuth()
        self.setSSLCertConfig()

        self.mgr.authenticationRequired.connect(
            self.handleAuthenticationRequired)

        self.ifcName = ifcName
        self.ifcAddr = QHostAddress()

        self.statusTimer = QTimer()
        self.statusTimer.setSingleShot(False)
        self.statusTimer.timeout.connect(self.slotStatusTimer)
        self.statusTimer.start(5000)

        self.essid = ''
        self.freq = ''
        self.quality = 0
        self.level = 0
Exemplo n.º 5
0
 def __init__(self, parent=None):
     """
     Constructor
     
     @param parent reference to the parent object (QObject)
     """
     super(E5SslErrorHandler, self).__init__(parent)
     
     caList = self.__getSystemCaCertificates()
     if Preferences.Prefs.settings.contains("Help/CaCertificatesDict"):
         # port old entries stored under 'Help'
         certificateDict = Globals.toDict(
             Preferences.Prefs.settings.value("Help/CaCertificatesDict"))
         Preferences.Prefs.settings.setValue(
             "Ssl/CaCertificatesDict", certificateDict)
         Preferences.Prefs.settings.remove("Help/CaCertificatesDict")
     else:
         certificateDict = Globals.toDict(
             Preferences.Prefs.settings.value("Ssl/CaCertificatesDict"))
     for server in certificateDict:
         for cert in QSslCertificate.fromData(certificateDict[server]):
             if cert not in caList:
                 caList.append(cert)
     sslCfg = QSslConfiguration.defaultConfiguration()
     sslCfg.setCaCertificates(caList)
     sslCfg.setProtocol(QSsl.AnyProtocol)
     try:
         sslCfg.setSslOption(QSsl.SslOptionDisableCompression, True)
     except AttributeError:
         pass
     QSslConfiguration.setDefaultConfiguration(sslCfg)
Exemplo n.º 6
0
 def __updateDefaultConfiguration(self):
     """
     Private method to update the default SSL configuration.
     """
     caList = self.__getSystemCaCertificates()
     certificateDict = Globals.toDict(Preferences.Prefs.settings.value("Ssl/CaCertificatesDict"))
     for server in certificateDict:
         for cert in QSslCertificate.fromData(certificateDict[server]):
             if cert not in caList:
                 caList.append(cert)
     sslCfg = QSslConfiguration.defaultConfiguration()
     sslCfg.setCaCertificates(caList)
     QSslConfiguration.setDefaultConfiguration(sslCfg)
 def __updateDefaultConfiguration(self):
     """
     Private method to update the default SSL configuration.
     """
     caList = self.__getSystemCaCertificates()
     certificateDict = Globals.toDict(
         Preferences.Prefs.settings.value("Ssl/CaCertificatesDict"))
     for server in certificateDict:
         for cert in QSslCertificate.fromData(certificateDict[server]):
             if cert not in caList:
                 caList.append(cert)
     sslCfg = QSslConfiguration.defaultConfiguration()
     sslCfg.setCaCertificates(caList)
     QSslConfiguration.setDefaultConfiguration(sslCfg)
Exemplo n.º 8
0
 def __init__(self, *args, **kwargs):
     super(Window, self).__init__(*args, **kwargs)
     self.resize(800, 600)
     # 浏览器设置
     setting = QWebSettings.globalSettings()
     setting.setAttribute(QWebSettings.PluginsEnabled, True)
     # 解决xp下ssl问题
     self.page().networkAccessManager().sslErrors.connect(self.handleSslErrors)
     sslconf = QSslConfiguration.defaultConfiguration()
     clist = sslconf.caCertificates()
     cnew = QSslCertificate.fromData(b"CaCertificates")
     clist.extend(cnew)
     sslconf.setCaCertificates(clist)
     sslconf.setProtocol(QSsl.AnyProtocol)
     QSslConfiguration.setDefaultConfiguration(sslconf)
Exemplo n.º 9
0
 def __sslErrors(self, errors):
     """
     Private slot to handle SSL errors.
     
     @param errors list of SSL errors (list of QSslError)
     """
     ignored, defaultChanged = self.__sslErrorHandler.sslErrors(
         errors, self.__server.getName(), self.__server.getPort())
     if ignored == E5SslErrorHandler.NotIgnored:
         self.networkWidget.addErrorMessage(
             self.tr("SSL Error"),
             self.tr(
                 """Could not connect to {0} (port {1}) using an SSL"""
                 """ encrypted connection. Either the server does not"""
                 """ support SSL (did you use the correct port?) or"""
                 """ you rejected the certificate.""")
             .format(self.__server.getName(), self.__server.getPort()))
         self.__socket.close()
     else:
         if defaultChanged:
             self.__socket.setSslConfiguration(
                 QSslConfiguration.defaultConfiguration())
         if ignored == E5SslErrorHandler.UserIgnored:
             self.networkWidget.addErrorMessage(
                 self.tr("SSL Error"),
                 self.tr(
                     """The SSL certificate for the server {0} (port {1})"""
                     """ failed the authenticity check. SSL errors"""
                     """ were accepted by you.""")
                 .format(self.__server.getName(), self.__server.getPort()))
         if self.__connectionState == IrcWidget.ServerConnecting:
             self.__socket.ignoreSslErrors()
Exemplo n.º 10
0
 def __sslErrors(self, errors):
     """
     Private slot to handle SSL errors.
     
     @param errors list of SSL errors (list of QSslError)
     """
     ignored, defaultChanged = self.__sslErrorHandler.sslErrors(
         errors, self.__server.getName(), self.__server.getPort())
     if ignored == E5SslErrorHandler.NotIgnored:
         self.networkWidget.addErrorMessage(
             self.tr("SSL Error"),
             self.tr(
                 """Could not connect to {0} (port {1}) using an SSL"""
                 """ encrypted connection. Either the server does not"""
                 """ support SSL (did you use the correct port?) or"""
                 """ you rejected the certificate.""")
             .format(self.__server.getName(), self.__server.getPort()))
         self.__socket.close()
     else:
         if defaultChanged:
             self.__socket.setSslConfiguration(
                 QSslConfiguration.defaultConfiguration())
         if ignored == E5SslErrorHandler.UserIgnored:
             self.networkWidget.addErrorMessage(
                 self.tr("SSL Error"),
                 self.tr(
                     """The SSL certificate for the server {0} (port {1})"""
                     """ failed the authenticity check. SSL errors"""
                     """ were accepted by you.""")
                 .format(self.__server.getName(), self.__server.getPort()))
         if self.__connectionState == IrcWidget.ServerConnecting:
             self.__socket.ignoreSslErrors()
Exemplo n.º 11
0
    def __init__(
        self,
        protocol=None,
        key=None,
        options=None,
    ):
        super(SSLConfig, self).__init__(
            protocol=protocol,
            key=key,
            options=options,
        )

        # Set up implementation-specific state...

        # QSslConfiguration is a bag of data we need to talk to Qt. Its
        # attributes must be set using its various setWhatever methods.
        self._q_ssl_config = QSslConfiguration()

        # Get a protocol constant Qt understands, or cry to the user.
        q_ssl_protocol = _PROTOCOL_CHOICES.get(self.protocol)
        if q_ssl_protocol is None:
            raise InvalidSSLConfig("unknown protocol for Qt: {0!r}".format(
                self.protocol))
        # Hang on to it just in case we possibly need it, e.g. debugger
        self._q_ssl_protocol = q_ssl_protocol

        # Otherwise, tell Qt about the protocol.
        # n.b.: setting this after connection starts has no effect, so we
        # definitely want to do it here instead of deferring this.
        self._q_ssl_config.setProtocol(q_ssl_protocol)

        # If we have an SSLKey, have it make a QSslKey and tell Qt about it.
        if self.key:
            q_ssl_key = self.key.to_q_ssl_key()
            self._q_ssl_config.setPrivateKey(q_ssl_key)
        else:
            q_ssl_key = None
        self._q_ssl_key = q_ssl_key

        # Process self.options
        self._set_options()
Exemplo n.º 12
0
    def request(self, image_url: str):
        """
        Make HTTP request asynchronously
        """
        request = QNetworkRequest(QUrl(image_url))
        request.setRawHeader(b"User-Agent", b"412 Image Requester")

        # Configure to utilize SSL
        config = QSslConfiguration.defaultConfiguration()
        config.setProtocol(QSsl.TlsV1_2)

        request.setSslConfiguration(config)

        self.__net_man.get(request)
Exemplo n.º 13
0
def load_certificates():
    """ load (if existing and not empty) the local PEM file; split it into
    individual certificates, add each to the default configuration

    """

    local_cert_path = expanduser("~/.eilat/local.pem")
    local_certificates = split_certificates(local_cert_path)

    if local_certificates:
        print(r"""
        /----------------------------\
        SETTING LOCAL SSL CERTIFICATES
        \----------------------------/


        """)
        current_configuration = QSslConfiguration.defaultConfiguration()
        current_certs = current_configuration.caCertificates()
        for certificate in local_certificates:
            current_certs.append(QSslCertificate(certificate))

            current_configuration.setCaCertificates(current_certs)
            QSslConfiguration.setDefaultConfiguration(current_configuration)
Exemplo n.º 14
0
def load_certificates():
    """ load (if existing and not empty) the local PEM file; split it into
    individual certificates, add each to the default configuration

    """

    local_cert_path = expanduser("~/.eilat/local.pem")
    local_certificates = split_certificates(local_cert_path)

    if local_certificates:
        print(r"""
        /----------------------------\
        SETTING LOCAL SSL CERTIFICATES
        \----------------------------/


        """)
        current_configuration = QSslConfiguration.defaultConfiguration()
        current_certs = current_configuration.caCertificates()
        for certificate in local_certificates:
            current_certs.append(QSslCertificate(certificate))

            current_configuration.setCaCertificates(current_certs)
            QSslConfiguration.setDefaultConfiguration(current_configuration)
Exemplo n.º 15
0
def init():
    """Disable insecure SSL ciphers on old Qt versions."""
    sslconfig = QSslConfiguration.defaultConfiguration()
    default_ciphers = sslconfig.ciphers()
    log.init.vdebug(  # type: ignore[attr-defined]
        "Default Qt ciphers: {}".format(', '.join(c.name()
                                                  for c in default_ciphers)))

    good_ciphers = []
    bad_ciphers = []
    for cipher in default_ciphers:
        if _is_secure_cipher(cipher):
            good_ciphers.append(cipher)
        else:
            bad_ciphers.append(cipher)

    if bad_ciphers:
        log.init.debug("Disabling bad ciphers: {}".format(', '.join(
            c.name() for c in bad_ciphers)))
        sslconfig.setCiphers(good_ciphers)
Exemplo n.º 16
0
    def sslErrorsReply(self, reply, errors):
        """
        Public slot to handle SSL errors for a network reply.
        
        @param reply reference to the reply object (QNetworkReply)
        @param errors list of SSL errors (list of QSslError)
        @return tuple indicating to ignore the SSL errors (one of NotIgnored,
            SystemIgnored or UserIgnored) and indicating a change of the
            default SSL configuration (boolean)
        """
        url = reply.url()
        ignore, defaultChanged = self.sslErrors(errors, url.host(), url.port())
        if ignore:
            if defaultChanged:
                reply.setSslConfiguration(QSslConfiguration.defaultConfiguration())
            reply.ignoreSslErrors()
        else:
            reply.abort()

        return ignore, defaultChanged
Exemplo n.º 17
0
    def createRequest(self, operation, request, device=None):
        if not self.control.job():
            return super().createRequest(operation, request, device)

        url = request.url()
        url_str = url.toString()

        if self.rule_list:
            for r in self.rule_list:
                if r.rule.search(url_str):
                    if r.rule_type == self._reject:
                        logger.debug(self.control.prepend_id('Blocking {}'.format(url_str)))
                        return super().createRequest(operation, QNetworkRequest(QUrl()), device)
                    else:
                        break

        if self.proxy and self.control.job() and self.control.job().is_crawlera:
            scheme = url.scheme()
            if scheme == 'https':
                url.setScheme('http')
                request.setRawHeader(b'X-Crawlera-Use-HTTPS', b'1')
                # TODO Check if this is needed
                request.setSslConfiguration(QSslConfiguration())
                request.setUrl(url)
            elif scheme == 'http':
                pass
            else:
                # We fail any request that is not http or https
                logger.warning(self.control.prepend_id('Unsupported Schema {}'.format(url_str)))
                return super().createRequest(operation, QNetworkRequest(QUrl()), device)

            key = bytes('{}:{}'.format(self.proxy.user(), self.proxy.password()), HTTP_HEADER_CHARSET)
            proxy_auth_value = b'Basic ' + base64.urlsafe_b64encode(key)
            request.setRawHeader(b'Proxy-Authorization', proxy_auth_value)
            request.setRawHeader(b'Proxy-Connection', b'Keep-Alive')
            request.setRawHeader(b'X-Crawlera-Cookies', b'disable')
            request.setRawHeader(b'X-Crawlera-UA', b'desktop')

        network_reply = super().createRequest(operation, request, device)
        network_reply.finished.connect(lambda: self.request_finished(network_reply))
        return network_reply
Exemplo n.º 18
0
    def sslErrorsReply(self, reply, errors):
        """
        Public slot to handle SSL errors for a network reply.
        
        @param reply reference to the reply object (QNetworkReply)
        @param errors list of SSL errors (list of QSslError)
        @return tuple indicating to ignore the SSL errors (one of NotIgnored,
            SystemIgnored or UserIgnored) and indicating a change of the
            default SSL configuration (boolean)
        """
        url = reply.url()
        ignore, defaultChanged = self.sslErrors(errors, url.host(), url.port())
        if ignore:
            if defaultChanged:
                reply.setSslConfiguration(
                    QSslConfiguration.defaultConfiguration())
            reply.ignoreSslErrors()
        else:
            reply.abort()

        return ignore, defaultChanged
Exemplo n.º 19
0
    def _createRequest(self,
                       url: str,
                       basic_auth_username: str = "",
                       basic_auth_password: str = "") -> QNetworkRequest:
        request = QNetworkRequest(url)
        request.setAttribute(QNetworkRequest.FollowRedirectsAttribute, True)
        request.setRawHeader(b"User-Agent", self._user_agent)

        if basic_auth_username and basic_auth_password:
            data = base64.b64encode(
                ("%s:%s" % (basic_auth_username,
                            basic_auth_password)).encode()).decode("utf-8")
            request.setRawHeader(b"Authorization",
                                 ("Basic %s" % data).encode())

        # ignore SSL errors (eg for self-signed certificates)
        ssl_configuration = QSslConfiguration.defaultConfiguration()
        ssl_configuration.setPeerVerifyMode(QSslSocket.VerifyNone)
        request.setSslConfiguration(ssl_configuration)

        return request
Exemplo n.º 20
0
    def start(self) -> None:
        self.stop()  # Ensure that previous requests (if any) are stopped.

        if not self._source_url:
            Logger.log("w", "Unable to start camera stream without target!")
            return

        auth_data = ""
        if self._source_url.userInfo():
            # move auth data to basic authorization header
            auth_data = base64.b64encode(
                self._source_url.userInfo().encode()).decode("utf-8")
            authority = self._source_url.authority()
            self._source_url.setAuthority(authority.rsplit("@", 1)[1])

        self._image_request = QNetworkRequest(self._source_url)
        self._image_request.setAttribute(
            QNetworkRequest.FollowRedirectsAttribute, True)

        if auth_data:
            self._image_request.setRawHeader(b"Authorization",
                                             ("basic %s" % auth_data).encode())

        if self._source_url.scheme().lower() == "https":
            # ignore SSL errors (eg for self-signed certificates)
            ssl_configuration = QSslConfiguration.defaultConfiguration()
            ssl_configuration.setPeerVerifyMode(QSslSocket.VerifyNone)
            self._image_request.setSslConfiguration(ssl_configuration)

        if self._network_manager is None:
            self._network_manager = QNetworkAccessManager()

        self._image_reply = self._network_manager.get(self._image_request)
        self._image_reply.downloadProgress.connect(
            self._onStreamDownloadProgress)

        self._started = True
Exemplo n.º 21
0
from functools import partial

logger = getLogger(__name__)
logger.debug("icons_rc found: %r", viur_admin.ui.icons_rc)  # import guard

if not isPyodide:
    # Setup the SSL-Configuration. We accept only the two known Certificates from google; reject all other
    try:
        css = QtCore.QFile(":resources/cacert.pem")
        css.open(QtCore.QFile.ReadOnly)
        certs = css.readAll()
    except:
        certs = None

    if certs:
        baseSslConfig = QSslConfiguration.defaultConfiguration()
        baseSslConfig.setCaCertificates(QSslCertificate.fromData(certs))
        QSslConfiguration.setDefaultConfiguration(baseSslConfig)
        nam = QNetworkAccessManager()
        _isSecureSSL = True
    else:
        # We got no valid certificate file - accept all SSL connections
        nam = QNetworkAccessManager()

        class SSLFIX(QtCore.QObject):
            def onSSLError(self, networkReply: Any, sslErros: Any) -> None:
                networkReply.ignoreSslErrors()

        _SSLFIX = SSLFIX()
        nam.sslErrors.connect(_SSLFIX.onSSLError)
        _isSecureSSL = False
Exemplo n.º 22
0
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply, QSslConfiguration, QSsl
from PyQt5.QtCore import QUrl


class ForRec(QNetworkAccessManager):
	def Reqest(self,reply):
		print(reply.readAll())
   

if __name__ == '__main__':

	url = "https://api.telegram.org/bot"

	manager = QNetworkAccessManager()
	request = QNetworkRequest()

	config = QSslConfiguration.defaultConfiguration()
	config.setProtocol(QSsl.SecureProtocols)

	request.setSslConfiguration(config)
	request.setUrl(QUrl(url));
	request.setHeader(QNetworkRequest.ServerHeader, "getUpdates")

	#manager.get(request)




Exemplo n.º 23
0
    def sslErrors(self, errors, server, port=-1):
        """
        Public method to handle SSL errors.
        
        @param errors list of SSL errors (list of QSslError)
        @param server name of the server (string)
        @keyparam port value of the port (integer)
        @return tuple indicating to ignore the SSL errors (one of NotIgnored,
            SystemIgnored or UserIgnored) and indicating a change of the
            default SSL configuration (boolean)
        """
        caMerge = {}
        certificateDict = Globals.toDict(
            Preferences.Prefs.settings.value("Ssl/CaCertificatesDict"))
        for caServer in certificateDict:
            caMerge[caServer] = QSslCertificate.fromData(
                certificateDict[caServer])
        caNew = []

        errorStrings = []
        if port != -1:
            server += ":{0:d}".format(port)
        if errors:
            for err in errors:
                if err.error() == QSslError.NoError:
                    continue
                if server in caMerge and err.certificate() in caMerge[server]:
                    continue
                errorStrings.append(err.errorString())
                if not err.certificate().isNull():
                    cert = err.certificate()
                    if cert not in caNew:
                        caNew.append(cert)
        if not errorStrings:
            return E5SslErrorHandler.SystemIgnored, False

        errorString = '.</li><li>'.join(errorStrings)
        ret = E5MessageBox.yesNo(
            None,
            self.tr("SSL Errors"),
            self.tr("""<p>SSL Errors for <br /><b>{0}</b>"""
                    """<ul><li>{1}</li></ul></p>"""
                    """<p>Do you want to ignore these errors?</p>""").format(
                        server, errorString),
            icon=E5MessageBox.Warning)

        if ret:
            caRet = False
            if len(caNew) > 0:
                certinfos = []
                for cert in caNew:
                    certinfos.append(self.__certToString(cert))
                caRet = E5MessageBox.yesNo(
                    None, self.tr("Certificates"),
                    self.tr("""<p>Certificates:<br/>{0}<br/>"""
                            """Do you want to accept all these certificates?"""
                            """</p>""").format("".join(certinfos)))
                if caRet:
                    if server not in caMerge:
                        caMerge[server] = []
                    for cert in caNew:
                        caMerge[server].append(cert)

                    sslCfg = QSslConfiguration.defaultConfiguration()
                    caList = sslCfg.caCertificates()
                    for cert in caNew:
                        caList.append(cert)
                    sslCfg.setCaCertificates(caList)
                    try:
                        sslCfg.setProtocol(QSsl.TlsV1_1OrLater)
                    except AttributeError:
                        sslCfg.setProtocol(QSsl.SecureProtocols)
                    try:
                        sslCfg.setSslOption(QSsl.SslOptionDisableCompression,
                                            True)
                    except AttributeError:
                        pass
                    QSslConfiguration.setDefaultConfiguration(sslCfg)

                    certificateDict = {}
                    for server in caMerge:
                        pems = QByteArray()
                        for cert in caMerge[server]:
                            pems.append(cert.toPem() + b'\n')
                        certificateDict[server] = pems
                    Preferences.Prefs.settings.setValue(
                        "Ssl/CaCertificatesDict", certificateDict)

            return E5SslErrorHandler.UserIgnored, caRet

        else:
            return E5SslErrorHandler.NotIgnored, False
Exemplo n.º 24
0
 def sslErrors(self, errors, server, port=-1):
     """
     Public method to handle SSL errors.
     
     @param errors list of SSL errors (list of QSslError)
     @param server name of the server (string)
     @keyparam port value of the port (integer)
     @return tuple indicating to ignore the SSL errors (one of NotIgnored,
         SystemIgnored or UserIgnored) and indicating a change of the
         default SSL configuration (boolean)
     """
     caMerge = {}
     certificateDict = Globals.toDict(
         Preferences.Prefs.settings.value("Ssl/CaCertificatesDict"))
     for caServer in certificateDict:
         caMerge[caServer] = QSslCertificate.fromData(
             certificateDict[caServer])
     caNew = []
     
     errorStrings = []
     if port != -1:
         server += ":{0:d}".format(port)
     if errors:
         for err in errors:
             if err.error() == QSslError.NoError:
                 continue
             if server in caMerge and err.certificate() in caMerge[server]:
                 continue
             errorStrings.append(err.errorString())
             if not err.certificate().isNull():
                 cert = err.certificate()
                 if cert not in caNew:
                     caNew.append(cert)
     if not errorStrings:
         return E5SslErrorHandler.SystemIgnored, False
     
     errorString = '.</li><li>'.join(errorStrings)
     ret = E5MessageBox.yesNo(
         None,
         self.tr("SSL Errors"),
         self.tr("""<p>SSL Errors for <br /><b>{0}</b>"""
                 """<ul><li>{1}</li></ul></p>"""
                 """<p>Do you want to ignore these errors?</p>""")
         .format(server, errorString),
         icon=E5MessageBox.Warning)
     
     if ret:
         caRet = False
         if len(caNew) > 0:
             certinfos = []
             for cert in caNew:
                 certinfos.append(self.__certToString(cert))
             caRet = E5MessageBox.yesNo(
                 None,
                 self.tr("Certificates"),
                 self.tr(
                     """<p>Certificates:<br/>{0}<br/>"""
                     """Do you want to accept all these certificates?"""
                     """</p>""")
                 .format("".join(certinfos)))
             if caRet:
                 if server not in caMerge:
                     caMerge[server] = []
                 for cert in caNew:
                     caMerge[server].append(cert)
                 
                 sslCfg = QSslConfiguration.defaultConfiguration()
                 caList = sslCfg.caCertificates()
                 for cert in caNew:
                     caList.append(cert)
                 sslCfg.setCaCertificates(caList)
                 sslCfg.setProtocol(QSsl.AnyProtocol)
                 QSslConfiguration.setDefaultConfiguration(sslCfg)
                 
                 certificateDict = {}
                 for server in caMerge:
                     pems = QByteArray()
                     for cert in caMerge[server]:
                         pems.append(cert.toPem() + b'\n')
                     certificateDict[server] = pems
                 Preferences.Prefs.settings.setValue(
                     "Ssl/CaCertificatesDict",
                     certificateDict)
         
         return E5SslErrorHandler.UserIgnored, caRet
     
     else:
         return E5SslErrorHandler.NotIgnored, False
Exemplo n.º 25
0
class SSLConfig(_SSLConfig):
    """Qt-based implementation of SSLConfig.

    This implementation does a few things to help:

    * Automate QSslConfiguration.set* calls and ensure that they happen up
      front, which is important when some may have no effect later.

    * Hide the dance of creating a QSslKey.

    * Makes it easier to set SSL options, and sets defaults marked in Qt docs
      as more secure, so that less secure options must be explicitly specified.
    """

    default_options = _SSLConfig.default_options.copy()
    default_options.update({
        # Prevent injection of plaintext into SSL sessions.
        # This option isn't available for other backends.
        "legacy renegotiation": False,

        # Prevents BEAST, but "causes problems with a large number of servers".
        # Yet it works with BCS, so we should use it when it's available.
        "empty_fragments": False,
    })

    def __init__(
        self,
        protocol=None,
        key=None,
        options=None,
    ):
        super(SSLConfig, self).__init__(
            protocol=protocol,
            key=key,
            options=options,
        )

        # Set up implementation-specific state...

        # QSslConfiguration is a bag of data we need to talk to Qt. Its
        # attributes must be set using its various setWhatever methods.
        self._q_ssl_config = QSslConfiguration()

        # Get a protocol constant Qt understands, or cry to the user.
        q_ssl_protocol = _PROTOCOL_CHOICES.get(self.protocol)
        if q_ssl_protocol is None:
            raise InvalidSSLConfig("unknown protocol for Qt: {0!r}".format(
                self.protocol))
        # Hang on to it just in case we possibly need it, e.g. debugger
        self._q_ssl_protocol = q_ssl_protocol

        # Otherwise, tell Qt about the protocol.
        # n.b.: setting this after connection starts has no effect, so we
        # definitely want to do it here instead of deferring this.
        self._q_ssl_config.setProtocol(q_ssl_protocol)

        # If we have an SSLKey, have it make a QSslKey and tell Qt about it.
        if self.key:
            q_ssl_key = self.key.to_q_ssl_key()
            self._q_ssl_config.setPrivateKey(q_ssl_key)
        else:
            q_ssl_key = None
        self._q_ssl_key = q_ssl_key

        # Process self.options
        self._set_options()

    def _set_options(self):
        """Internal: convert options to set QSSLConfiguration option flags.
        """
        for key, value in self.options.items():

            # Get the constant used by PyQt
            option = _PROTOCOL_OPTIONS.get(key.lower().replace("_", " "))

            # Make sure we don't fail silently with unrecognized options
            if option is None:
                raise InvalidSSLConfig(
                    "unknown option for Qt: {0!r}".format(key))

            # All the Qt options are "Disable*", inverting the bools.
            self._q_ssl_config.setSslOption(option, not value)
Exemplo n.º 26
0
 def __init__(self, url, configuration, parent=None):
     """
     Constructor
     
     @param url URL to show SSL info for (QUrl)
     @param configuration SSL configuration (QSslConfiguration)
     @param parent reference to the parent widget (QWidget)
     """
     super(E5SslInfoWidget, self).__init__(parent)
     
     self.__url = QUrl(url)
     self.__configuration = QSslConfiguration(configuration)
     
     self.setMinimumWidth(400)
     
     certList = self.__configuration.peerCertificateChain()
     if certList:
         cert = certList[0]
     else:
         cert = QSslCertificate()
     
     layout = QGridLayout(self)
     rows = 0
     
     ##########################################
     ## Identity Information
     ##########################################
     imageLabel = QLabel(self)
     layout.addWidget(imageLabel, rows, 0, Qt.AlignCenter)
     
     label = QLabel(self)
     label.setWordWrap(True)
     label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
     label.setText(self.tr("Identity"))
     font = label.font()
     font.setBold(True)
     label.setFont(font)
     layout.addWidget(label, rows, 1)
     rows += 1
     
     label = QLabel(self)
     label.setWordWrap(True)
     if cert.isNull():
         label.setText(self.tr(
             "Warning: this site is NOT carrying a certificate."))
         imageLabel.setPixmap(UI.PixmapCache.getPixmap("securityLow32.png"))
     else:
         if qVersion() >= "5.0.0":
             valid = not cert.isBlacklisted()
         else:
             valid = cert.isValid()
         if valid:
             if qVersion() >= "5.0.0":
                 txt = ", ".join(
                     cert.issuerInfo(QSslCertificate.CommonName))
             else:
                 txt = cert.issuerInfo(QSslCertificate.CommonName)
             label.setText(self.tr(
                 "The certificate for this site is valid"
                 " and has been verified by:\n{0}").format(
                 Utilities.decodeString(txt)))
             imageLabel.setPixmap(
                 UI.PixmapCache.getPixmap("securityHigh32.png"))
         else:
             label.setText(self.tr(
                 "The certificate for this site is NOT valid."))
             imageLabel.setPixmap(
                 UI.PixmapCache.getPixmap("securityLow32.png"))
         layout.addWidget(label, rows, 1)
         rows += 1
         
         label = QLabel(self)
         label.setWordWrap(True)
         label.setText(
             '<a href="moresslinfos">' +
             self.tr("Certificate Information") + "</a>")
         label.linkActivated.connect(self.__showCertificateInfos)
         layout.addWidget(label, rows, 1)
         rows += 1
     
     ##########################################
     ## Identity Information
     ##########################################
     imageLabel = QLabel(self)
     layout.addWidget(imageLabel, rows, 0, Qt.AlignCenter)
     
     label = QLabel(self)
     label.setWordWrap(True)
     label.setText(self.tr("Encryption"))
     font = label.font()
     font.setBold(True)
     label.setFont(font)
     layout.addWidget(label, rows, 1)
     rows += 1
     
     cipher = self.__configuration.sessionCipher()
     if cipher.isNull():
         label = QLabel(self)
         label.setWordWrap(True)
         label.setText(self.tr(
             'Your connection to "{0}" is NOT encrypted.\n').format(
             self.__url.host()))
         layout.addWidget(label, rows, 1)
         imageLabel.setPixmap(UI.PixmapCache.getPixmap("securityLow32.png"))
         rows += 1
     else:
         label = QLabel(self)
         label.setWordWrap(True)
         label.setText(self.tr(
             'Your connection to "{0}" is encrypted.').format(
             self.__url.host()))
         layout.addWidget(label, rows, 1)
         
         proto = cipher.protocol()
         if proto == QSsl.SslV3:
             sslVersion = "SSL 3.0"
             imageLabel.setPixmap(
                 UI.PixmapCache.getPixmap("securityLow32.png"))
         elif proto == QSsl.TlsV1SslV3:
             sslVersion = "TLS 1.0/SSL 3.0"
             imageLabel.setPixmap(
                 UI.PixmapCache.getPixmap("securityLow32.png"))
         elif proto == QSsl.SslV2:
             sslVersion = "SSL 2.0"
             imageLabel.setPixmap(
                 UI.PixmapCache.getPixmap("securityLow32.png"))
         else:
             sslVersion = self.tr("unknown")
             imageLabel.setPixmap(
                 UI.PixmapCache.getPixmap("securityLow32.png"))
         if qVersion() >= "5.0.0":
             if proto == QSsl.TlsV1_0:
                 sslVersion = "TLS 1.0"
                 imageLabel.setPixmap(
                     UI.PixmapCache.getPixmap("securityHigh32.png"))
             elif proto == QSsl.TlsV1_1:
                 sslVersion = "TLS 1.1"
                 imageLabel.setPixmap(
                     UI.PixmapCache.getPixmap("securityHigh32.png"))
             elif proto == QSsl.TlsV1_2:
                 sslVersion = "TLS 1.2"
                 imageLabel.setPixmap(
                     UI.PixmapCache.getPixmap("securityHigh32.png"))
         else:
             if proto == QSsl.TlsV1:
                 sslVersion = "TLS 1.0"
                 imageLabel.setPixmap(
                     UI.PixmapCache.getPixmap("securityHigh32.png"))
         rows += 1
         
         label = QLabel(self)
         label.setWordWrap(True)
         label.setText(self.tr(
             "It uses protocol: {0}").format(sslVersion))
         layout.addWidget(label, rows, 1)
         rows += 1
         
         label = QLabel(self)
         label.setWordWrap(True)
         label.setText(self.tr(
             "It is encrypted using {0} at {1} bits, "
             "with {2} for message authentication and "
             "{3} as key exchange mechanism.\n\n").format(
             cipher.encryptionMethod(),
             cipher.usedBits(),
             cipher.authenticationMethod(),
             cipher.keyExchangeMethod()))
         layout.addWidget(label, rows, 1)
         rows += 1
Exemplo n.º 27
0
    os.environ["DYLD_FALLBACK_LIBRARY_PATH"] = old_env

# WORKAROUND: CURA-6739
# Similar CTM file loading fix for Linux, but NOTE THAT this doesn't work directly with Python 3.5.7. There's a fix
# for ctypes.util.find_library() in Python 3.6 and 3.7. That fix makes sure that find_library() will check
# LD_LIBRARY_PATH. With Python 3.5, that fix needs to be backported to make this workaround work.
if Platform.isLinux() and getattr(sys, "frozen", False):
    old_env = os.environ.get("LD_LIBRARY_PATH", "")
    # This is where libopenctm.so is in the AppImage.
    search_path = os.path.join(CuraApplication.getInstallPrefix(), "bin")
    path_list = old_env.split(":")
    if search_path not in path_list:
        path_list.append(search_path)
    os.environ["LD_LIBRARY_PATH"] = ":".join(path_list)
    import trimesh.exchange.load
    os.environ["LD_LIBRARY_PATH"] = old_env

# WORKAROUND: Cura#5488
# When using the KDE qqc2-desktop-style, the UI layout is completely broken, and
# even worse, it crashes when switching to the "Preview" pane.
if Platform.isLinux():
    os.environ["QT_QUICK_CONTROLS_STYLE"] = "default"

if ApplicationMetadata.CuraDebugMode:
    ssl_conf = QSslConfiguration.defaultConfiguration()
    ssl_conf.setPeerVerifyMode(QSslSocket.VerifyNone)
    QSslConfiguration.setDefaultConfiguration(ssl_conf)

app = CuraApplication()
app.run()
Exemplo n.º 28
0
    def __init__(self, url, configuration, parent=None):
        """
        Constructor
        
        @param url URL to show SSL info for (QUrl)
        @param configuration SSL configuration (QSslConfiguration)
        @param parent reference to the parent widget (QWidget)
        """
        super(E5SslInfoWidget, self).__init__(parent)

        self.__url = QUrl(url)
        self.__configuration = QSslConfiguration(configuration)

        self.setMinimumWidth(400)

        certList = self.__configuration.peerCertificateChain()
        if certList:
            cert = certList[0]
        else:
            cert = QSslCertificate()

        layout = QGridLayout(self)
        rows = 0

        ##########################################
        ## Identity Information
        ##########################################
        imageLabel = QLabel(self)
        layout.addWidget(imageLabel, rows, 0, Qt.AlignCenter)

        label = QLabel(self)
        label.setWordWrap(True)
        label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        label.setText(self.tr("Identity"))
        font = label.font()
        font.setBold(True)
        label.setFont(font)
        layout.addWidget(label, rows, 1)
        rows += 1

        label = QLabel(self)
        label.setWordWrap(True)
        if cert.isNull():
            label.setText(
                self.tr("Warning: this site is NOT carrying a certificate."))
            imageLabel.setPixmap(UI.PixmapCache.getPixmap("securityLow32.png"))
        else:
            if qVersion() >= "5.0.0":
                valid = not cert.isBlacklisted()
            else:
                valid = cert.isValid()
            if valid:
                if qVersion() >= "5.0.0":
                    txt = ", ".join(cert.issuerInfo(
                        QSslCertificate.CommonName))
                else:
                    txt = cert.issuerInfo(QSslCertificate.CommonName)
                label.setText(
                    self.tr("The certificate for this site is valid"
                            " and has been verified by:\n{0}").format(
                                Utilities.decodeString(txt)))
                imageLabel.setPixmap(
                    UI.PixmapCache.getPixmap("securityHigh32.png"))
            else:
                label.setText(
                    self.tr("The certificate for this site is NOT valid."))
                imageLabel.setPixmap(
                    UI.PixmapCache.getPixmap("securityLow32.png"))
            layout.addWidget(label, rows, 1)
            rows += 1

            label = QLabel(self)
            label.setWordWrap(True)
            label.setText('<a href="moresslinfos">' +
                          self.tr("Certificate Information") + "</a>")
            label.linkActivated.connect(self.__showCertificateInfos)
            layout.addWidget(label, rows, 1)
            rows += 1

        ##########################################
        ## Identity Information
        ##########################################
        imageLabel = QLabel(self)
        layout.addWidget(imageLabel, rows, 0, Qt.AlignCenter)

        label = QLabel(self)
        label.setWordWrap(True)
        label.setText(self.tr("Encryption"))
        font = label.font()
        font.setBold(True)
        label.setFont(font)
        layout.addWidget(label, rows, 1)
        rows += 1

        cipher = self.__configuration.sessionCipher()
        if cipher.isNull():
            label = QLabel(self)
            label.setWordWrap(True)
            label.setText(
                self.tr('Your connection to "{0}" is NOT encrypted.\n').format(
                    self.__url.host()))
            layout.addWidget(label, rows, 1)
            imageLabel.setPixmap(UI.PixmapCache.getPixmap("securityLow32.png"))
            rows += 1
        else:
            label = QLabel(self)
            label.setWordWrap(True)
            label.setText(
                self.tr('Your connection to "{0}" is encrypted.').format(
                    self.__url.host()))
            layout.addWidget(label, rows, 1)

            proto = cipher.protocol()
            if proto == QSsl.SslV3:
                sslVersion = "SSL 3.0"
                imageLabel.setPixmap(
                    UI.PixmapCache.getPixmap("securityHigh32.png"))
            elif proto == QSsl.TlsV1SslV3:
                sslVersion = "TLS 1.0/SSL 3.0"
                imageLabel.setPixmap(
                    UI.PixmapCache.getPixmap("securityHigh32.png"))
            elif proto == QSsl.SslV2:
                sslVersion = "SSL 2.0"
                imageLabel.setPixmap(
                    UI.PixmapCache.getPixmap("securityLow32.png"))
            else:
                sslVersion = self.tr("unknown")
                imageLabel.setPixmap(
                    UI.PixmapCache.getPixmap("securityLow32.png"))
            if qVersion() >= "5.0.0":
                if proto == QSsl.TlsV1_0:
                    sslVersion = "TLS 1.0"
                    imageLabel.setPixmap(
                        UI.PixmapCache.getPixmap("securityHigh32.png"))
                elif proto == QSsl.TlsV1_1:
                    sslVersion = "TLS 1.1"
                    imageLabel.setPixmap(
                        UI.PixmapCache.getPixmap("securityHigh32.png"))
                elif proto == QSsl.TlsV1_2:
                    sslVersion = "TLS 1.2"
                    imageLabel.setPixmap(
                        UI.PixmapCache.getPixmap("securityHigh32.png"))
            else:
                if proto == QSsl.TlsV1:
                    sslVersion = "TLS 1.0"
                    imageLabel.setPixmap(
                        UI.PixmapCache.getPixmap("securityHigh32.png"))
            rows += 1

            label = QLabel(self)
            label.setWordWrap(True)
            label.setText(self.tr("It uses protocol: {0}").format(sslVersion))
            layout.addWidget(label, rows, 1)
            rows += 1

            label = QLabel(self)
            label.setWordWrap(True)
            label.setText(
                self.tr("It is encrypted using {0} at {1} bits, "
                        "with {2} for message authentication and "
                        "{3} as key exchange mechanism.\n\n").format(
                            cipher.encryptionMethod(), cipher.usedBits(),
                            cipher.authenticationMethod(),
                            cipher.keyExchangeMethod()))
            layout.addWidget(label, rows, 1)
            rows += 1
Exemplo n.º 29
0
class NetWorker(QObject):
    ifcAddrChanged = pyqtSignal(str, name='ifcAddrChanged', arguments=['ip'])
    currentIfcAddrChanged = pyqtSignal()
    wifiStatus = pyqtSignal(str,
                            str,
                            int,
                            int,
                            name='wifiStatus',
                            arguments=['essid', 'freq', 'quality', 'level'])
    wifiStatusChanged = pyqtSignal()

    @pyqtProperty(str, notify=currentIfcAddrChanged)
    def currentIfcAddr(self):
        return self.ifcAddr.toString()

    @pyqtProperty(str, notify=wifiStatusChanged)
    def currentWifiESSID(self):
        return self.essid

    @pyqtProperty(str, notify=wifiStatusChanged)
    def currentWifiFreq(self):
        return self.freq

    @pyqtProperty(int, notify=wifiStatusChanged)
    def currentWifiQuality(self):
        return self.quality

    @pyqtProperty(int, notify=wifiStatusChanged)
    def currentWifiLevel(self):
        return self.level

    def __init__(self, loglevel='WARNING', ifcName='wlan0'):
        QObject.__init__(self)

        self.logger = Logger(name='ratt.networker')
        self.logger.setLogLevelStr(loglevel)
        self.debug = self.logger.isDebug()

        self.mgr = QNetworkAccessManager()
        self.sslConfig = QSslConfiguration()
        self.sslSupported = QSslSocket.supportsSsl()

        self.setAuth()
        self.setSSLCertConfig()

        self.mgr.authenticationRequired.connect(
            self.handleAuthenticationRequired)

        self.ifcName = ifcName
        self.ifcAddr = QHostAddress()

        self.statusTimer = QTimer()
        self.statusTimer.setSingleShot(False)
        self.statusTimer.timeout.connect(self.slotStatusTimer)
        self.statusTimer.start(5000)

        self.essid = ''
        self.freq = ''
        self.quality = 0
        self.level = 0

    def slotStatusTimer(self):
        ip = self.getIfcAddress(ifc=self.ifcName)

        if ip != self.ifcAddr:
            self.ifcAddr = ip
            self.ifcAddrChanged.emit(ip.toString())
            self.currentIfcAddrChanged.emit()

        results = {}
        if self.getWifiStatus(results):
            self.essid = results['essid']
            self.freq = results['freq']
            self.quality = results['quality']
            self.level = results['level']
            self.wifiStatus.emit(self.essid, self.freq, self.quality,
                                 self.level)
            self.wifiStatusChanged.emit()

    # ['wlan0', 'IEEE', '802.11', 'ESSID:"FooBar"', 'Mode:Managed', 'Frequency:2.412',
    # 'GHz', 'Access', 'Point:', '00:11:22:33:44:55', 'Bit', 'Rate=65', 'Mb/s', 'Tx-Power=31',
    # 'dBm', 'Retry', 'short', 'limit:7', 'RTS', 'thr:off', 'Fragment', 'thr:off', 'Power',
    # 'Management:on', 'Link', 'Quality=43/70', 'Signal', 'level=-67', 'dBm', 'Rx', 'invalid',
    # 'nwid:0', 'Rx', 'invalid', 'crypt:0', 'Rx', 'invalid', 'frag:0', 'Tx', 'excessive', 'retries:113',
    # 'Invalid', 'misc:0', 'Missed', 'beacon:0']
    def getWifiStatus(self, res):
        try:
            iw = getoutput('/sbin/iwconfig %s' % self.ifcName)

            fields = iw.split()

            for field in fields:
                if field.find('ESSID') != -1:
                    res['essid'] = field.split('"')[1]
                elif field.find('Frequency') != -1:
                    res['freq'] = field.split(':')[1]
                elif field.find('Quality') != -1:
                    frac = field.split('=')[1]
                    (n, d) = frac.split('/')
                    q = int(n) * 100 / int(d)
                    res['quality'] = q
                elif field.find('level') != -1:
                    res['level'] = int(field.split('=')[1])
        except:
            return False

        return True

    def getIfcAddress(self, ifc):
        myIfc = QNetworkInterface.interfaceFromName(ifc)
        addrList = myIfc.addressEntries()

        for addr in addrList:
            if addr.ip().protocol() == QAbstractSocket.IPv4Protocol:
                return addr.ip()

        return QHostAddress()

    def setAuth(self, user='', password=''):
        self.user = user
        self.password = password

    def setSSLCertConfig(self,
                         enabled=False,
                         caCertFile='',
                         clientCertFile='',
                         clientKeyFile=''):
        self.sslEnabled = enabled

        if self.sslSupported and self.sslEnabled:
            self.caCertFile = caCertFile
            self.clientCertFile = clientCertFile
            self.clientKeyFile = clientKeyFile

            self.configureCerts()

    def get(self, url):
        self.logger.debug('get url=%s' % url.toString())

        request = QNetworkRequest(QUrl(url))
        request.setRawHeader("User-Agent", "RATT")

        if self.sslSupported and self.sslEnabled:
            request.setSslConfiguration(self.sslConfig)

        reply = self.mgr.get(request)

        if self.sslSupported and self.sslEnabled:
            reply.sslErrors.connect(self.handleSSLErrors)

        return reply

    def buildRequest(self, url):
        request = QNetworkRequest(QUrl(url))
        request.setHeader(QNetworkRequest.ContentTypeHeader,
                          "application/x-www-form-urlencoded")

        return request

    def buildQuery(self, vars):
        query = str()
        for key in vars:
            value = vars[key]
            sep = '&' if query != '' else ''
            query = query + '%s%s=%s' % (sep, key, value)

        return query

    def post(self, request, query):
        self.logger.debug('post url=%s query=%s' %
                          (request.url().toString(), query))

        if self.sslSupported and self.sslEnabled:
            request.setSslConfiguration(self.sslConfig)

        bytearray = QByteArray()
        bytearray.append(query)

        reply = self.mgr.post(request, bytearray)

        if self.sslSupported and self.sslEnabled:
            self.mgr.sslErrors.connect(self.handleSSLErrors)

        return reply

    def handleSSLErrors(self, reply, errors):
        for err in errors:
            self.logger.error('SSL errors:' + err.errorString())

    def handleAuthenticationRequired(self, reply, authenticator):
        if self.user == '' and self.password == '':
            self.logger.warning(
                'authentication required and no user/password set')

        authenticator.setUser(self.user)
        authenticator.setPassword(self.password)

    def configureCerts(self):
        ## import the private client key
        privateKeyFile = QFile(self.clientKeyFile)
        privateKeyFile.open(QIODevice.ReadOnly)
        privateKey = QSslKey(privateKeyFile, QSsl.Rsa)

        if privateKey.isNull():
            self.logger.warning('SSL private key is null')
        else:
            self.sslConfig.setPrivateKey(privateKey)

        ## import the client certificate
        certFile = QFile(self.clientCertFile)
        certFile.open(QIODevice.ReadOnly)
        cert = QSslCertificate(certFile)
        self.sslConfig.setLocalCertificate(cert)

        ## import the self-signed CA certificate
        caCertFile = QFile(self.caCertFile)
        caCertFile.open(QIODevice.ReadOnly)
        caCert = QSslCertificate(caCertFile)

        ## add self-signed CA cert to the other CA certs
        caCertList = self.sslConfig.caCertificates()
        caCertList.append(caCert)
        self.sslConfig.setCaCertificates(caCertList)
Exemplo n.º 30
0
class E5SslInfoWidget(QMenu):
    """
    Class implementing a widget to show SSL certificate infos.
    """
    def __init__(self, url, configuration, parent=None):
        """
        Constructor
        
        @param url URL to show SSL info for (QUrl)
        @param configuration SSL configuration (QSslConfiguration)
        @param parent reference to the parent widget (QWidget)
        """
        super(E5SslInfoWidget, self).__init__(parent)

        self.__url = QUrl(url)
        self.__configuration = QSslConfiguration(configuration)

        self.setMinimumWidth(400)

        certList = self.__configuration.peerCertificateChain()
        if certList:
            cert = certList[0]
        else:
            cert = QSslCertificate()

        layout = QGridLayout(self)
        rows = 0

        ##########################################
        ## Identity Information
        ##########################################
        imageLabel = QLabel(self)
        layout.addWidget(imageLabel, rows, 0, Qt.AlignCenter)

        label = QLabel(self)
        label.setWordWrap(True)
        label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        label.setText(self.tr("Identity"))
        font = label.font()
        font.setBold(True)
        label.setFont(font)
        layout.addWidget(label, rows, 1)
        rows += 1

        label = QLabel(self)
        label.setWordWrap(True)
        if cert.isNull():
            label.setText(
                self.tr("Warning: this site is NOT carrying a certificate."))
            imageLabel.setPixmap(UI.PixmapCache.getPixmap("securityLow32.png"))
        else:
            valid = not cert.isBlacklisted()
            if valid:
                txt = ", ".join(cert.issuerInfo(QSslCertificate.CommonName))
                label.setText(
                    self.tr("The certificate for this site is valid"
                            " and has been verified by:\n{0}").format(
                                Utilities.decodeString(txt)))
                imageLabel.setPixmap(
                    UI.PixmapCache.getPixmap("securityHigh32.png"))
            else:
                label.setText(
                    self.tr("The certificate for this site is NOT valid."))
                imageLabel.setPixmap(
                    UI.PixmapCache.getPixmap("securityLow32.png"))
            layout.addWidget(label, rows, 1)
            rows += 1

            label = QLabel(self)
            label.setWordWrap(True)
            label.setText('<a href="moresslinfos">' +
                          self.tr("Certificate Information") + "</a>")
            label.linkActivated.connect(self.__showCertificateInfos)
            layout.addWidget(label, rows, 1)
            rows += 1

        ##########################################
        ## Identity Information
        ##########################################
        imageLabel = QLabel(self)
        layout.addWidget(imageLabel, rows, 0, Qt.AlignCenter)

        label = QLabel(self)
        label.setWordWrap(True)
        label.setText(self.tr("Encryption"))
        font = label.font()
        font.setBold(True)
        label.setFont(font)
        layout.addWidget(label, rows, 1)
        rows += 1

        cipher = self.__configuration.sessionCipher()
        if cipher.isNull():
            label = QLabel(self)
            label.setWordWrap(True)
            label.setText(
                self.tr('Your connection to "{0}" is NOT encrypted.\n').format(
                    self.__url.host()))
            layout.addWidget(label, rows, 1)
            imageLabel.setPixmap(UI.PixmapCache.getPixmap("securityLow32.png"))
            rows += 1
        else:
            label = QLabel(self)
            label.setWordWrap(True)
            label.setText(
                self.tr('Your connection to "{0}" is encrypted.').format(
                    self.__url.host()))
            layout.addWidget(label, rows, 1)

            proto = cipher.protocol()
            if proto == QSsl.SslV3:
                sslVersion = "SSL 3.0"
                imageLabel.setPixmap(
                    UI.PixmapCache.getPixmap("securityLow32.png"))
            elif proto == QSsl.TlsV1SslV3:
                sslVersion = "TLS 1.0/SSL 3.0"
                imageLabel.setPixmap(
                    UI.PixmapCache.getPixmap("securityLow32.png"))
            elif proto == QSsl.SslV2:
                sslVersion = "SSL 2.0"
                imageLabel.setPixmap(
                    UI.PixmapCache.getPixmap("securityLow32.png"))
            else:
                sslVersion = self.tr("unknown")
                imageLabel.setPixmap(
                    UI.PixmapCache.getPixmap("securityLow32.png"))
            if proto == QSsl.TlsV1_0:
                sslVersion = "TLS 1.0"
                imageLabel.setPixmap(
                    UI.PixmapCache.getPixmap("securityHigh32.png"))
            elif proto == QSsl.TlsV1_1:
                sslVersion = "TLS 1.1"
                imageLabel.setPixmap(
                    UI.PixmapCache.getPixmap("securityHigh32.png"))
            elif proto == QSsl.TlsV1_2:
                sslVersion = "TLS 1.2"
                imageLabel.setPixmap(
                    UI.PixmapCache.getPixmap("securityHigh32.png"))
            try:
                # Qt 5.12 and newer
                if proto == QSsl.TlsV1_2:
                    sslVersion = "TLS 1.2"
                    imageLabel.setPixmap(
                        UI.PixmapCache.getPixmap("securityHigh32.png"))
            except AttributeError:
                pass
            rows += 1

            label = QLabel(self)
            label.setWordWrap(True)
            label.setText(self.tr("It uses protocol: {0}").format(sslVersion))
            layout.addWidget(label, rows, 1)
            rows += 1

            label = QLabel(self)
            label.setWordWrap(True)
            label.setText(
                self.tr("It is encrypted using {0} at {1} bits, "
                        "with {2} for message authentication and "
                        "{3} as key exchange mechanism.\n\n").format(
                            cipher.encryptionMethod(), cipher.usedBits(),
                            cipher.authenticationMethod(),
                            cipher.keyExchangeMethod()))
            layout.addWidget(label, rows, 1)
            rows += 1

    def showAt(self, pos):
        """
        Public method to show the widget.
        
        @param pos position to show at (QPoint)
        """
        self.adjustSize()
        xpos = pos.x() - self.width()
        if xpos < 0:
            xpos = 10
        p = QPoint(xpos, pos.y() + 10)
        self.move(p)
        self.show()

    def __showCertificateInfos(self):
        """
        Private slot to show certificate information.
        """
        from .E5SslCertificatesInfoDialog import E5SslCertificatesInfoDialog
        dlg = E5SslCertificatesInfoDialog(
            self.__configuration.peerCertificateChain())
        dlg.exec_()

    def accept(self):
        """
        Public method to accept the widget.
        """
        self.close()