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)
def __importCertificate(self): """ Private method to read a certificate. @return certificates read (list of QSslCertificate) """ fname = E5FileDialog.getOpenFileName( self, self.tr("Import Certificate"), "", self.tr("Certificate Files (*.pem *.crt *.der *.cer *.ca);;" "All Files (*)")) if fname: f = QFile(fname) if not f.open(QIODevice.ReadOnly): E5MessageBox.critical( self, self.tr("Export Certificate"), self.tr( """<p>The certificate could not be read from file""" """ <b>{0}</b></p><p>Error: {1}</p>""") .format(fname, f.errorString())) return [] crt = f.readAll() f.close() cert = QSslCertificate.fromData(crt, QSsl.Pem) if not cert: cert = QSslCertificate.fromData(crt, QSsl.Der) return cert return []
def __importCertificate(self): """ Private method to read a certificate. @return certificates read (list of QSslCertificate) """ fname = E5FileDialog.getOpenFileName( self, self.tr("Import Certificate"), "", self.tr("Certificate Files (*.pem *.crt *.der *.cer *.ca);;" "All Files (*)"), ) if fname: f = QFile(fname) if not f.open(QIODevice.ReadOnly): E5MessageBox.critical( self, self.tr("Export Certificate"), self.tr( """<p>The certificate could not be read from file""" """ <b>{0}</b></p><p>Error: {1}</p>""" ).format(fname, f.errorString()), ) return [] crt = f.readAll() f.close() cert = QSslCertificate.fromData(crt, QSsl.Pem) if not cert: cert = QSslCertificate.fromData(crt, QSsl.Der) return cert return []
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)
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 __getSystemCaCertificates(self): """ Private method to get the list of system certificates. @return list of system certificates (list of QSslCertificate) """ caList = QSslCertificate.fromData(Globals.toByteArray( Preferences.Prefs.settings.value("Ssl/SystemCertificates"))) if not caList: caList = QSslSocket.systemCaCertificates() return caList
def on_caViewButton_clicked(self): """ Private slot to show data of the selected CA certificate. """ try: from E5Network.E5SslCertificatesInfoDialog import E5SslCertificatesInfoDialog cert = QSslCertificate.fromData(self.caCertificatesTree.currentItem().data(0, self.CertRole)) dlg = E5SslCertificatesInfoDialog(cert, self) dlg.exec_() except ImportError: pass
def __populateServerCertificatesTree(self): """ Private slot to populate the server certificates tree. """ certificateDict = Globals.toDict(Preferences.Prefs.settings.value("Ssl/CaCertificatesDict")) for server in certificateDict: for cert in QSslCertificate.fromData(certificateDict[server]): self.__createServerCertificateEntry(server, cert) self.serversCertificatesTree.expandAll() for i in range(self.serversCertificatesTree.columnCount()): self.serversCertificatesTree.resizeColumnToContents(i)
def __init__(self): super().__init__() self.clientSocket = ClientSocket(QSslSocket()) self.socket = self.clientSocket.socket self.sendStream = self.clientSocket.sendStream self.clientSocket.setReceiveHandler(self.handleConnectorReceive) self.socket.setCaCertificates( [QSslCertificate(base64.b64decode(certificate))]) self.socket.encrypted.connect(self.handleConnected) self.socket.error.connect(self.handleError) self.socket.connectToHostEncrypted(Client.serverSettings.address, listenPort, QIODevice.ReadWrite, QSslSocket.IPv4Protocol)
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 __populateServerCertificatesTree(self): """ Private slot to populate the server certificates tree. """ certificateDict = Globals.toDict( Preferences.Prefs.settings.value("Ssl/CaCertificatesDict")) for server in certificateDict: for cert in QSslCertificate.fromData(certificateDict[server]): self.__createServerCertificateEntry(server, cert) self.serversCertificatesTree.expandAll() for i in range(self.serversCertificatesTree.columnCount()): self.serversCertificatesTree.resizeColumnToContents(i)
def on_caViewButton_clicked(self): """ Private slot to show data of the selected CA certificate. """ try: from E5Network.E5SslCertificatesInfoDialog import \ E5SslCertificatesInfoDialog cert = QSslCertificate.fromData( self.caCertificatesTree.currentItem().data(0, self.CertRole)) dlg = E5SslCertificatesInfoDialog(cert, self) dlg.exec_() except ImportError: pass
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 incomingConnection(self, handle): socket = QSslSocket() if socket.setSocketDescriptor(handle): if blockedAddresses.get(socket.peerAddress(), 1) <= 0: socket.close() return def handleSslErrors(errors, socket = socket): address = socket.peerAddress().toString() log('SSL errors for peer ' + address + ' : ' + ', '.join([x.errorString() for x in errors])) socket.sslErrors.connect(handleSslErrors) socket.setLocalCertificate(QSslCertificate(base64.b64decode(certificate))) socket.setPrivateKey(QSslKey(base64.b64decode(privatekey), QSsl.Rsa)) socket.startServerEncryption() self.addPendingConnection(socket)
def on_viewButton_clicked(self): """ Private slot to show data of the selected certificate. """ try: from E5Network.E5SslCertificatesInfoDialog import ( E5SslCertificatesInfoDialog ) cert = QSslCertificate.fromData( self.certificatesTree.selectedItems()[0].data( 0, self.CertRole)) dlg = E5SslCertificatesInfoDialog(cert, self) dlg.exec_() except ImportError: pass
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)
def on_serversDeleteButton_clicked(self): """ Private slot to delete the selected server certificate. """ itm = self.serversCertificatesTree.currentItem() res = E5MessageBox.yesNo( self, self.tr("Delete Server Certificate"), self.tr("""<p>Shall the server certificate really be""" """ deleted?</p><p>{0}</p>""" """<p>If the server certificate is deleted, the""" """ normal security checks will be reinstantiated""" """ and the server has to present a valid""" """ certificate.</p>""") .format(itm.text(0))) if res: server = itm.text(1) cert = self.serversCertificatesTree.currentItem().data( 0, self.CertRole) # delete the selected entry and its parent entry, # if it was the only one parent = itm.parent() parent.takeChild(parent.indexOfChild(itm)) if parent.childCount() == 0: self.serversCertificatesTree.takeTopLevelItem( self.serversCertificatesTree.indexOfTopLevelItem(parent)) # delete the certificate from the user certificate store certificateDict = Globals.toDict( Preferences.Prefs.settings.value("Ssl/CaCertificatesDict")) if server in certificateDict: certs = QSslCertificate.fromData(certificateDict[server]) if cert in certs: certs.remove(cert) if certs: pems = QByteArray() for cert in certs: pems.append(cert.toPem() + '\n') certificateDict[server] = pems else: del certificateDict[server] Preferences.Prefs.settings.setValue( "Ssl/CaCertificatesDict", certificateDict) # delete the certificate from the default certificates self.__updateDefaultConfiguration()
def on_serversDeleteButton_clicked(self): """ Private slot to delete the selected server certificate. """ itm = self.serversCertificatesTree.currentItem() res = E5MessageBox.yesNo( self, self.tr("Delete Server Certificate"), self.tr("""<p>Shall the server certificate really be""" """ deleted?</p><p>{0}</p>""" """<p>If the server certificate is deleted, the""" """ normal security checks will be reinstantiated""" """ and the server has to present a valid""" """ certificate.</p>""") .format(itm.text(0))) if res: server = itm.text(1) cert = self.serversCertificatesTree.currentItem().data( 0, self.CertRole) # delete the selected entry and its parent entry, # if it was the only one parent = itm.parent() parent.takeChild(parent.indexOfChild(itm)) if parent.childCount() == 0: self.serversCertificatesTree.takeTopLevelItem( self.serversCertificatesTree.indexOfTopLevelItem(parent)) # delete the certificate from the user certificate store certificateDict = Preferences.toDict( Preferences.Prefs.settings.value("Ssl/CaCertificatesDict")) if server in certificateDict: certs = QSslCertificate.fromData(certificateDict[server]) if cert in certs: certs.remove(cert) if certs: pems = QByteArray() for cert in certs: pems.append(cert.toPem() + '\n') certificateDict[server] = pems else: del certificateDict[server] Preferences.Prefs.settings.setValue( "Ssl/CaCertificatesDict", certificateDict) # delete the certificate from the default certificates self.__updateDefaultConfiguration()
def on_serversImportButton_clicked(self): """ Private slot to import server certificates. """ certs = self.__importCertificate() if certs: server = "*" certificateDict = Globals.toDict( Preferences.Prefs.settings.value("Ssl/CaCertificatesDict")) if server in certificateDict: sCerts = QSslCertificate.fromData(certificateDict[server]) else: sCerts = [] pems = QByteArray() for cert in certs: if cert in sCerts: if qVersion() >= "5.0.0": commonStr = ", ".join( cert.subjectInfo(QSslCertificate.CommonName)) else: commonStr = cert.subjectInfo( QSslCertificate.CommonName) E5MessageBox.warning( self, self.tr("Import Certificate"), self.tr( """<p>The certificate <b>{0}</b> already exists.""" """ Skipping.</p>""") .format(Utilities.decodeString(commonStr))) else: pems.append(cert.toPem() + '\n') if server not in certificateDict: certificateDict[server] = QByteArray() certificateDict[server].append(pems) Preferences.Prefs.settings.setValue( "Ssl/CaCertificatesDict", certificateDict) self.serversCertificatesTree.clear() self.__populateServerCertificatesTree() self.__updateDefaultConfiguration()
def on_serversImportButton_clicked(self): """ Private slot to import server certificates. """ certs = self.__importCertificate() if certs: server = "*" certificateDict = Preferences.toDict( Preferences.Prefs.settings.value("Ssl/CaCertificatesDict")) if server in certificateDict: sCerts = QSslCertificate.fromData(certificateDict[server]) else: sCerts = [] pems = QByteArray() for cert in certs: if cert in sCerts: if qVersion() >= "5.0.0": commonStr = ", ".join( cert.subjectInfo(QSslCertificate.CommonName)) else: commonStr = cert.subjectInfo( QSslCertificate.CommonName) E5MessageBox.warning( self, self.tr("Import Certificate"), self.tr( """<p>The certificate <b>{0}</b> already exists.""" """ Skipping.</p>""") .format(Utilities.decodeString(commonStr))) else: pems.append(cert.toPem() + '\n') if server not in certificateDict: certificateDict[server] = QByteArray() certificateDict[server].append(pems) Preferences.Prefs.settings.setValue( "Ssl/CaCertificatesDict", certificateDict) self.serversCertificatesTree.clear() self.__populateServerCertificatesTree() self.__updateDefaultConfiguration()
def getSelectedCertificate(self): """ Public method to get the selected certificate. @return selected certificate @rtype QSslCertificate """ valid = ( len(self.certificatesTree.selectedItems()) > 0 and self.certificatesTree.selectedItems()[0].parent() is not None ) if valid: certificate = QSslCertificate.fromData( self.certificatesTree.selectedItems()[0].data( 0, self.CertRole)) else: certificate = None return certificate
def __init__(self): super().__init__() self.timerDict = dict() self.lastLogMinute = datetime.now().minute // 10 self.watchDogTimer = self.startTimer(30000) self.restartTimer = None self.testSocket = QSslSocket() self.testSocket.setCaCertificates([QSslCertificate(base64.b64decode(certificate))]) def onTestSuccess(): if self.restartTimer: self.killTimer(self.restartTimer) self.restartTimer = None minute = datetime.now().minute // 10 if minute != self.lastLogMinute: log('server ok, tot: ' + str(Session.IdCounter) + ' open: ' + str(len(openSessions)) + ' active: ' + str(len(activeSessions)) + ' unv: ' + str(len(unvalidatedSockets)) + ' cached: ' + str(len(fileHashDict)) + ' join: ' + str(len(joiningClients)) + ' blockd: ' + str(len(blockedAddresses)) + ' ctrl: ' + str(len(controlHandlers))) self.lastLogMinute = minute self.testSocket.disconnectFromHost() self.testSocket.encrypted.connect(onTestSuccess) self.newConnection.connect(self.handleNewConnection)
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)
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
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
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
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
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