Add a secure UDP server example

It's a simple DTLS server, implemented with QUdpSocket,
QDtlsClientVerifier and QDtls. The server is configured
to use PSK only (it has no certificate/key).

The server uses a single QUdpSocket socket and
de-multiplexes UDP datagrams internally (thus
it can work with several clients simultaneously).

Future update will probably add more options (like
configuring with certificate/key, etc). For now -
it's as minimalistic and simple as possible.

Task-number: QTBUG-67596
Change-Id: Ic7d18dbab6dbcc9ed44c82e69a2b364df24aa256
Reviewed-by: Timur Pocheptsov <timur.pocheptsov@qt.io>
This commit is contained in:
Timur Pocheptsov 2018-03-15 14:26:26 +01:00
parent d502d883fd
commit ed775e794c
11 changed files with 1212 additions and 1 deletions

View File

@ -29,7 +29,11 @@ qtHaveModule(widgets) {
}
qtConfig(openssl): SUBDIRS += securesocketclient
qtConfig(openssl) {
SUBDIRS += \
securesocketclient \
secureudpserver
}
qtConfig(sctp): SUBDIRS += multistreamserver multistreamclient
}

View File

@ -0,0 +1,64 @@
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QT_USE_NAMESPACE
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}

View File

@ -0,0 +1,136 @@
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "mainwindow.h"
#include "nicselector.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow()
: ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(&server, &DtlsServer::errorMessage, this, &MainWindow::addErrorMessage);
connect(&server, &DtlsServer::warningMessage, this, &MainWindow::addWarningMessage);
connect(&server, &DtlsServer::infoMessage, this, &MainWindow::addInfoMessage);
connect(&server, &DtlsServer::datagramReceived, this, &MainWindow::addClientMessage);
updateUi();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_startButton_clicked()
{
if (!server.isListening()) {
NicSelector ipDialog;
if (ipDialog.exec() == QDialog::Accepted) {
const QHostAddress address = ipDialog.selectedIp();
const quint16 port = ipDialog.selectedPort();
if (address.isNull()) {
addErrorMessage(tr("Failed to start listening, no valid address/port"));
} else if (server.listen(address, port)) {
addInfoMessage(tr("Server is listening on address %1 and port %2")
.arg(address.toString())
.arg(port));
}
}
} else {
server.close();
addInfoMessage(tr("Server is not accepting new connections"));
}
updateUi();
}
void MainWindow::on_quitButton_clicked()
{
QCoreApplication::exit(0);
}
void MainWindow::updateUi()
{
server.isListening() ? ui->startButton->setText(tr("Stop listening"))
: ui->startButton->setText(tr("Start listening"));
}
const QString colorizer(QStringLiteral("<font color=\"%1\">%2</font><br>"));
void MainWindow::addErrorMessage(const QString &message)
{
ui->serverInfo->insertHtml(colorizer.arg(QStringLiteral("Crimson"), message));
}
void MainWindow::addWarningMessage(const QString &message)
{
ui->serverInfo->insertHtml(colorizer.arg(QStringLiteral("DarkOrange"), message));
}
void MainWindow::addInfoMessage(const QString &message)
{
ui->serverInfo->insertHtml(colorizer.arg(QStringLiteral("DarkBlue"), message));
}
void MainWindow::addClientMessage(const QString &peerInfo, const QByteArray &datagram,
const QByteArray &plainText)
{
static const QString messageColor = QStringLiteral("DarkMagenta");
static const QString formatter = QStringLiteral("<br>---------------"
"<br>A message from %1"
"<br>DTLS datagram:<br> %2"
"<br>As plain text:<br> %3");
const QString html = formatter.arg(peerInfo, QString::fromUtf8(datagram.toHex(' ')),
QString::fromUtf8(plainText));
ui->messages->insertHtml(colorizer.arg(messageColor, html));
}

View File

@ -0,0 +1,95 @@
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "server.h"
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE
QT_USE_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow();
~MainWindow();
private slots:
void addErrorMessage(const QString &message);
void addWarningMessage(const QString &message);
void addInfoMessage(const QString &message);
void addClientMessage(const QString &peerInfo, const QByteArray &datagram,
const QByteArray &plainText);
void on_startButton_clicked();
void on_quitButton_clicked();
private:
void updateUi();
Ui::MainWindow *ui = nullptr;
DtlsServer server;
};
#endif // MAINWINDOW_H

View File

@ -0,0 +1,207 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1090</width>
<height>670</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>1090</width>
<height>670</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>1090</width>
<height>670</height>
</size>
</property>
<property name="windowTitle">
<string>DTLS server</string>
</property>
<widget class="QWidget" name="centralWidget">
<widget class="QWidget" name="layoutWidget">
<property name="geometry">
<rect>
<x>20</x>
<y>20</y>
<width>1050</width>
<height>576</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QGroupBox" name="infoBox">
<property name="minimumSize">
<size>
<width>520</width>
<height>540</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>520</width>
<height>540</height>
</size>
</property>
<property name="title">
<string>Dtls server info:</string>
</property>
<property name="flat">
<bool>true</bool>
</property>
<widget class="QTextEdit" name="serverInfo">
<property name="geometry">
<rect>
<x>10</x>
<y>30</y>
<width>500</width>
<height>500</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>500</width>
<height>500</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>500</width>
<height>500</height>
</size>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBox">
<property name="minimumSize">
<size>
<width>520</width>
<height>540</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>520</width>
<height>540</height>
</size>
</property>
<property name="title">
<string>Received messages:</string>
</property>
<property name="flat">
<bool>true</bool>
</property>
<widget class="QTextEdit" name="messages">
<property name="geometry">
<rect>
<x>10</x>
<y>30</y>
<width>500</width>
<height>500</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>500</width>
<height>500</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>500</width>
<height>500</height>
</size>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="startButton">
<property name="text">
<string>Start listening</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="quitButton">
<property name="text">
<string>Quit</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
</layout>
</widget>
</widget>
<widget class="QMenuBar" name="menuBar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1090</width>
<height>22</height>
</rect>
</property>
</widget>
<widget class="QToolBar" name="mainToolBar">
<attribute name="toolBarArea">
<enum>TopToolBarArea</enum>
</attribute>
<attribute name="toolBarBreak">
<bool>false</bool>
</attribute>
</widget>
<widget class="QStatusBar" name="statusBar"/>
</widget>
<layoutdefault spacing="6" margin="11"/>
<resources/>
<connections/>
</ui>

View File

@ -0,0 +1,95 @@
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <limits>
#include <QtCore>
#include <QtNetwork>
#include "nicselector.h"
#include "ui_nicselector.h"
NicSelector::NicSelector(QWidget *parent) :
QDialog(parent),
ui(new Ui::NicSelector)
{
ui->setupUi(this);
auto portValidator = new QIntValidator(0, int(std::numeric_limits<quint16>::max()),
ui->portSelector);
ui->portSelector->setValidator(portValidator);
ui->portSelector->setText(QStringLiteral("22334"));
const QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
availableAddresses.reserve(ipAddressesList.size());
for (const QHostAddress &ip : ipAddressesList) {
if (ip != QHostAddress::LocalHost && ip.toIPv4Address()) {
availableAddresses.push_back(ip);
ui->ipSelector->addItem(ip.toString());
}
}
}
NicSelector::~NicSelector()
{
delete ui;
}
QHostAddress NicSelector::selectedIp() const
{
if (!availableAddresses.size())
return {};
return availableAddresses[ui->ipSelector->currentIndex()];
}
quint16 NicSelector::selectedPort() const
{
return quint16(ui->portSelector->text().toUInt());
}

View File

@ -0,0 +1,84 @@
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef NICSELECTOR_H
#define NICSELECTOR_H
#include <QDialog>
#include <QHostAddress>
#include <QVector>
QT_BEGIN_NAMESPACE
namespace Ui {
class NicSelector;
}
QT_END_NAMESPACE
QT_USE_NAMESPACE
class NicSelector : public QDialog
{
Q_OBJECT
public:
explicit NicSelector(QWidget *parent = nullptr);
~NicSelector();
QHostAddress selectedIp() const;
quint16 selectedPort() const;
private:
Ui::NicSelector *ui = nullptr;
QVector<QHostAddress> availableAddresses;
};
#endif // NICSELECTOR_H

View File

@ -0,0 +1,144 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>NicSelector</class>
<widget class="QDialog" name="NicSelector">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>373</width>
<height>213</height>
</rect>
</property>
<property name="windowTitle">
<string>IP and port</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="sizeConstraint">
<enum>QLayout::SetFixedSize</enum>
</property>
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Listen on address:</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="ipSelector">
<property name="minimumSize">
<size>
<width>250</width>
<height>0</height>
</size>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeType">
<enum>QSizePolicy::Fixed</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout_2">
<property name="sizeConstraint">
<enum>QLayout::SetFixedSize</enum>
</property>
<item>
<widget class="QLabel" name="label_2">
<property name="text">
<string>Port:</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="portSelector">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer_2">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeType">
<enum>QSizePolicy::Fixed</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>NicSelector</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>NicSelector</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>

View File

@ -0,0 +1,21 @@
QT += widgets network
TARGET = secureudpserver
TEMPLATE = app
SOURCES += \
main.cpp \
mainwindow.cpp \
server.cpp \
nicselector.cpp
HEADERS += \
mainwindow.h \
server.h \
nicselector.h
FORMS = mainwindow.ui \
nicselector.ui
target.path = $$[QT_INSTALL_EXAMPLES]/network/secureudpserver
INSTALLS += target

View File

@ -0,0 +1,252 @@
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "server.h"
#include <algorithm>
QT_BEGIN_NAMESPACE
namespace {
QString peer_info(const QHostAddress &address, quint16 port)
{
const static QString info = QStringLiteral("(%1:%2)");
return info.arg(address.toString()).arg(port);
}
QString connection_info(QSharedPointer<QDtls> connection)
{
QString info(DtlsServer::tr("Session cipher: "));
info += connection->sessionCipher().name();
info += DtlsServer::tr("; session protocol: ");
switch (connection->sessionProtocol()) {
case QSsl::DtlsV1_0:
info += DtlsServer::tr("DTLS 1.0.");
break;
case QSsl::DtlsV1_2:
info += DtlsServer::tr("DTLS 1.2.");
break;
case QSsl::DtlsV1_2OrLater:
info += DtlsServer::tr("DTLS 1.2 or later.");
break;
default:
info += DtlsServer::tr("Unknown protocol.");
}
return info;
}
} // unnamed namespace
DtlsServer::DtlsServer()
{
connect(&serverSocket, &QAbstractSocket::readyRead, this, &DtlsServer::readyRead);
serverConfiguration.setPreSharedKeyIdentityHint("Qt DTLS example server");
serverConfiguration.setPeerVerifyMode(QSslSocket::VerifyNone);
}
DtlsServer::~DtlsServer()
{
shutdown();
}
bool DtlsServer::listen(const QHostAddress &address, quint16 port)
{
if (address != serverSocket.localAddress() || port != serverSocket.localPort()) {
shutdown();
listening = serverSocket.bind(address, port);
if (!listening)
emit errorMessage(serverSocket.errorString());
} else {
listening = true;
}
return listening;
}
bool DtlsServer::isListening() const
{
return listening;
}
void DtlsServer::close()
{
listening = false;
}
void DtlsServer::readyRead()
{
const qint64 bytesToRead = serverSocket.pendingDatagramSize();
if (bytesToRead <= 0) {
emit warningMessage(tr("A spurious read notification"));
return;
}
QByteArray dgram(bytesToRead, Qt::Uninitialized);
QHostAddress peerAddress;
quint16 peerPort = 0;
const qint64 bytesRead = serverSocket.readDatagram(dgram.data(), dgram.size(),
&peerAddress, &peerPort);
if (bytesRead <= 0) {
emit warningMessage(tr("Failed to read a datagram: ") + serverSocket.errorString());
return;
}
dgram.resize(bytesRead);
if (peerAddress.isNull() || !peerPort) {
emit warningMessage(tr("Failed to extract peer info (address, port)"));
return;
}
const auto client = std::find_if(knownClients.begin(), knownClients.end(),
[&](const DtlsConnection &connection){
return connection->remoteAddress() == peerAddress
&& connection->remotePort() == peerPort;
});
if (client == knownClients.end())
return handleNewConnection(peerAddress, peerPort, dgram);
if ((*client)->connectionEncrypted()) {
decryptDatagram(*client, dgram);
if ((*client)->dtlsError() == QDtlsError::RemoteClosedConnectionError)
knownClients.erase(client);
return;
}
doHandshake(*client, dgram);
}
void DtlsServer::pskRequired(QSslPreSharedKeyAuthenticator *auth)
{
Q_ASSERT(auth);
emit infoMessage(tr("PSK callback, received a client's identity: '%1'")
.arg(QString::fromLatin1(auth->identity())));
auth->setPreSharedKey(QByteArrayLiteral("\x1a\x2b\x3c\x4d\x5e\x6f"));
}
void DtlsServer::handleNewConnection(const QHostAddress &peerAddress,
quint16 peerPort, const QByteArray &clientHello)
{
if (!listening)
return;
const QString peerInfo = peer_info(peerAddress, peerPort);
if (cookieSender.verifyClient(&serverSocket, clientHello, peerAddress, peerPort)) {
emit infoMessage(peerInfo + tr(": verified, starting a handshake"));
DtlsConnection newConnection(new QDtls(QSslSocket::SslServerMode));
newConnection->setDtlsConfiguration(serverConfiguration);
newConnection->setRemote(peerAddress, peerPort);
newConnection->connect(newConnection.data(), &QDtls::pskRequired,
this, &DtlsServer::pskRequired);
knownClients.push_back(newConnection);
doHandshake(newConnection, clientHello);
} else if (cookieSender.dtlsError() != QDtlsError::NoError) {
emit errorMessage(tr("DTLS error: ") + cookieSender.dtlsErrorString());
} else {
emit infoMessage(peerInfo + tr(": not verified yet"));
}
}
void DtlsServer::doHandshake(DtlsConnection newConnection, const QByteArray &clientHello)
{
const bool result = newConnection->doHandshake(&serverSocket, clientHello);
if (!result) {
emit errorMessage(newConnection->dtlsErrorString());
return;
}
const QString peerInfo = peer_info(newConnection->remoteAddress(),
newConnection->remotePort());
switch (newConnection->handshakeState()) {
case QDtls::HandshakeInProgress:
emit infoMessage(peerInfo + tr(": handshake is in progress ..."));
break;
case QDtls::HandshakeComplete:
emit infoMessage(tr("Connection with %1 encrypted. %2")
.arg(peerInfo, connection_info(newConnection)));
break;
default:
Q_UNREACHABLE();
}
}
void DtlsServer::decryptDatagram(DtlsConnection connection, const QByteArray &clientMessage)
{
Q_ASSERT(connection->connectionEncrypted());
const QString peerInfo = peer_info(connection->remoteAddress(), connection->remotePort());
const QByteArray dgram = connection->decryptDatagram(&serverSocket, clientMessage);
if (dgram.size()) {
emit datagramReceived(peerInfo, clientMessage, dgram);
connection->writeDatagramEncrypted(&serverSocket, tr("to %1: ACK").arg(peerInfo).toLatin1());
} else if (connection->dtlsError() == QDtlsError::NoError) {
emit warningMessage(peerInfo + ": " + tr("0 byte dgram, could be a re-connect attempt?"));
} else {
emit errorMessage(peerInfo + ": " + connection->dtlsErrorString());
}
}
void DtlsServer::shutdown()
{
for (DtlsConnection &connection : knownClients)
connection->sendShutdownAlert(&serverSocket);
knownClients.clear();
serverSocket.close();
}
QT_END_NAMESPACE

View File

@ -0,0 +1,109 @@
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef SERVER_H
#define SERVER_H
#include <QtCore>
#include <QtNetwork>
#include <vector>
QT_BEGIN_NAMESPACE
class DtlsServer : public QObject
{
Q_OBJECT
public:
DtlsServer();
~DtlsServer();
bool listen(const QHostAddress &address, quint16 port);
bool isListening() const;
void close();
signals:
void errorMessage(const QString &message);
void warningMessage(const QString &message);
void infoMessage(const QString &message);
void datagramReceived(const QString &peerInfo, const QByteArray &cipherText,
const QByteArray &plainText);
private slots:
void readyRead();
void pskRequired(QSslPreSharedKeyAuthenticator *auth);
private:
void handleNewConnection(const QHostAddress &peerAddress, quint16 peerPort,
const QByteArray &clientHello);
using DtlsConnection = QSharedPointer<QDtls>;
void doHandshake(DtlsConnection newConnection, const QByteArray &clientHello);
void decryptDatagram(DtlsConnection connection, const QByteArray &clientMessage);
void shutdown();
bool listening = false;
QUdpSocket serverSocket;
QSslConfiguration serverConfiguration;
QDtlsClientVerifier cookieSender;
QVector<DtlsConnection> knownClients;
Q_DISABLE_COPY(DtlsServer)
};
QT_END_NAMESPACE
#endif // SERVER_H