Пример #1
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()
Пример #2
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)
Пример #3
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)
Пример #4
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()
Пример #5
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)
Пример #6
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)
 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)
Пример #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)
Пример #9
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)
Пример #10
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
Пример #11
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
Пример #12
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
Пример #13
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
Пример #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)
Пример #15
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)
Пример #16
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
Пример #17
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)




Пример #18
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
Пример #19
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()
Пример #20
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