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