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