QGIS API Documentation 3.41.0-Master (57ec4277f5e)
Loading...
Searching...
No Matches
qgsauthsslimportdialog.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsauthsslimportdialog.cpp
3 ---------------------
4 begin : May 17, 2015
5 copyright : (C) 2015 by Boundless Spatial, Inc. USA
6 author : Larry Shaffer
7 email : lshaffer at boundlessgeo dot com
8 ***************************************************************************
9 * *
10 * This program is free software; you can redistribute it and/or modify *
11 * it under the terms of the GNU General Public License as published by *
12 * the Free Software Foundation; either version 2 of the License, or *
13 * (at your option) any later version. *
14 * *
15 ***************************************************************************/
16
17/****************************************************************************
18**
19** Portions of this code were derived from the following...
20**
21** qt-everywhere-opensource-src-4.8.6/examples/network/
22** securesocketclient/certificateinfo.h (and .cpp)
23**
24** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
25** Contact: http://www.qt-project.org/legal
26**
27** This file is part of the examples of the Qt Toolkit.
28**
29** $QT_BEGIN_LICENSE:BSD$
30** You may use this file under the terms of the BSD license as follows:
31**
32** "Redistribution and use in source and binary forms, with or without
33** modification, are permitted provided that the following conditions are
34** met:
35** * Redistributions of source code must retain the above copyright
36** notice, this list of conditions and the following disclaimer.
37** * Redistributions in binary form must reproduce the above copyright
38** notice, this list of conditions and the following disclaimer in
39** the documentation and/or other materials provided with the
40** distribution.
41** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
42** of its contributors may be used to endorse or promote products derived
43** from this software without specific prior written permission.
44**
45**
46** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
47** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
48** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
49** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
50** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
51** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
52** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
53** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
54** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
55** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
56** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
57**
58** $QT_END_LICENSE$
59**
60****************************************************************************/
61
62
65#include "moc_qgsauthsslimportdialog.cpp"
67#include "ui_qgsauthsslimporterrors.h"
68
69#include <QDir>
70#include <QFileDialog>
71#include <QFileInfo>
72#include <QPushButton>
73#include <QScrollBar>
74#include <QStyle>
75#include <QTimer>
76#include <QToolButton>
77#include <QSslCipher>
78
79#include "qgsauthguiutils.h"
80#include "qgsauthmanager.h"
81#include "qgslogger.h"
82#include "qgsapplication.h"
83
84
86 : QDialog( parent )
87{
88 if ( QgsApplication::authManager()->isDisabled() )
89 {
90 mAuthNotifyLayout = new QVBoxLayout;
91 this->setLayout( mAuthNotifyLayout );
92 mAuthNotify = new QLabel( QgsApplication::authManager()->disabledMessage(), this );
93 mAuthNotifyLayout->addWidget( mAuthNotify );
94 }
95 else
96 {
97 setupUi( this );
98 connect( btnCertPath, &QToolButton::clicked, this, &QgsAuthSslImportDialog::btnCertPath_clicked );
99 QStyle *style = QApplication::style();
100 lblWarningIcon->setPixmap( style->standardIcon( QStyle::SP_MessageBoxWarning ).pixmap( 48, 48 ) );
101 lblWarningIcon->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );
102
103 closeButton()->setDefault( false );
104 saveButton()->setEnabled( false );
105
106 leServer->setSelection( 0, leServer->text().size() );
107 pteSessionStatus->setReadOnly( true );
108 spinbxTimeout->setClearValue( 15 );
109 spinbxTimeout->setValue( 15 );
110 spinbxPort->setClearValue( 443 );
111
112 grpbxServer->setCollapsed( false );
113 radioServerImport->setChecked( true );
114 frameServerImport->setEnabled( true );
115 radioFileImport->setChecked( false );
116 frameFileImport->setEnabled( false );
117
118 connect( radioServerImport, &QAbstractButton::toggled, this, &QgsAuthSslImportDialog::radioServerImportToggled );
119 connect( radioFileImport, &QAbstractButton::toggled, this, &QgsAuthSslImportDialog::radioFileImportToggled );
120
121 connect( leServer, &QLineEdit::textChanged, this, &QgsAuthSslImportDialog::updateEnabledState );
122 connect( btnConnect, &QAbstractButton::clicked, this, &QgsAuthSslImportDialog::secureConnect );
123 connect( leServer, &QLineEdit::returnPressed, btnConnect, &QAbstractButton::click );
124
125 connect( buttonBox, &QDialogButtonBox::accepted, this, &QgsAuthSslImportDialog::accept );
126 connect( buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject );
127
128 connect( wdgtSslConfig, &QgsAuthSslConfigWidget::readyToSaveChanged, this, &QgsAuthSslImportDialog::widgetReadyToSaveChanged );
129 wdgtSslConfig->setEnabled( false );
130
132 }
133}
134
136{
137 wdgtSslConfig->saveSslCertConfig();
138 QDialog::accept();
139}
140
141void QgsAuthSslImportDialog::updateEnabledState()
142{
143 leServer->setStyleSheet( QString() );
144
145 const bool unconnected = !mSocket || mSocket->state() == QAbstractSocket::UnconnectedState;
146
147 leServer->setReadOnly( !unconnected );
148 spinbxPort->setReadOnly( !unconnected );
149 spinbxTimeout->setReadOnly( !unconnected );
150
151 leServer->setFocusPolicy( unconnected ? Qt::StrongFocus : Qt::NoFocus );
152 btnConnect->setEnabled( unconnected && !leServer->text().isEmpty() );
153
154 const bool connected = mSocket && mSocket->state() == QAbstractSocket::ConnectedState;
155 if ( connected && !mSocket->peerName().isEmpty() )
156 {
157 appendString( tr( "Connected to %1: %2" ).arg( mSocket->peerName() ).arg( mSocket->peerPort() ) );
158 }
159}
160
161void QgsAuthSslImportDialog::secureConnect()
162{
163 if ( leServer->text().isEmpty() )
164 {
165 return;
166 }
167
168 leServer->setStyleSheet( QString() );
169 clearStatusCertificateConfig();
170
171 if ( !mSocket )
172 {
173 mSocket = new QSslSocket( this );
174 connect( mSocket, &QAbstractSocket::stateChanged, this, &QgsAuthSslImportDialog::socketStateChanged );
175 connect( mSocket, &QAbstractSocket::connected, this, &QgsAuthSslImportDialog::socketConnected );
176 connect( mSocket, &QAbstractSocket::disconnected, this, &QgsAuthSslImportDialog::socketDisconnected );
177 connect( mSocket, &QSslSocket::encrypted, this, &QgsAuthSslImportDialog::socketEncrypted );
178#if QT_VERSION < QT_VERSION_CHECK( 6, 0, 0 )
179 connect( mSocket, static_cast<void ( QAbstractSocket::* )( QAbstractSocket::SocketError )>( &QAbstractSocket::error ), this, &QgsAuthSslImportDialog::socketError );
180#else
181 connect( mSocket, &QAbstractSocket::errorOccurred, this, &QgsAuthSslImportDialog::socketError );
182#endif
183 connect( mSocket, static_cast<void ( QSslSocket::* )( const QList<QSslError> & )>( &QSslSocket::sslErrors ), this, &QgsAuthSslImportDialog::sslErrors );
184 connect( mSocket, &QIODevice::readyRead, this, &QgsAuthSslImportDialog::socketReadyRead );
185 }
186
187 QSslConfiguration sslConfig = mSocket->sslConfiguration();
188 sslConfig.setCaCertificates( mTrustedCAs );
189 mSocket->setSslConfiguration( sslConfig );
190
191 if ( !mTimer )
192 {
193 mTimer = new QTimer( this );
194 connect( mTimer, &QTimer::timeout, this, &QgsAuthSslImportDialog::destroySocket );
195 }
196 mTimer->start( spinbxTimeout->value() * 1000 );
197
198 mSocket->connectToHost( leServer->text(), spinbxPort->value() );
199 updateEnabledState();
200}
201
202void QgsAuthSslImportDialog::socketStateChanged( QAbstractSocket::SocketState state )
203{
204 if ( mExecErrorsDialog )
205 {
206 return;
207 }
208
209 updateEnabledState();
210 if ( state == QAbstractSocket::UnconnectedState )
211 {
212 leServer->setFocus();
213 destroySocket();
214 }
215}
216
217void QgsAuthSslImportDialog::socketConnected()
218{
219 appendString( tr( "Socket CONNECTED" ) );
220 mSocket->startClientEncryption();
221}
222
223void QgsAuthSslImportDialog::socketDisconnected()
224{
225 appendString( tr( "Socket DISCONNECTED" ) );
226}
227
228void QgsAuthSslImportDialog::socketEncrypted()
229{
230 QgsDebugMsgLevel( QStringLiteral( "socketEncrypted entered" ), 2 );
231 if ( !mSocket )
232 return; // might have disconnected already
233
234 appendString( tr( "Socket ENCRYPTED" ) );
235
236 appendString( QStringLiteral( "%1: %2" ).arg( tr( "Protocol" ), QgsAuthCertUtils::getSslProtocolName( mSocket->protocol() ) ) );
237
238 const QSslCipher ciph = mSocket->sessionCipher();
239 const QString cipher = QStringLiteral( "%1: %2, %3 (%4/%5)" )
240 .arg( tr( "Session cipher" ), ciph.authenticationMethod(), ciph.name() )
241 .arg( ciph.usedBits() )
242 .arg( ciph.supportedBits() );
243 appendString( cipher );
244
245
246 wdgtSslConfig->setEnabled( true );
247 const QString hostport( QStringLiteral( "%1:%2" ).arg( mSocket->peerName() ).arg( mSocket->peerPort() ) );
248 wdgtSslConfig->setSslCertificate( mSocket->peerCertificate(), hostport.trimmed() );
249 if ( !mSslErrors.isEmpty() )
250 {
251 wdgtSslConfig->appendSslIgnoreErrors( mSslErrors );
252 mSslErrors.clear();
253 }
254
255 // checkCanSave();
256
257 // must come after last state change, or gets reverted
258 leServer->setStyleSheet( QgsAuthGuiUtils::greenTextStyleSheet() );
259
260 destroySocket();
261}
262
263void QgsAuthSslImportDialog::socketError( QAbstractSocket::SocketError err )
264{
265 Q_UNUSED( err )
266 if ( mSocket )
267 {
268 appendString( QStringLiteral( "%1: %2" ).arg( tr( "Socket ERROR" ), mSocket->errorString() ) );
269 }
270}
271
272void QgsAuthSslImportDialog::socketReadyRead()
273{
274 appendString( QString::fromUtf8( mSocket->readAll() ) );
275}
276
277void QgsAuthSslImportDialog::destroySocket()
278{
279 if ( !mSocket )
280 {
281 return;
282 }
283 if ( !mSocket->isEncrypted() )
284 {
285 appendString( tr( "Socket unavailable or not encrypted" ) );
286 }
287 mSocket->disconnectFromHost();
288 mSocket->deleteLater();
289 mSocket = nullptr;
290}
291
292void QgsAuthSslImportDialog::sslErrors( const QList<QSslError> &errors )
293{
294 if ( !mTimer->isActive() )
295 {
296 return;
297 }
298 mTimer->stop();
299
300 QDialog errorDialog( this );
301 Ui_SslErrors ui;
302 ui.setupUi( &errorDialog );
303 const auto constErrors = errors;
304 for ( const QSslError &error : constErrors )
305 {
306 ui.sslErrorList->addItem( error.errorString() );
307 }
308
309 mExecErrorsDialog = true;
310 if ( errorDialog.exec() == QDialog::Accepted )
311 {
312 mSocket->ignoreSslErrors();
313 mSslErrors = errors;
314 }
315 mExecErrorsDialog = false;
316
317 mTimer->start();
318
319 // did the socket state change?
320 if ( mSocket->state() != QAbstractSocket::ConnectedState )
321 socketStateChanged( mSocket->state() );
322}
323
324void QgsAuthSslImportDialog::showCertificateInfo()
325{
326 QList<QSslCertificate> peerchain( mSocket->peerCertificateChain() );
327
328 if ( !peerchain.isEmpty() )
329 {
330 const QSslCertificate cert = peerchain.takeFirst();
331 if ( !cert.isNull() )
332 {
333 QgsAuthCertInfoDialog *info = new QgsAuthCertInfoDialog( cert, false, this, peerchain );
334 info->exec();
335 info->deleteLater();
336 }
337 }
338}
339
340void QgsAuthSslImportDialog::widgetReadyToSaveChanged( bool cansave )
341{
342 saveButton()->setEnabled( cansave );
343}
344
345void QgsAuthSslImportDialog::checkCanSave()
346{
347 saveButton()->setEnabled( wdgtSslConfig->readyToSave() );
348 saveButton()->setDefault( false );
349 closeButton()->setDefault( false );
350}
351
352void QgsAuthSslImportDialog::radioServerImportToggled( bool checked )
353{
354 frameServerImport->setEnabled( checked );
355 clearStatusCertificateConfig();
356}
357
358void QgsAuthSslImportDialog::radioFileImportToggled( bool checked )
359{
360 frameFileImport->setEnabled( checked );
361 clearStatusCertificateConfig();
362}
363
364void QgsAuthSslImportDialog::btnCertPath_clicked()
365{
366 const QString &fn = getOpenFileName( tr( "Open Server Certificate File" ), tr( "All files (*.*);;PEM (*.pem);;DER (*.der)" ) );
367 if ( !fn.isEmpty() )
368 {
369 leCertPath->setText( fn );
370 loadCertFromFile();
371 }
372}
373
374void QgsAuthSslImportDialog::clearCertificateConfig()
375{
376 wdgtSslConfig->resetSslCertConfig();
377 wdgtSslConfig->setEnabled( false );
378}
379
380void QgsAuthSslImportDialog::clearStatusCertificateConfig()
381{
382 mSslErrors.clear();
383 pteSessionStatus->clear();
384 saveButton()->setEnabled( false );
385 clearCertificateConfig();
386}
387
388void QgsAuthSslImportDialog::loadCertFromFile()
389{
390 clearStatusCertificateConfig();
391 QList<QSslCertificate> certs( QgsAuthCertUtils::certsFromFile( leCertPath->text() ) );
392
393 if ( certs.isEmpty() )
394 {
395 appendString( tr( "Could not load any certs from file" ) );
396 return;
397 }
398
399 const QSslCertificate cert( certs.first() );
400 if ( cert.isNull() )
401 {
402 appendString( tr( "Could not load server cert from file" ) );
403 return;
404 }
405
407 {
408 appendString( tr( "Certificate does not appear for be for an SSL server. "
409 "You can still add a configuration, if you know it is the correct certificate." ) );
410 }
411
412 wdgtSslConfig->setEnabled( true );
413 wdgtSslConfig->setSslHost( QString() );
414 wdgtSslConfig->setSslCertificate( cert );
415 if ( !mSslErrors.isEmpty() )
416 {
417 wdgtSslConfig->appendSslIgnoreErrors( mSslErrors );
418 mSslErrors.clear();
419 }
420 // checkCanSave();
421}
422
423void QgsAuthSslImportDialog::appendString( const QString &line )
424{
425 QTextCursor cursor( pteSessionStatus->textCursor() );
426 cursor.movePosition( QTextCursor::End );
427 cursor.insertText( line + '\n' );
428 // pteSessionStatus->verticalScrollBar()->setValue( pteSessionStatus->verticalScrollBar()->maximum() );
429}
430
431QPushButton *QgsAuthSslImportDialog::saveButton()
432{
433 return buttonBox->button( QDialogButtonBox::Save );
434}
435
436QPushButton *QgsAuthSslImportDialog::closeButton()
437{
438 return buttonBox->button( QDialogButtonBox::Close );
439}
440
441QString QgsAuthSslImportDialog::getOpenFileName( const QString &title, const QString &extfilter )
442{
443 QgsSettings settings;
444 const QString recentdir = settings.value( QStringLiteral( "UI/lastAuthImportSslOpenFileDir" ), QDir::homePath() ).toString();
445 QString f = QFileDialog::getOpenFileName( this, title, recentdir, extfilter );
446
447 // return dialog focus on Mac
448 this->raise();
449 this->activateWindow();
450
451 if ( !f.isEmpty() )
452 {
453 settings.setValue( QStringLiteral( "UI/lastAuthImportSslOpenFileDir" ), QFileInfo( f ).absoluteDir().path() );
454 }
455 return f;
456}
static QgsAuthManager * authManager()
Returns the application's authentication manager instance.
Dialog wrapper for widget displaying detailed info on a certificate and its hierarchical trust chain.
static QString getSslProtocolName(QSsl::SslProtocol protocol)
SSL Protocol name strings per enum.
static QList< QSslCertificate > certsFromFile(const QString &certspath)
Returns a list of concatenated certs from a PEM or DER formatted file.
static bool certificateIsSslServer(const QSslCertificate &cert)
Gets whether a certificate is probably used for a SSL server.
static QString greenTextStyleSheet(const QString &selector="*")
Green text stylesheet representing valid, trusted, etc. certificate.
const QList< QSslCertificate > trustedCaCertsCache()
trustedCaCertsCache cache of trusted certificate authorities, ready for network connections
void readyToSaveChanged(bool cansave)
Emitted when the configuration can be saved changes.
QgsAuthSslImportDialog(QWidget *parent=nullptr)
Construct dialog for importing certificates.
This class is a composition of two QSettings instances:
Definition qgssettings.h:64
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
void setValue(const QString &key, const QVariant &value, QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:39