QGIS API Documentation 4.1.0-Master (5bf3c20f3c9)
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
63#include "ui_qgsauthsslimporterrors.h"
65
66#include "qgsapplication.h"
68#include "qgsauthguiutils.h"
69#include "qgsauthmanager.h"
71#include "qgslogger.h"
72
73#include <QDir>
74#include <QFileDialog>
75#include <QFileInfo>
76#include <QPushButton>
77#include <QScrollBar>
78#include <QSslCipher>
79#include <QString>
80#include <QStyle>
81#include <QTimer>
82#include <QToolButton>
83
84#include "moc_qgsauthsslimportdialog.cpp"
85
86using namespace Qt::StringLiterals;
87
89 : QDialog( parent )
90{
91 if ( QgsApplication::authManager()->isDisabled() )
92 {
93 mAuthNotifyLayout = new QVBoxLayout;
94 this->setLayout( mAuthNotifyLayout );
95 mAuthNotify = new QLabel( QgsApplication::authManager()->disabledMessage(), this );
96 mAuthNotifyLayout->addWidget( mAuthNotify );
97 }
98 else
99 {
100 setupUi( this );
101 connect( btnCertPath, &QToolButton::clicked, this, &QgsAuthSslImportDialog::btnCertPath_clicked );
102 QStyle *style = QApplication::style();
103 lblWarningIcon->setPixmap( style->standardIcon( QStyle::SP_MessageBoxWarning ).pixmap( 48, 48 ) );
104 lblWarningIcon->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );
105
106 closeButton()->setDefault( false );
107 saveButton()->setEnabled( false );
108
109 leServer->setSelection( 0, leServer->text().size() );
110 pteSessionStatus->setReadOnly( true );
111 spinbxTimeout->setClearValue( 15 );
112 spinbxTimeout->setValue( 15 );
113 spinbxPort->setClearValue( 443 );
114
115 grpbxServer->setCollapsed( false );
116 radioServerImport->setChecked( true );
117 frameServerImport->setEnabled( true );
118 radioFileImport->setChecked( false );
119 frameFileImport->setEnabled( false );
120
121 connect( radioServerImport, &QAbstractButton::toggled, this, &QgsAuthSslImportDialog::radioServerImportToggled );
122 connect( radioFileImport, &QAbstractButton::toggled, this, &QgsAuthSslImportDialog::radioFileImportToggled );
123
124 connect( leServer, &QLineEdit::textChanged, this, &QgsAuthSslImportDialog::updateEnabledState );
125 connect( btnConnect, &QAbstractButton::clicked, this, &QgsAuthSslImportDialog::secureConnect );
126 connect( leServer, &QLineEdit::returnPressed, btnConnect, &QAbstractButton::click );
127
128 connect( buttonBox, &QDialogButtonBox::accepted, this, &QgsAuthSslImportDialog::accept );
129 connect( buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject );
130
131 connect( wdgtSslConfig, &QgsAuthSslConfigWidget::readyToSaveChanged, this, &QgsAuthSslImportDialog::widgetReadyToSaveChanged );
132 wdgtSslConfig->setEnabled( false );
133
135 }
136}
137
139{
140 wdgtSslConfig->saveSslCertConfig();
141 QDialog::accept();
142}
143
144void QgsAuthSslImportDialog::updateEnabledState()
145{
146 leServer->setStyleSheet( QString() );
147
148 const bool unconnected = !mSocket || mSocket->state() == QAbstractSocket::UnconnectedState;
149
150 leServer->setReadOnly( !unconnected );
151 spinbxPort->setReadOnly( !unconnected );
152 spinbxTimeout->setReadOnly( !unconnected );
153
154 leServer->setFocusPolicy( unconnected ? Qt::StrongFocus : Qt::NoFocus );
155 btnConnect->setEnabled( unconnected && !leServer->text().isEmpty() );
156
157 const bool connected = mSocket && mSocket->state() == QAbstractSocket::ConnectedState;
158 if ( connected && !mSocket->peerName().isEmpty() )
159 {
160 appendString( tr( "Connected to %1: %2" ).arg( mSocket->peerName() ).arg( mSocket->peerPort() ) );
161 }
162}
163
164void QgsAuthSslImportDialog::secureConnect()
165{
166 if ( leServer->text().isEmpty() )
167 {
168 return;
169 }
170
171 leServer->setStyleSheet( QString() );
172 clearStatusCertificateConfig();
173
174 if ( !mSocket )
175 {
176 mSocket = new QSslSocket( this );
177 connect( mSocket, &QAbstractSocket::stateChanged, this, &QgsAuthSslImportDialog::socketStateChanged );
178 connect( mSocket, &QAbstractSocket::connected, this, &QgsAuthSslImportDialog::socketConnected );
179 connect( mSocket, &QAbstractSocket::disconnected, this, &QgsAuthSslImportDialog::socketDisconnected );
180 connect( mSocket, &QSslSocket::encrypted, this, &QgsAuthSslImportDialog::socketEncrypted );
181 connect( mSocket, &QAbstractSocket::errorOccurred, this, &QgsAuthSslImportDialog::socketError );
182 connect( mSocket, static_cast<void ( QSslSocket::* )( const QList<QSslError> & )>( &QSslSocket::sslErrors ), this, &QgsAuthSslImportDialog::sslErrors );
183 connect( mSocket, &QIODevice::readyRead, this, &QgsAuthSslImportDialog::socketReadyRead );
184 }
185
186 QSslConfiguration sslConfig = mSocket->sslConfiguration();
187 sslConfig.setCaCertificates( mTrustedCAs );
188 mSocket->setSslConfiguration( sslConfig );
189
190 if ( !mTimer )
191 {
192 mTimer = new QTimer( this );
193 connect( mTimer, &QTimer::timeout, this, &QgsAuthSslImportDialog::destroySocket );
194 }
195 mTimer->start( spinbxTimeout->value() * 1000 );
196
197 mSocket->connectToHost( leServer->text(), spinbxPort->value() );
198 updateEnabledState();
199}
200
201void QgsAuthSslImportDialog::socketStateChanged( QAbstractSocket::SocketState state )
202{
203 if ( mExecErrorsDialog )
204 {
205 return;
206 }
207
208 updateEnabledState();
209 if ( state == QAbstractSocket::UnconnectedState )
210 {
211 leServer->setFocus();
212 destroySocket();
213 }
214}
215
216void QgsAuthSslImportDialog::socketConnected()
217{
218 appendString( tr( "Socket CONNECTED" ) );
219 mSocket->startClientEncryption();
220}
221
222void QgsAuthSslImportDialog::socketDisconnected()
223{
224 appendString( tr( "Socket DISCONNECTED" ) );
225}
226
227void QgsAuthSslImportDialog::socketEncrypted()
228{
229 QgsDebugMsgLevel( u"socketEncrypted entered"_s, 2 );
230 if ( !mSocket )
231 return; // might have disconnected already
232
233 appendString( tr( "Socket ENCRYPTED" ) );
234
235 appendString( u"%1: %2"_s.arg( tr( "Protocol" ), QgsAuthCertUtils::getSslProtocolName( mSocket->protocol() ) ) );
236
237 const QSslCipher ciph = mSocket->sessionCipher();
238 const QString cipher = u"%1: %2, %3 (%4/%5)"_s.arg( tr( "Session cipher" ), ciph.authenticationMethod(), ciph.name() ).arg( ciph.usedBits() ).arg( ciph.supportedBits() );
239 appendString( cipher );
240
241
242 wdgtSslConfig->setEnabled( true );
243 const QString hostport( u"%1:%2"_s.arg( mSocket->peerName() ).arg( mSocket->peerPort() ) );
244 wdgtSslConfig->setSslCertificate( mSocket->peerCertificate(), hostport.trimmed() );
245 if ( !mSslErrors.isEmpty() )
246 {
247 wdgtSslConfig->appendSslIgnoreErrors( mSslErrors );
248 mSslErrors.clear();
249 }
250
251 // checkCanSave();
252
253 // must come after last state change, or gets reverted
254 leServer->setStyleSheet( QgsAuthGuiUtils::greenTextStyleSheet() );
255
256 destroySocket();
257}
258
259void QgsAuthSslImportDialog::socketError( QAbstractSocket::SocketError err )
260{
261 Q_UNUSED( err )
262 if ( mSocket )
263 {
264 appendString( u"%1: %2"_s.arg( tr( "Socket ERROR" ), mSocket->errorString() ) );
265 }
266}
267
268void QgsAuthSslImportDialog::socketReadyRead()
269{
270 appendString( QString::fromUtf8( mSocket->readAll() ) );
271}
272
273void QgsAuthSslImportDialog::destroySocket()
274{
275 if ( !mSocket )
276 {
277 return;
278 }
279 if ( !mSocket->isEncrypted() )
280 {
281 appendString( tr( "Socket unavailable or not encrypted" ) );
282 }
283 mSocket->disconnectFromHost();
284 mSocket->deleteLater();
285 mSocket = nullptr;
286}
287
288void QgsAuthSslImportDialog::sslErrors( const QList<QSslError> &errors )
289{
290 if ( !mTimer->isActive() )
291 {
292 return;
293 }
294 mTimer->stop();
295
296 QDialog errorDialog( this );
297 Ui_SslErrors ui;
298 ui.setupUi( &errorDialog );
299 const auto constErrors = errors;
300 for ( const QSslError &error : constErrors )
301 {
302 ui.sslErrorList->addItem( error.errorString() );
303 }
304
305 mExecErrorsDialog = true;
306 if ( errorDialog.exec() == QDialog::Accepted )
307 {
308 mSocket->ignoreSslErrors();
309 mSslErrors = errors;
310 }
311 mExecErrorsDialog = false;
312
313 mTimer->start();
314
315 // did the socket state change?
316 if ( mSocket->state() != QAbstractSocket::ConnectedState )
317 socketStateChanged( mSocket->state() );
318}
319
320void QgsAuthSslImportDialog::showCertificateInfo()
321{
322 QList<QSslCertificate> peerchain( mSocket->peerCertificateChain() );
323
324 if ( !peerchain.isEmpty() )
325 {
326 const QSslCertificate cert = peerchain.takeFirst();
327 if ( !cert.isNull() )
328 {
329 QgsAuthCertInfoDialog *info = new QgsAuthCertInfoDialog( cert, false, this, peerchain );
330 info->exec();
331 info->deleteLater();
332 }
333 }
334}
335
336void QgsAuthSslImportDialog::widgetReadyToSaveChanged( bool cansave )
337{
338 saveButton()->setEnabled( cansave );
339}
340
341void QgsAuthSslImportDialog::checkCanSave()
342{
343 saveButton()->setEnabled( wdgtSslConfig->readyToSave() );
344 saveButton()->setDefault( false );
345 closeButton()->setDefault( false );
346}
347
348void QgsAuthSslImportDialog::radioServerImportToggled( bool checked )
349{
350 frameServerImport->setEnabled( checked );
351 clearStatusCertificateConfig();
352}
353
354void QgsAuthSslImportDialog::radioFileImportToggled( bool checked )
355{
356 frameFileImport->setEnabled( checked );
357 clearStatusCertificateConfig();
358}
359
360void QgsAuthSslImportDialog::btnCertPath_clicked()
361{
362 const QString &fn = getOpenFileName( tr( "Open Server Certificate File" ), tr( "All files (*.*);;PEM (*.pem);;DER (*.der)" ) );
363 if ( !fn.isEmpty() )
364 {
365 leCertPath->setText( fn );
366 loadCertFromFile();
367 }
368}
369
370void QgsAuthSslImportDialog::clearCertificateConfig()
371{
372 wdgtSslConfig->resetSslCertConfig();
373 wdgtSslConfig->setEnabled( false );
374}
375
376void QgsAuthSslImportDialog::clearStatusCertificateConfig()
377{
378 mSslErrors.clear();
379 pteSessionStatus->clear();
380 saveButton()->setEnabled( false );
381 clearCertificateConfig();
382}
383
384void QgsAuthSslImportDialog::loadCertFromFile()
385{
386 clearStatusCertificateConfig();
387 QList<QSslCertificate> certs( QgsAuthCertUtils::certsFromFile( leCertPath->text() ) );
388
389 if ( certs.isEmpty() )
390 {
391 appendString( tr( "Could not load any certs from file" ) );
392 return;
393 }
394
395 const QSslCertificate cert( certs.first() );
396 if ( cert.isNull() )
397 {
398 appendString( tr( "Could not load server cert from file" ) );
399 return;
400 }
401
402 if ( !QgsAuthCertUtils::certificateIsSslServer( cert ) )
403 {
404 appendString( tr(
405 "Certificate does not appear for be for an SSL server. "
406 "You can still add a configuration, if you know it is the correct certificate."
407 ) );
408 }
409
410 wdgtSslConfig->setEnabled( true );
411 wdgtSslConfig->setSslHost( QString() );
412 wdgtSslConfig->setSslCertificate( cert );
413 if ( !mSslErrors.isEmpty() )
414 {
415 wdgtSslConfig->appendSslIgnoreErrors( mSslErrors );
416 mSslErrors.clear();
417 }
418 // checkCanSave();
419}
420
421void QgsAuthSslImportDialog::appendString( const QString &line )
422{
423 QTextCursor cursor( pteSessionStatus->textCursor() );
424 cursor.movePosition( QTextCursor::End );
425 cursor.insertText( line + '\n' );
426 // pteSessionStatus->verticalScrollBar()->setValue( pteSessionStatus->verticalScrollBar()->maximum() );
427}
428
429QPushButton *QgsAuthSslImportDialog::saveButton()
430{
431 return buttonBox->button( QDialogButtonBox::Save );
432}
433
434QPushButton *QgsAuthSslImportDialog::closeButton()
435{
436 return buttonBox->button( QDialogButtonBox::Close );
437}
438
439QString QgsAuthSslImportDialog::getOpenFileName( const QString &title, const QString &extfilter )
440{
441 QgsSettings settings;
442 const QString recentdir = settings.value( u"UI/lastAuthImportSslOpenFileDir"_s, QDir::homePath() ).toString();
443 QString f = QFileDialog::getOpenFileName( this, title, recentdir, extfilter );
444
445 // return dialog focus on Mac
446 this->raise();
447 this->activateWindow();
448
449 if ( !f.isEmpty() )
450 {
451 settings.setValue( u"UI/lastAuthImportSslOpenFileDir"_s, QFileInfo( f ).absoluteDir().path() );
452 }
453 return f;
454}
static QgsAuthManager * authManager()
Returns the application's authentication manager instance.
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.
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:63