QGIS API Documentation  3.6.0-Noosa (5873452)
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  Q_FOREACH ( const QSslError &error, errors )
311  {
312  ui.sslErrorList->addItem( error.errorString() );
313  }
314 
315  mExecErrorsDialog = true;
316  if ( errorDialog.exec() == QDialog::Accepted )
317  {
318  mSocket->ignoreSslErrors();
319  mSslErrors = errors;
320  }
321  mExecErrorsDialog = false;
322 
323  mTimer->start();
324 
325  // did the socket state change?
326  if ( mSocket->state() != QAbstractSocket::ConnectedState )
327  socketStateChanged( mSocket->state() );
328 }
329 
330 void QgsAuthSslImportDialog::showCertificateInfo()
331 {
332  QList<QSslCertificate> peerchain( mSocket->peerCertificateChain() );
333 
334  if ( !peerchain.isEmpty() )
335  {
336  QSslCertificate cert = peerchain.takeFirst();
337  if ( !cert.isNull() )
338  {
339  QgsAuthCertInfoDialog *info = new QgsAuthCertInfoDialog( cert, false, this, peerchain );
340  info->exec();
341  info->deleteLater();
342  }
343  }
344 }
345 
346 void QgsAuthSslImportDialog::widgetReadyToSaveChanged( bool cansave )
347 {
348  saveButton()->setEnabled( cansave );
349 }
350 
351 void QgsAuthSslImportDialog::checkCanSave()
352 {
353  saveButton()->setEnabled( wdgtSslConfig->readyToSave() );
354  saveButton()->setDefault( false );
355  closeButton()->setDefault( false );
356 }
357 
358 void QgsAuthSslImportDialog::radioServerImportToggled( bool checked )
359 {
360  frameServerImport->setEnabled( checked );
361  clearStatusCertificateConfig();
362 }
363 
364 void QgsAuthSslImportDialog::radioFileImportToggled( bool checked )
365 {
366  frameFileImport->setEnabled( checked );
367  clearStatusCertificateConfig();
368 }
369 
370 void QgsAuthSslImportDialog::btnCertPath_clicked()
371 {
372  const QString &fn = getOpenFileName( tr( "Open Server Certificate File" ), tr( "All files (*.*);;PEM (*.pem);;DER (*.der)" ) );
373  if ( !fn.isEmpty() )
374  {
375  leCertPath->setText( fn );
376  loadCertFromFile();
377  }
378 }
379 
380 void QgsAuthSslImportDialog::clearCertificateConfig()
381 {
382  wdgtSslConfig->resetSslCertConfig();
383  wdgtSslConfig->setEnabled( false );
384 }
385 
386 void QgsAuthSslImportDialog::clearStatusCertificateConfig()
387 {
388  mSslErrors.clear();
389  pteSessionStatus->clear();
390  saveButton()->setEnabled( false );
391  clearCertificateConfig();
392 }
393 
394 void QgsAuthSslImportDialog::loadCertFromFile()
395 {
396  clearStatusCertificateConfig();
397  QList<QSslCertificate> certs( QgsAuthCertUtils::certsFromFile( leCertPath->text() ) );
398 
399  if ( certs.isEmpty() )
400  {
401  appendString( tr( "Could not load any certs from file" ) );
402  return;
403  }
404 
405  QSslCertificate cert( certs.first() );
406  if ( cert.isNull() )
407  {
408  appendString( tr( "Could not load server cert from file" ) );
409  return;
410  }
411 
413  {
414  appendString( tr( "Certificate does not appear for be for an SSL server. "
415  "You can still add a configuration, if you know it is the correct certificate." ) );
416  }
417 
418  wdgtSslConfig->setEnabled( true );
419  wdgtSslConfig->setSslHost( QString() );
420  wdgtSslConfig->setSslCertificate( cert );
421  if ( !mSslErrors.isEmpty() )
422  {
423  wdgtSslConfig->appendSslIgnoreErrors( mSslErrors );
424  mSslErrors.clear();
425  }
426 // checkCanSave();
427 }
428 
429 void QgsAuthSslImportDialog::appendString( const QString &line )
430 {
431  QTextCursor cursor( pteSessionStatus->textCursor() );
432  cursor.movePosition( QTextCursor::End );
433  cursor.insertText( line + '\n' );
434 // pteSessionStatus->verticalScrollBar()->setValue( pteSessionStatus->verticalScrollBar()->maximum() );
435 }
436 
437 QPushButton *QgsAuthSslImportDialog::saveButton()
438 {
439  return buttonBox->button( QDialogButtonBox::Save );
440 }
441 
442 QPushButton *QgsAuthSslImportDialog::closeButton()
443 {
444  return buttonBox->button( QDialogButtonBox::Close );
445 }
446 
447 QString QgsAuthSslImportDialog::getOpenFileName( const QString &title, const QString &extfilter )
448 {
449  QgsSettings settings;
450  QString recentdir = settings.value( QStringLiteral( "UI/lastAuthImportSslOpenFileDir" ), QDir::homePath() ).toString();
451  QString f = QFileDialog::getOpenFileName( this, title, recentdir, extfilter );
452 
453  // return dialog focus on Mac
454  this->raise();
455  this->activateWindow();
456 
457  if ( !f.isEmpty() )
458  {
459  settings.setValue( QStringLiteral( "UI/lastAuthImportSslOpenFileDir" ), QFileInfo( f ).absoluteDir().path() );
460  }
461  return f;
462 }
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.