Qt文档阅读笔记-DTLS server解析
Posted IT1995
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Qt文档阅读笔记-DTLS server解析相关的知识,希望对你有一定的参考价值。
此篇博文展示了如何创建一个简单的DTLS服务端:
注意:这个DTLS服务端需要和DTLS客户端一起跑,才能看出效果。
服务端实现了DtlsServer类,这个类使用了QUdpSocket,QDtlsClientVerifier,QDtls使用这些类用于和客户端的连接,完成握手及数据加密传输与读取。
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);
void doHandshake(QDtls *newConnection, const QByteArray &clientHello);
void decryptDatagram(QDtls *connection, const QByteArray &clientMessage);
void shutdown();
bool listening = false;
QUdpSocket serverSocket;
QSslConfiguration serverConfiguration;
QDtlsClientVerifier cookieSender;
std::vector<std::unique_ptr<QDtls>> knownClients;
Q_DISABLE_COPY(DtlsServer)
};
构造函数中QUdpSocket::readyRead()信号连接了readyRead()槽,用于获取客户端的数据报,最简单的设置了DTLS的配置:
DtlsServer::DtlsServer()
{
connect(&serverSocket, &QAbstractSocket::readyRead, this, &DtlsServer::readyRead);
serverConfiguration = QSslConfiguration::defaultDtlsConfiguration();
serverConfiguration.setPreSharedKeyIdentityHint("Qt DTLS example server");
serverConfiguration.setPeerVerifyMode(QSslSocket::VerifyNone);
}
注意:服务端未使用证书,仅仅是依赖共享密钥(PSK)握手。
listen()与QUdpSocket进行了捆绑:
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;
}
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);
...
随后获取客户端的IP和端口,服务端发送数据报给客户端:
...
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 std::unique_ptr<QDtls> &connection){
return connection->peerAddress() == peerAddress
&& connection->peerPort() == peerPort;
});
...
如果是新的客户端,未知地址和端口,客户端会发送ClientHello消息,随后服务端回HelloVerifyRequest这个要先处理下:
...
if (client == knownClients.end())
return handleNewConnection(peerAddress, peerPort, dgram);
...
如果是连上的已知的客户端,服务端会进行解密:
...
if ((*client)->isConnectionEncrypted()) {
decryptDatagram(client->get(), dgram);
if ((*client)->dtlsError() == QDtlsError::RemoteClosedConnectionError)
knownClients.erase(client);
return;
}
...
以及进行握手:
...
doHandshake(client->get(), dgram);
...
handleNewConnect()对客户端进行认证,以及发送HelloVerifyRequest:
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"));
...
如果服务端认为新来的客户端可达,那个服务端会创建一个Qtls的配置,然后进行握手:
...
std::unique_ptr<QDtls> newConnection{new QDtls{QSslSocket::SslServerMode}};
newConnection->setDtlsConfiguration(serverConfiguration);
newConnection->setPeer(peerAddress, peerPort);
newConnection->connect(newConnection.get(), &QDtls::pskRequired,
this, &DtlsServer::pskRequired);
knownClients.push_back(std::move(newConnection));
doHandshake(knownClients.back().get(), clientHello);
...
关于握手的代码在doHandshake()中
void DtlsServer::doHandshake(QDtls *newConnection, const QByteArray &clientHello)
{
const bool result = newConnection->doHandshake(&serverSocket, clientHello);
if (!result) {
emit errorMessage(newConnection->dtlsErrorString());
return;
}
const QString peerInfo = peer_info(newConnection->peerAddress(),
newConnection->peerPort());
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();
}
}
在握手中,QDtls::pskRequired()信号关联到pskRequired()槽函数中,并且设置了PSK:
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::decryptDatagram(QDtls *connection, const QByteArray &clientMessage)
{
Q_ASSERT(connection->isConnectionEncrypted());
const QString peerInfo = peer_info(connection->peerAddress(), connection->peerPort());
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());
}
}
服务端关闭DTLS服务调用QDtls::shutdown()
void DtlsServer::shutdown()
{
for (const auto &connection : qExchange(knownClients, {}))
connection->shutdown(&serverSocket);
serverSocket.close();
}
下面是出现问题或警告时的代码:
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));
}
以上是关于Qt文档阅读笔记-DTLS server解析的主要内容,如果未能解决你的问题,请参考以下文章
Qt文档阅读笔记-Threaded Fortune Server Example解析
网络协议文档阅读笔记-TLS vs DTLS | Difference between TLS and DTLS
网络协议文档阅读笔记-Introduction to DTLS(Datagram Transport Layer Security)
Qt文档阅读笔记-Simple Chat Example解析