Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qdtls_openssl.cpp
Go to the documentation of this file.
1// Copyright (C) 2018 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#include <QtNetwork/private/qnativesocketengine_p_p.h>
5
9
10#include <QtNetwork/private/qsslpresharedkeyauthenticator_p.h>
11#include <QtNetwork/private/qsslcertificate_p.h>
12#include <QtNetwork/private/qssl_p.h>
13
14#include <QtNetwork/qudpsocket.h>
15
16#include <QtCore/qmessageauthenticationcode.h>
17#include <QtCore/qcryptographichash.h>
18
19#include <QtCore/qdebug.h>
20
21#include <cstring>
22#include <cstddef>
23
24QT_BEGIN_NAMESPACE
25
26#define QT_DTLS_VERBOSE 0
27
29
30#define qDtlsWarning(arg) qWarning(arg)
31#define qDtlsDebug(arg) qDebug(arg)
32
33#else
34
35#define qDtlsWarning(arg)
36#define qDtlsDebug(arg)
37
38#endif // QT_DTLS_VERBOSE
39
40namespace dtlsutil
41{
42
44{
45 Q_ASSERT(ssl);
46
47 // SSL_get_rbio does not increment the reference count
48 BIO *readBIO = q_SSL_get_rbio(ssl);
49 if (!readBIO) {
50 qCWarning(lcTlsBackend, "No BIO (dgram) found in SSL object");
51 return {};
52 }
53
54 auto listener = static_cast<dtlsopenssl::DtlsState *>(q_BIO_get_app_data(readBIO));
55 if (!listener) {
56 qCWarning(lcTlsBackend, "BIO_get_app_data returned invalid (nullptr) value");
57 return {};
58 }
59
60 const QHostAddress peerAddress(listener->remoteAddress);
61 const quint16 peerPort(listener->remotePort);
62 QByteArray peerData;
63 if (peerAddress.protocol() == QAbstractSocket::IPv6Protocol) {
64 const Q_IPV6ADDR sin6_addr(peerAddress.toIPv6Address());
65 peerData.resize(int(sizeof sin6_addr + sizeof peerPort));
66 char *dst = peerData.data();
67 std::memcpy(dst, &peerPort, sizeof peerPort);
68 dst += sizeof peerPort;
69 std::memcpy(dst, &sin6_addr, sizeof sin6_addr);
70 } else if (peerAddress.protocol() == QAbstractSocket::IPv4Protocol) {
71 const quint32 sin_addr(peerAddress.toIPv4Address());
72 peerData.resize(int(sizeof sin_addr + sizeof peerPort));
73 char *dst = peerData.data();
74 std::memcpy(dst, &peerPort, sizeof peerPort);
75 dst += sizeof peerPort;
76 std::memcpy(dst, &sin_addr, sizeof sin_addr);
77 } else {
78 Q_UNREACHABLE();
79 }
80
81 return peerData;
82}
83
85{
87 {
88 key.resize(32);
89 const int status = q_RAND_bytes(reinterpret_cast<unsigned char *>(key.data()),
90 key.size());
91 if (status <= 0)
92 key.clear();
93 }
94
96
98};
99
101{
102 static const FallbackCookieSecret generator;
103 return generator.key;
104}
105
106int next_timeoutMs(SSL *tlsConnection)
107{
108 Q_ASSERT(tlsConnection);
109 timeval timeLeft = {};
110 q_DTLSv1_get_timeout(tlsConnection, &timeLeft);
111 return timeLeft.tv_sec * 1000;
112}
113
114
115void delete_connection(SSL *ssl)
116{
117 // The 'deleter' for QSharedPointer<SSL>.
118 if (ssl)
119 q_SSL_free(ssl);
120}
121
122void delete_BIO_ADDR(BIO_ADDR *bio)
123{
124 // A deleter for QSharedPointer<BIO_ADDR>
125 if (bio)
126 q_BIO_ADDR_free(bio);
127}
128
129void delete_bio_method(BIO_METHOD *method)
130{
131 // The 'deleter' for QSharedPointer<BIO_METHOD>.
132 if (method)
133 q_BIO_meth_free(method);
134}
135
136// The path MTU discovery is non-trivial: it's a mix of getsockopt/setsockopt
137// (IP_MTU/IP6_MTU/IP_MTU_DISCOVER) and fallback MTU values. It's not
138// supported on all platforms, worse so - imposes specific requirements on
139// underlying UDP socket etc. So for now, we either try a user-proposed MTU
140// hint or rely on our own fallback value. As a fallback mtu OpenSSL uses 576
141// for IPv4 and 1280 for IPv6 (RFC 791, RFC 2460). To KIS we use 576. This
142// rather small MTU value does not affect the size that can be read/written
143// by QDtls, only a handshake (which is allowed to fragment).
144enum class MtuGuess : long
145{
147};
148
149} // namespace dtlsutil
150
152{
153
154extern "C" int q_generate_cookie_callback(SSL *ssl, unsigned char *dst,
155 unsigned *cookieLength)
156{
157 if (!ssl || !dst || !cookieLength) {
158 qCWarning(lcTlsBackend,
159 "Failed to generate cookie - invalid (nullptr) parameter(s)");
160 return 0;
161 }
162
164 if (!generic) {
165 qCWarning(lcTlsBackend, "SSL_get_ex_data returned nullptr, cannot generate cookie");
166 return 0;
167 }
168
169 *cookieLength = 0;
170
171 auto dtls = static_cast<dtlsopenssl::DtlsState *>(generic);
172 if (!dtls->secret.size())
173 return 0;
174
175 const QByteArray peerData(dtlsutil::cookie_for_peer(ssl));
176 if (!peerData.size())
177 return 0;
178
179 QMessageAuthenticationCode hmac(dtls->hashAlgorithm, dtls->secret);
180 hmac.addData(peerData);
181 const QByteArrayView cookie = hmac.resultView();
182 Q_ASSERT(cookie.size() >= 0);
183 // DTLS1_COOKIE_LENGTH is erroneously 256 bytes long, must be 255 - RFC 6347, 4.2.1.
184 *cookieLength = qMin(DTLS1_COOKIE_LENGTH - 1, cookie.size());
185 std::memcpy(dst, cookie.constData(), *cookieLength);
186
187 return 1;
188}
189
190extern "C" int q_verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
191 unsigned cookieLength)
192{
193 if (!ssl || !cookie || !cookieLength) {
194 qCWarning(lcTlsBackend, "Could not verify cookie, invalid (nullptr or zero) parameters");
195 return 0;
196 }
197
198 unsigned char newCookie[DTLS1_COOKIE_LENGTH] = {};
199 unsigned newCookieLength = 0;
200 if (q_generate_cookie_callback(ssl, newCookie, &newCookieLength) != 1)
201 return 0;
202
203 return newCookieLength == cookieLength
204 && !q_CRYPTO_memcmp(cookie, newCookie, size_t(cookieLength));
205}
206
207extern "C" int q_X509DtlsCallback(int ok, X509_STORE_CTX *ctx)
208{
209 if (!ok) {
210 // Store the error and at which depth the error was detected.
212 if (!ssl) {
213 qCWarning(lcTlsBackend, "X509_STORE_CTX_get_ex_data returned nullptr, handshake failure");
214 return 0;
215 }
216
218 if (!generic) {
219 qCWarning(lcTlsBackend, "SSL_get_ex_data returned nullptr, handshake failure");
220 return 0;
221 }
222
223 auto dtls = static_cast<dtlsopenssl::DtlsState *>(generic);
224 dtls->x509Errors.append(QTlsPrivate::X509CertificateOpenSSL::errorEntryFromStoreContext(ctx));
225 }
226
227 // Always return 1 (OK) to allow verification to continue. We handle the
228 // errors gracefully after collecting all errors, after verification has
229 // completed.
230 return 1;
231}
232
233extern "C" unsigned q_PSK_client_callback(SSL *ssl, const char *hint, char *identity,
234 unsigned max_identity_len, unsigned char *psk,
235 unsigned max_psk_len)
236{
237 auto *dtls = static_cast<dtlsopenssl::DtlsState *>(q_SSL_get_ex_data(ssl,
239 if (!dtls)
240 return 0;
241
242 Q_ASSERT(dtls->dtlsPrivate);
243 return dtls->dtlsPrivate->pskClientCallback(hint, identity, max_identity_len, psk, max_psk_len);
244}
245
246extern "C" unsigned q_PSK_server_callback(SSL *ssl, const char *identity, unsigned char *psk,
247 unsigned max_psk_len)
248{
249 auto *dtls = static_cast<dtlsopenssl::DtlsState *>(q_SSL_get_ex_data(ssl,
251 if (!dtls)
252 return 0;
253
254 Q_ASSERT(dtls->dtlsPrivate);
255 return dtls->dtlsPrivate->pskServerCallback(identity, psk, max_psk_len);
256}
257
258} // namespace dtlscallbacks
259
260namespace dtlsbio
261{
262
263extern "C" int q_dgram_read(BIO *bio, char *dst, int bytesToRead)
264{
265 if (!bio || !dst || bytesToRead <= 0) {
266 qCWarning(lcTlsBackend, "invalid input parameter(s)");
267 return 0;
268 }
269
271
272 auto dtls = static_cast<dtlsopenssl::DtlsState *>(q_BIO_get_app_data(bio));
273 // It's us who set data, if OpenSSL does too, the logic here is wrong
274 // then and we have to use BIO_set_app_data then!
275 Q_ASSERT(dtls);
276 int bytesRead = 0;
277 if (dtls->dgram.size()) {
278 bytesRead = qMin(dtls->dgram.size(), bytesToRead);
279 std::memcpy(dst, dtls->dgram.constData(), bytesRead);
280
281 if (!dtls->peeking)
282 dtls->dgram = dtls->dgram.mid(bytesRead);
283 } else {
284 bytesRead = -1;
285 }
286
287 if (bytesRead <= 0)
289
290 return bytesRead;
291}
292
293extern "C" int q_dgram_write(BIO *bio, const char *src, int bytesToWrite)
294{
295 if (!bio || !src || bytesToWrite <= 0) {
296 qCWarning(lcTlsBackend, "invalid input parameter(s)");
297 return 0;
298 }
299
301
302 auto dtls = static_cast<dtlsopenssl::DtlsState *>(q_BIO_get_app_data(bio));
303 Q_ASSERT(dtls);
304 if (dtls->writeSuppressed) {
305 // See the comment in QDtls::startHandshake.
306 return bytesToWrite;
307 }
308
309 QUdpSocket *udpSocket = dtls->udpSocket;
310 Q_ASSERT(udpSocket);
311
312 const QByteArray dgram(QByteArray::fromRawData(src, bytesToWrite));
313 qint64 bytesWritten = -1;
314 if (udpSocket->state() == QAbstractSocket::ConnectedState) {
315 bytesWritten = udpSocket->write(dgram);
316 } else {
317 bytesWritten = udpSocket->writeDatagram(dgram, dtls->remoteAddress,
318 dtls->remotePort);
319 }
320
321 if (bytesWritten <= 0)
323
324 Q_ASSERT(bytesWritten <= std::numeric_limits<int>::max());
325 return int(bytesWritten);
326}
327
328extern "C" int q_dgram_puts(BIO *bio, const char *src)
329{
330 if (!bio || !src) {
331 qCWarning(lcTlsBackend, "invalid input parameter(s)");
332 return 0;
333 }
334
335 return q_dgram_write(bio, src, int(std::strlen(src)));
336}
337
338extern "C" long q_dgram_ctrl(BIO *bio, int cmd, long num, void *ptr)
339{
340 // This is our custom BIO_ctrl. bio.h defines a lot of BIO_CTRL_*
341 // and BIO_* constants and BIO_somename macros that expands to BIO_ctrl
342 // call with one of those constants as argument. What exactly BIO_ctrl
343 // does - depends on the 'cmd' and the type of BIO (so BIO_ctrl does
344 // not even have a single well-defined value meaning success or failure).
345 // We handle only the most generic commands - the ones documented for
346 // BIO_ctrl - and also DGRAM specific ones. And even for them - in most
347 // cases we do nothing but report a success or some non-error value.
348 // Documents also state: "Source/sink BIOs return an 0 if they do not
349 // recognize the BIO_ctrl() operation." - these are covered by 'default'
350 // label in the switch-statement below. Debug messages in the switch mean:
351 // 1) we got a command that is unexpected for dgram BIO, or:
352 // 2) we do not call any function that would lead to OpenSSL using this
353 // command.
354
355 if (!bio) {
356 qCDebug(lcTlsBackend, "invalid 'bio' parameter (nullptr)");
357 return -1;
358 }
359
360 auto dtls = static_cast<dtlsopenssl::DtlsState *>(q_BIO_get_app_data(bio));
361 Q_ASSERT(dtls);
362
363 switch (cmd) {
364 // Let's start from the most generic ones, in the order in which they are
365 // documented (as BIO_ctrl):
366 case BIO_CTRL_RESET:
367 // BIO_reset macro.
368 // From documentation:
369 // "BIO_reset() normally returns 1 for success and 0 or -1 for failure.
370 // File BIOs are an exception, they return 0 for success and -1 for
371 // failure."
372 // We have nothing to reset and we are not file BIO.
373 return 1;
374 case BIO_C_FILE_SEEK:
375 case BIO_C_FILE_TELL:
376 qDtlsWarning("Unexpected cmd (BIO_C_FILE_SEEK/BIO_C_FILE_TELL)");
377 // These are for BIO_seek, BIO_tell. We are not a file BIO.
378 // Non-negative return value means success.
379 return 0;
380 case BIO_CTRL_FLUSH:
381 // BIO_flush, nothing to do, we do not buffer any data.
382 // 0 or -1 means error, 1 - success.
383 return 1;
384 case BIO_CTRL_EOF:
385 qDtlsWarning("Unexpected cmd (BIO_CTRL_EOF)");
386 // BIO_eof, 1 means EOF read. Makes no sense for us.
387 return 0;
388 case BIO_CTRL_SET_CLOSE:
389 // BIO_set_close with BIO_CLOSE/BIO_NOCLOSE flags. Documented as
390 // always returning 1.
391 // From the documentation:
392 // "Typically BIO_CLOSE is used in a source/sink BIO to indicate that
393 // the underlying I/O stream should be closed when the BIO is freed."
394 //
395 // QUdpSocket we work with is not BIO's business, ignoring.
396 return 1;
397 case BIO_CTRL_GET_CLOSE:
398 // BIO_get_close. No, never, see the comment above.
399 return 0;
400 case BIO_CTRL_PENDING:
401 qDtlsWarning("Unexpected cmd (BIO_CTRL_PENDING)");
402 // BIO_pending. Not used by DTLS/OpenSSL (we are not buffering).
403 return 0;
404 case BIO_CTRL_WPENDING:
405 // No, we have nothing buffered.
406 return 0;
407 // The constants below are not documented as a part BIO_ctrl documentation,
408 // but they are also not type-specific.
409 case BIO_CTRL_DUP:
410 qDtlsWarning("Unexpected cmd (BIO_CTRL_DUP)");
411 // BIO_dup_state, not used by DTLS (and socket-related BIOs in general).
412 // For some very specific BIO type this 'cmd' would copy some state
413 // from 'bio' to (BIO*)'ptr'. 1 means success.
414 return 0;
415 case BIO_CTRL_SET_CALLBACK:
416 qDtlsWarning("Unexpected cmd (BIO_CTRL_SET_CALLBACK)");
417 // BIO_set_info_callback. We never call this, OpenSSL does not do this
418 // on its own (normally it's used if client code wants to have some
419 // debug information, for example, dumping handshake state via
420 // BIO_printf from SSL info_callback).
421 return 0;
422 case BIO_CTRL_GET_CALLBACK:
423 qDtlsWarning("Unexpected cmd (BIO_CTRL_GET_CALLBACK)");
424 // BIO_get_info_callback. We never call this.
425 if (ptr)
426 *static_cast<bio_info_cb **>(ptr) = nullptr;
427 return 0;
428 case BIO_CTRL_SET:
429 case BIO_CTRL_GET:
430 qDtlsWarning("Unexpected cmd (BIO_CTRL_SET/BIO_CTRL_GET)");
431 // Somewhat 'documented' as setting/getting IO type. Not used anywhere
432 // except BIO_buffer_get_num_lines (which contradics 'get IO type').
433 // Ignoring.
434 return 0;
435 // DGRAM-specific operation, we have to return some reasonable value
436 // (so far, I've encountered only peek mode switching, connect).
437 case BIO_CTRL_DGRAM_CONNECT:
438 // BIO_ctrl_dgram_connect. Not needed. Our 'dtls' already knows
439 // the peer's address/port. Report success though.
440 return 1;
441 case BIO_CTRL_DGRAM_SET_CONNECTED:
442 qDtlsWarning("Unexpected cmd (BIO_CTRL_DGRAM_SET_CONNECTED)");
443 // BIO_ctrl_dgram_set_connected. We never call it, OpenSSL does
444 // not call it on its own (so normally it's done by client code).
445 // Similar to BIO_CTRL_DGRAM_CONNECT, but it also informs the BIO
446 // that its UDP socket is connected. We never need it though.
447 return -1;
448 case BIO_CTRL_DGRAM_SET_RECV_TIMEOUT:
449 qDtlsWarning("Unexpected cmd (BIO_CTRL_DGRAM_SET_RECV_TIMEOUT)");
450 // Essentially setsockopt with SO_RCVTIMEO, not needed, our sockets
451 // are non-blocking.
452 return -1;
453 case BIO_CTRL_DGRAM_GET_RECV_TIMEOUT:
454 qDtlsWarning("Unexpected cmd (BIO_CTRL_DGRAM_GET_RECV_TIMEOUT)");
455 // getsockopt with SO_RCVTIMEO, not needed, our sockets are
456 // non-blocking. ptr is timeval *.
457 return -1;
458 case BIO_CTRL_DGRAM_SET_SEND_TIMEOUT:
459 qDtlsWarning("Unexpected cmd (BIO_CTRL_DGRAM_SET_SEND_TIMEOUT)");
460 // setsockopt, SO_SNDTIMEO, cannot happen.
461 return -1;
462 case BIO_CTRL_DGRAM_GET_SEND_TIMEOUT:
463 qDtlsWarning("Unexpected cmd (BIO_CTRL_DGRAM_GET_SEND_TIMEOUT)");
464 // getsockopt, SO_SNDTIMEO, cannot happen.
465 return -1;
466 case BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP:
467 // BIO_dgram_recv_timedout. No, we are non-blocking.
468 return 0;
469 case BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP:
470 // BIO_dgram_send_timedout. No, we are non-blocking.
471 return 0;
472 case BIO_CTRL_DGRAM_MTU_DISCOVER:
473 qDtlsWarning("Unexpected cmd (BIO_CTRL_DGRAM_MTU_DISCOVER)");
474 // setsockopt, IP_MTU_DISCOVER/IP6_MTU_DISCOVER, to be done
475 // in QUdpSocket instead. OpenSSL never calls it, only client
476 // code.
477 return 1;
478 case BIO_CTRL_DGRAM_QUERY_MTU:
479 qDtlsWarning("Unexpected cmd (BIO_CTRL_DGRAM_QUERY_MTU)");
480 // To be done in QUdpSocket instead.
481 return 1;
482 case BIO_CTRL_DGRAM_GET_FALLBACK_MTU:
483 qDtlsWarning("Unexpected command *BIO_CTRL_DGRAM_GET_FALLBACK_MTU)");
484 // Without SSL_OP_NO_QUERY_MTU set on SSL, OpenSSL can request for
485 // fallback MTU after several re-transmissions.
486 // Should never happen in our case.
488 case BIO_CTRL_DGRAM_GET_MTU:
489 qDtlsWarning("Unexpected cmd (BIO_CTRL_DGRAM_GET_MTU)");
490 return -1;
491 case BIO_CTRL_DGRAM_SET_MTU:
492 qDtlsWarning("Unexpected cmd (BIO_CTRL_DGRAM_SET_MTU)");
493 // Should not happen (we don't call BIO_ctrl with this parameter)
494 // and set MTU on SSL instead.
495 return -1; // num is mtu and it's a return value meaning success.
496 case BIO_CTRL_DGRAM_MTU_EXCEEDED:
497 qDtlsWarning("Unexpected cmd (BIO_CTRL_DGRAM_MTU_EXCEEDED)");
498 return 0;
499 case BIO_CTRL_DGRAM_GET_PEER:
500 qDtlsDebug("BIO_CTRL_DGRAM_GET_PEER");
501 // BIO_dgram_get_peer. We do not return a real address (DTLS is not
502 // using this address), but let's pretend a success.
503 switch (dtls->remoteAddress.protocol()) {
504 case QAbstractSocket::IPv6Protocol:
505 return sizeof(sockaddr_in6);
506 case QAbstractSocket::IPv4Protocol:
507 return sizeof(sockaddr_in);
508 default:
509 return -1;
510 }
511 case BIO_CTRL_DGRAM_SET_PEER:
512 // Similar to BIO_CTRL_DGRAM_CONNECTED.
513 return 1;
514 case BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT:
515 // DTLSTODO: I'm not sure yet, how it's used by OpenSSL.
516 return 1;
517 case BIO_CTRL_DGRAM_SET_DONT_FRAG:
518 qDtlsDebug("BIO_CTRL_DGRAM_SET_DONT_FRAG");
519 // To be done in QUdpSocket, it's about IP_DONTFRAG etc.
520 return 1;
521 case BIO_CTRL_DGRAM_GET_MTU_OVERHEAD:
522 // AFAIK it's 28 for IPv4 and 48 for IPv6, but let's pretend it's 0
523 // so that OpenSSL does not start suddenly fragmenting the first
524 // client hello (which will result in DTLSv1_listen rejecting it).
525 return 0;
526 case BIO_CTRL_DGRAM_SET_PEEK_MODE:
527 dtls->peeking = num;
528 return 1;
529 default:;
531 qWarning() << "Unexpected cmd (" << cmd << ")";
532#endif
533 }
534
535 return 0;
536}
537
538extern "C" int q_dgram_create(BIO *bio)
539{
540
542 // With a custom BIO you'd normally allocate some implementation-specific
543 // data and append it to this new BIO using BIO_set_data. We don't need
544 // it and thus q_dgram_destroy below is a noop.
545 return 1;
546}
547
548extern "C" int q_dgram_destroy(BIO *bio)
549{
550 Q_UNUSED(bio);
551 return 1;
552}
553
554const char * const qdtlsMethodName = "qdtlsbio";
555
556} // namespace dtlsbio
557
558namespace dtlsopenssl
559{
560
561bool DtlsState::init(QDtlsBasePrivate *dtlsBase, QUdpSocket *socket,
562 const QHostAddress &remote, quint16 port,
563 const QByteArray &receivedMessage)
564{
565 Q_ASSERT(dtlsBase);
566 Q_ASSERT(socket);
567
568 if (!tlsContext && !initTls(dtlsBase))
569 return false;
570
571 udpSocket = socket;
572
573 setLinkMtu(dtlsBase);
574
575 dgram = receivedMessage;
576 remoteAddress = remote;
577 remotePort = port;
578
579 // SSL_get_rbio does not increment a reference count.
580 BIO *bio = q_SSL_get_rbio(tlsConnection.data());
581 Q_ASSERT(bio);
582 q_BIO_set_app_data(bio, this);
583
584 return true;
585}
586
588{
589 tlsConnection.reset();
590 tlsContext.reset();
591}
592
593bool DtlsState::initTls(QDtlsBasePrivate *dtlsBase)
594{
595 if (tlsContext)
596 return true;
597
598 if (!QSslSocket::supportsSsl())
599 return false;
600
601 if (!initCtxAndConnection(dtlsBase))
602 return false;
603
604 if (!initBIO(dtlsBase)) {
605 tlsConnection.reset();
606 tlsContext.reset();
607 return false;
608 }
609
610 return true;
611}
612
613static QString msgFunctionFailed(const char *function)
614{
615 //: %1: Some function
616 return QDtls::tr("%1 failed").arg(QLatin1StringView(function));
617}
618
619bool DtlsState::initCtxAndConnection(QDtlsBasePrivate *dtlsBase)
620{
621 Q_ASSERT(dtlsBase);
622 Q_ASSERT(QSslSocket::supportsSsl());
623
624 if (dtlsBase->mode == QSslSocket::UnencryptedMode) {
625 dtlsBase->setDtlsError(QDtlsError::TlsInitializationError,
626 QDtls::tr("Invalid SslMode, SslServerMode or SslClientMode expected"));
627 return false;
628 }
629
630 if (!QDtlsBasePrivate::isDtlsProtocol(dtlsBase->dtlsConfiguration.protocol())) {
631 dtlsBase->setDtlsError(QDtlsError::TlsInitializationError,
632 QDtls::tr("Invalid protocol version, DTLS protocol expected"));
633 return false;
634 }
635
636 const bool rootsOnDemand = QTlsBackend::rootLoadingOnDemandAllowed(dtlsBase->dtlsConfiguration);
637 TlsContext newContext(QSslContext::sharedFromConfiguration(dtlsBase->mode, dtlsBase->dtlsConfiguration,
638 rootsOnDemand));
639
640 if (newContext->error() != QSslError::NoError) {
641 dtlsBase->setDtlsError(QDtlsError::TlsInitializationError, newContext->errorString());
642 return false;
643 }
644
645 TlsConnection newConnection(newContext->createSsl(), dtlsutil::delete_connection);
646 if (!newConnection.data()) {
647 dtlsBase->setDtlsError(QDtlsError::TlsInitializationError,
648 msgFunctionFailed("SSL_new"));
649 return false;
650 }
651
652 const int set = q_SSL_set_ex_data(newConnection.data(),
654 this);
655
656 if (set != 1 && dtlsBase->dtlsConfiguration.peerVerifyMode() != QSslSocket::VerifyNone) {
657 dtlsBase->setDtlsError(QDtlsError::TlsInitializationError,
658 msgFunctionFailed("SSL_set_ex_data"));
659 return false;
660 }
661
662 if (dtlsBase->mode == QSslSocket::SslServerMode) {
663 if (dtlsBase->dtlsConfiguration.dtlsCookieVerificationEnabled())
664 q_SSL_set_options(newConnection.data(), SSL_OP_COOKIE_EXCHANGE);
665 q_SSL_set_psk_server_callback(newConnection.data(), dtlscallbacks::q_PSK_server_callback);
666 } else {
667 q_SSL_set_psk_client_callback(newConnection.data(), dtlscallbacks::q_PSK_client_callback);
668 }
669
670 tlsContext.swap(newContext);
671 tlsConnection.swap(newConnection);
672
673 return true;
674}
675
676bool DtlsState::initBIO(QDtlsBasePrivate *dtlsBase)
677{
678 Q_ASSERT(dtlsBase);
679 Q_ASSERT(tlsContext && tlsConnection);
680
681 BioMethod customMethod(q_BIO_meth_new(BIO_TYPE_DGRAM, dtlsbio::qdtlsMethodName),
683 if (!customMethod.data()) {
684 dtlsBase->setDtlsError(QDtlsError::TlsInitializationError,
685 msgFunctionFailed("BIO_meth_new"));
686 return false;
687 }
688
689 BIO_METHOD *biom = customMethod.data();
690 q_BIO_meth_set_create(biom, dtlsbio::q_dgram_create);
691 q_BIO_meth_set_destroy(biom, dtlsbio::q_dgram_destroy);
692 q_BIO_meth_set_read(biom, dtlsbio::q_dgram_read);
693 q_BIO_meth_set_write(biom, dtlsbio::q_dgram_write);
694 q_BIO_meth_set_puts(biom, dtlsbio::q_dgram_puts);
695 q_BIO_meth_set_ctrl(biom, dtlsbio::q_dgram_ctrl);
696
697 BIO *bio = q_BIO_new(biom);
698 if (!bio) {
699 dtlsBase->setDtlsError(QDtlsError::TlsInitializationError,
700 msgFunctionFailed("BIO_new"));
701 return false;
702 }
703
704 q_SSL_set_bio(tlsConnection.data(), bio, bio);
705
706 bioMethod.swap(customMethod);
707
708 return true;
709}
710
711void DtlsState::setLinkMtu(QDtlsBasePrivate *dtlsBase)
712{
713 Q_ASSERT(dtlsBase);
714 Q_ASSERT(udpSocket);
715 Q_ASSERT(tlsConnection.data());
716
717 long mtu = dtlsBase->mtuHint;
718 if (!mtu) {
719 // If the underlying QUdpSocket was connected, getsockopt with
720 // IP_MTU/IP6_MTU can give us some hint:
721 bool optionFound = false;
722 if (udpSocket->state() == QAbstractSocket::ConnectedState) {
723 const QVariant val(udpSocket->socketOption(QAbstractSocket::PathMtuSocketOption));
724 if (val.isValid() && val.canConvert<int>())
725 mtu = val.toInt(&optionFound);
726 }
727
728 if (!optionFound || mtu <= 0) {
729 // OK, our own initial guess.
731 }
732 }
733
734 // For now, we disable this option.
735 q_SSL_set_options(tlsConnection.data(), SSL_OP_NO_QUERY_MTU);
736
737 q_DTLS_set_link_mtu(tlsConnection.data(), mtu);
738}
739
740} // namespace dtlsopenssl
741
746
747bool QDtlsClientVerifierOpenSSL::verifyClient(QUdpSocket *socket, const QByteArray &dgram,
748 const QHostAddress &address, quint16 port)
749{
750 Q_ASSERT(socket);
751 Q_ASSERT(dgram.size());
752 Q_ASSERT(!address.isNull());
753 Q_ASSERT(port);
754
755 clearDtlsError();
756 verifiedClientHello.clear();
757
758 if (!dtls.init(this, socket, address, port, dgram))
759 return false;
760
761 dtls.secret = secret;
762 dtls.hashAlgorithm = hashAlgorithm;
763
764 Q_ASSERT(dtls.tlsConnection.data());
765 QSharedPointer<BIO_ADDR> peer(q_BIO_ADDR_new(), dtlsutil::delete_BIO_ADDR);
766 if (!peer.data()) {
767 setDtlsError(QDtlsError::TlsInitializationError,
768 QDtlsClientVerifier::tr("BIO_ADDR_new failed, ignoring client hello"));
769 return false;
770 }
771
772 const int ret = q_DTLSv1_listen(dtls.tlsConnection.data(), peer.data());
773 if (ret < 0) {
774 // Since 1.1 - it's a fatal error (not so in 1.0.2 for non-blocking socket)
775 setDtlsError(QDtlsError::TlsFatalError, QTlsBackendOpenSSL::getErrorsFromOpenSsl());
776 return false;
777 }
778
779 if (ret > 0) {
780 verifiedClientHello = dgram;
781 return true;
782 }
783
784 return false;
785}
786
788{
789 return verifiedClientHello;
790}
791
792void QDtlsPrivateOpenSSL::TimeoutHandler::start(int hintMs)
793{
794 Q_ASSERT(!timer.isActive());
795 timer.start(hintMs > 0 ? hintMs : timeoutMs, Qt::PreciseTimer, this);
796}
797
798void QDtlsPrivateOpenSSL::TimeoutHandler::doubleTimeout()
799{
800 if (timeoutMs * 2 < 60000)
801 timeoutMs *= 2;
802 else
803 timeoutMs = 60000;
804}
805
806void QDtlsPrivateOpenSSL::TimeoutHandler::stop()
807{
808 timer.stop();
809}
810
811void QDtlsPrivateOpenSSL::TimeoutHandler::timerEvent(QTimerEvent *event)
812{
813 Q_UNUSED(event);
814 Q_ASSERT(timer.isActive());
815
816 timer.stop();
817
818 Q_ASSERT(dtlsConnection);
819 dtlsConnection->reportTimeout();
820}
821
822QDtlsPrivateOpenSSL::QDtlsPrivateOpenSSL(QDtls *qObject, QSslSocket::SslMode side)
823 : QDtlsBasePrivate(side, dtlsutil::fallbackSecret()), q(qObject)
824{
825 Q_ASSERT(qObject);
826
827 dtls.dtlsPrivate = this;
828}
829
831{
832 return mode;
833}
834
835void QDtlsPrivateOpenSSL::setPeer(const QHostAddress &addr, quint16 port, const QString &name)
836{
837 remoteAddress = addr;
838 remotePort = port;
839 peerVfyName = name;
840}
841
843{
844 return remoteAddress;
845}
846
848{
849 return remotePort;
850}
851
853{
854 peerVfyName = name;
855}
856
858{
859 return peerVfyName;
860}
861
863{
864 mtuHint = mtu;
865}
866
868{
869 return mtuHint;
870}
871
873{
874 return handshakeState;
875}
876
878{
879 return connectionEncrypted;
880}
881
882bool QDtlsPrivateOpenSSL::startHandshake(QUdpSocket *socket, const QByteArray &dgram)
883{
884 Q_ASSERT(socket);
885 Q_ASSERT(handshakeState == QDtls::HandshakeNotStarted);
886
887 clearDtlsError();
888 connectionEncrypted = false;
889
890 if (!dtls.init(this, socket, remoteAddress, remotePort, dgram))
891 return false;
892
893 if (mode == QSslSocket::SslServerMode && dtlsConfiguration.dtlsCookieVerificationEnabled()) {
894 dtls.secret = secret;
895 dtls.hashAlgorithm = hashAlgorithm;
896 // Let's prepare the state machine so that message sequence 1 does not
897 // surprise DTLS/OpenSSL (such a message would be disregarded as
898 // 'stale or future' in SSL_accept otherwise):
899 int result = 0;
900 QSharedPointer<BIO_ADDR> peer(q_BIO_ADDR_new(), dtlsutil::delete_BIO_ADDR);
901 if (!peer.data()) {
902 setDtlsError(QDtlsError::TlsInitializationError,
903 QDtls::tr("BIO_ADD_new failed, cannot start handshake"));
904 return false;
905 }
906
907 // If it's an invalid/unexpected ClientHello, we don't want to send
908 // VerifyClientRequest - it's a job of QDtlsClientVerifier - so we
909 // suppress any attempts to write into socket:
910 dtls.writeSuppressed = true;
911 result = q_DTLSv1_listen(dtls.tlsConnection.data(), peer.data());
912 dtls.writeSuppressed = false;
913
914 if (result <= 0) {
915 setDtlsError(QDtlsError::TlsFatalError,
916 QDtls::tr("Cannot start the handshake, verified client hello expected"));
917 dtls.reset();
918 return false;
919 }
920 }
921
922 handshakeState = QDtls::HandshakeInProgress;
923 opensslErrors.clear();
924 tlsErrors.clear();
925
926 return continueHandshake(socket, dgram);
927}
928
929bool QDtlsPrivateOpenSSL::continueHandshake(QUdpSocket *socket, const QByteArray &dgram)
930{
931 Q_ASSERT(socket);
932
933 Q_ASSERT(handshakeState == QDtls::HandshakeInProgress);
934
935 clearDtlsError();
936
937 if (timeoutHandler.data())
938 timeoutHandler->stop();
939
940 if (!dtls.init(this, socket, remoteAddress, remotePort, dgram))
941 return false;
942
943 dtls.x509Errors.clear();
944
945 int result = 0;
946 if (mode == QSslSocket::SslServerMode)
947 result = q_SSL_accept(dtls.tlsConnection.data());
948 else
949 result = q_SSL_connect(dtls.tlsConnection.data());
950
951 // DTLSTODO: Investigate/test if it makes sense - QSslSocket can emit
952 // peerVerifyError at this point (and thus potentially client code
953 // will close the underlying TCP connection immediately), but we are using
954 // QUdpSocket, no connection to close, our verification callback returns 1
955 // (verified OK) and this probably means OpenSSL has already sent a reply
956 // to the server's hello/certificate.
957
958 opensslErrors << dtls.x509Errors;
959
960 if (result <= 0) {
961 const auto code = q_SSL_get_error(dtls.tlsConnection.data(), result);
962 switch (code) {
963 case SSL_ERROR_WANT_READ:
964 case SSL_ERROR_WANT_WRITE:
965 // DTLSTODO: to be tested - in principle, if it was the first call to
966 // continueHandshake and server for some reason discards the client
967 // hello message (even the verified one) - our 'this' will probably
968 // forever stay in this strange InProgress state? (the client
969 // will dully re-transmit the same hello and we discard it again?)
970 // SSL_get_state can provide more information about state
971 // machine and we can switch to NotStarted (since we have not
972 // replied with our hello ...)
973 if (!timeoutHandler.data()) {
974 timeoutHandler.reset(new TimeoutHandler);
975 timeoutHandler->dtlsConnection = this;
976 } else {
977 // Back to 1s.
978 timeoutHandler->resetTimeout();
979 }
980
981 timeoutHandler->start();
982
983 return true; // The handshake is not yet complete.
984 default:
985 storePeerCertificates();
986 setDtlsError(QDtlsError::TlsFatalError,
987 QTlsBackendOpenSSL::msgErrorsDuringHandshake());
988 dtls.reset();
989 handshakeState = QDtls::HandshakeNotStarted;
990 return false;
991 }
992 }
993
994 storePeerCertificates();
995 fetchNegotiatedParameters();
996
997 const bool doVerifyPeer = dtlsConfiguration.peerVerifyMode() == QSslSocket::VerifyPeer
998 || (dtlsConfiguration.peerVerifyMode() == QSslSocket::AutoVerifyPeer
999 && mode == QSslSocket::SslClientMode);
1000
1001 if (!doVerifyPeer || verifyPeer() || tlsErrorsWereIgnored()) {
1002 connectionEncrypted = true;
1003 handshakeState = QDtls::HandshakeComplete;
1004 return true;
1005 }
1006
1007 setDtlsError(QDtlsError::PeerVerificationError, QDtls::tr("Peer verification failed"));
1008 handshakeState = QDtls::PeerVerificationFailed;
1009 return false;
1010}
1011
1012
1013bool QDtlsPrivateOpenSSL::handleTimeout(QUdpSocket *socket)
1014{
1015 Q_ASSERT(socket);
1016
1017 Q_ASSERT(timeoutHandler.data());
1018 Q_ASSERT(dtls.tlsConnection.data());
1019
1020 clearDtlsError();
1021
1022 dtls.udpSocket = socket;
1023
1024 if (q_DTLSv1_handle_timeout(dtls.tlsConnection.data()) > 0) {
1025 timeoutHandler->doubleTimeout();
1026 timeoutHandler->start();
1027 } else {
1028 timeoutHandler->start(dtlsutil::next_timeoutMs(dtls.tlsConnection.data()));
1029 }
1030
1031 return true;
1032}
1033
1034bool QDtlsPrivateOpenSSL::resumeHandshake(QUdpSocket *socket)
1035{
1036 Q_UNUSED(socket);
1037 Q_ASSERT(socket);
1038 Q_ASSERT(handshakeState == QDtls::PeerVerificationFailed);
1039
1040 clearDtlsError();
1041
1042 if (tlsErrorsWereIgnored()) {
1043 handshakeState = QDtls::HandshakeComplete;
1044 connectionEncrypted = true;
1045 tlsErrors.clear();
1046 tlsErrorsToIgnore.clear();
1047 return true;
1048 }
1049
1050 return false;
1051}
1052
1053void QDtlsPrivateOpenSSL::abortHandshake(QUdpSocket *socket)
1054{
1055 Q_ASSERT(socket);
1056 Q_ASSERT(handshakeState == QDtls::PeerVerificationFailed
1057 || handshakeState == QDtls::HandshakeInProgress);
1058
1059 clearDtlsError();
1060
1061 if (handshakeState == QDtls::PeerVerificationFailed) {
1062 // Yes, while peer verification failed, we were actually encrypted.
1063 // Let's play it nice - inform our peer about connection shut down.
1064 sendShutdownAlert(socket);
1065 } else {
1066 resetDtls();
1067 }
1068}
1069
1071{
1072 Q_ASSERT(socket);
1073
1074 clearDtlsError();
1075
1076 if (connectionEncrypted && !connectionWasShutdown) {
1077 dtls.udpSocket = socket;
1078 Q_ASSERT(dtls.tlsConnection.data());
1079 q_SSL_shutdown(dtls.tlsConnection.data());
1080 }
1081
1082 resetDtls();
1083}
1084
1086{
1087 return tlsErrors;
1088}
1089
1090void QDtlsPrivateOpenSSL::ignoreVerificationErrors(const QList<QSslError> &errorsToIgnore)
1091{
1092 tlsErrorsToIgnore = errorsToIgnore;
1093}
1094
1096{
1097 return sessionCipher;
1098}
1099
1101{
1102 return sessionProtocol;
1103}
1104
1106 const QByteArray &dgram)
1107{
1108 Q_ASSERT(socket);
1109 Q_ASSERT(dtls.tlsConnection.data());
1110 Q_ASSERT(connectionEncrypted);
1111
1112 clearDtlsError();
1113
1114 dtls.udpSocket = socket;
1115 const int written = q_SSL_write(dtls.tlsConnection.data(),
1116 dgram.constData(), dgram.size());
1117 if (written > 0)
1118 return written;
1119
1120 const unsigned long errorCode = q_ERR_get_error();
1121 if (!dgram.size() && errorCode == SSL_ERROR_NONE) {
1122 // With OpenSSL <= 1.1 this can happen. For example, DTLS client
1123 // tries to reconnect (while re-using the same address/port) -
1124 // DTLS server drops a message with unexpected epoch but says - no
1125 // error. We leave to client code to resolve such problems until
1126 // OpenSSL provides something better.
1127 return 0;
1128 }
1129
1130 switch (errorCode) {
1131 case SSL_ERROR_WANT_WRITE:
1132 case SSL_ERROR_WANT_READ:
1133 // We do not set any error/description ... a user can probably re-try
1134 // sending a datagram.
1135 break;
1136 case SSL_ERROR_ZERO_RETURN:
1137 connectionWasShutdown = true;
1138 setDtlsError(QDtlsError::TlsFatalError, QDtls::tr("The DTLS connection has been closed"));
1139 handshakeState = QDtls::HandshakeNotStarted;
1140 dtls.reset();
1141 break;
1142 case SSL_ERROR_SYSCALL:
1143 case SSL_ERROR_SSL:
1144 default:
1145 // DTLSTODO: we don't know yet what to do. Tests needed - probably,
1146 // some errors can be just ignored (it's UDP, not TCP after all).
1147 // Unlike QSslSocket we do not abort though.
1148 QString description(QTlsBackendOpenSSL::getErrorsFromOpenSsl());
1149 if (socket->error() != QAbstractSocket::UnknownSocketError && description.isEmpty()) {
1150 setDtlsError(QDtlsError::UnderlyingSocketError, socket->errorString());
1151 } else {
1152 setDtlsError(QDtlsError::TlsFatalError,
1153 QDtls::tr("Error while writing: %1").arg(description));
1154 }
1155 }
1156
1157 return -1;
1158}
1159
1160QByteArray QDtlsPrivateOpenSSL::decryptDatagram(QUdpSocket *socket, const QByteArray &tlsdgram)
1161{
1162 Q_ASSERT(socket);
1163 Q_ASSERT(tlsdgram.size());
1164
1165 Q_ASSERT(dtls.tlsConnection.data());
1166 Q_ASSERT(connectionEncrypted);
1167
1168 dtls.dgram = tlsdgram;
1169 dtls.udpSocket = socket;
1170
1171 clearDtlsError();
1172
1173 QByteArray dgram;
1174 dgram.resize(tlsdgram.size());
1175 const int read = q_SSL_read(dtls.tlsConnection.data(), dgram.data(),
1176 dgram.size());
1177
1178 if (read > 0) {
1179 dgram.resize(read);
1180 return dgram;
1181 }
1182
1183 dgram.clear();
1184 unsigned long errorCode = q_ERR_get_error();
1185 if (errorCode == SSL_ERROR_NONE) {
1186 const int shutdown = q_SSL_get_shutdown(dtls.tlsConnection.data());
1187 if (shutdown & SSL_RECEIVED_SHUTDOWN)
1188 errorCode = SSL_ERROR_ZERO_RETURN;
1189 else
1190 return dgram;
1191 }
1192
1193 switch (errorCode) {
1194 case SSL_ERROR_WANT_READ:
1195 case SSL_ERROR_WANT_WRITE:
1196 return dgram;
1197 case SSL_ERROR_ZERO_RETURN:
1198 // "The connection was shut down cleanly" ... hmm, whatever,
1199 // needs testing (DTLSTODO).
1200 connectionWasShutdown = true;
1201 setDtlsError(QDtlsError::RemoteClosedConnectionError,
1202 QDtls::tr("The DTLS connection has been shutdown"));
1203 dtls.reset();
1204 connectionEncrypted = false;
1205 handshakeState = QDtls::HandshakeNotStarted;
1206 return dgram;
1207 case SSL_ERROR_SYSCALL: // some IO error
1208 case SSL_ERROR_SSL: // error in the SSL library
1209 // DTLSTODO: Apparently, some errors can be ignored, for example,
1210 // ECONNRESET etc. This all needs a lot of testing!!!
1211 default:
1212 setDtlsError(QDtlsError::TlsNonFatalError,
1213 QDtls::tr("Error while reading: %1")
1214 .arg(QTlsBackendOpenSSL::getErrorsFromOpenSsl()));
1215 return dgram;
1216 }
1217}
1218
1219unsigned QDtlsPrivateOpenSSL::pskClientCallback(const char *hint, char *identity,
1220 unsigned max_identity_len,
1221 unsigned char *psk,
1222 unsigned max_psk_len)
1223{
1224 // The code below is taken (with some modifications) from qsslsocket_openssl
1225 // - alas, we cannot simply re-use it, it's in QSslSocketPrivate.
1226 {
1227 QSslPreSharedKeyAuthenticator authenticator;
1228 // Fill in some read-only fields (for client code)
1229 if (hint) {
1230 identityHint.clear();
1231 identityHint.append(hint);
1232 }
1233
1234 QTlsBackend::setupClientPskAuth(&authenticator, hint ? identityHint.constData() : nullptr,
1235 hint ? int(std::strlen(hint)) : 0, max_identity_len, max_psk_len);
1236 pskAuthenticator.swap(authenticator);
1237 }
1238
1239 // Let the client provide the remaining bits...
1240 emit q->pskRequired(&pskAuthenticator);
1241
1242 // No PSK set? Return now to make the handshake fail
1243 if (pskAuthenticator.preSharedKey().isEmpty())
1244 return 0;
1245
1246 // Copy data back into OpenSSL
1247 const int identityLength = qMin(pskAuthenticator.identity().size(),
1248 pskAuthenticator.maximumIdentityLength());
1249 std::memcpy(identity, pskAuthenticator.identity().constData(), identityLength);
1250 identity[identityLength] = 0;
1251
1252 const int pskLength = qMin(pskAuthenticator.preSharedKey().size(),
1253 pskAuthenticator.maximumPreSharedKeyLength());
1254 std::memcpy(psk, pskAuthenticator.preSharedKey().constData(), pskLength);
1255
1256 return pskLength;
1257}
1258
1259unsigned QDtlsPrivateOpenSSL::pskServerCallback(const char *identity, unsigned char *psk,
1260 unsigned max_psk_len)
1261{
1262 {
1263 QSslPreSharedKeyAuthenticator authenticator;
1264 // Fill in some read-only fields (for the user)
1265 QTlsBackend::setupServerPskAuth(&authenticator, identity, dtlsConfiguration.preSharedKeyIdentityHint(),
1266 max_psk_len);
1267 pskAuthenticator.swap(authenticator);
1268 }
1269
1270 // Let the client provide the remaining bits...
1271 emit q->pskRequired(&pskAuthenticator);
1272
1273 // No PSK set? Return now to make the handshake fail
1274 if (pskAuthenticator.preSharedKey().isEmpty())
1275 return 0;
1276
1277 // Copy data back into OpenSSL
1278 const int pskLength = qMin(pskAuthenticator.preSharedKey().size(),
1279 pskAuthenticator.maximumPreSharedKeyLength());
1280
1281 std::memcpy(psk, pskAuthenticator.preSharedKey().constData(), pskLength);
1282
1283 return pskLength;
1284}
1285
1286bool QDtlsPrivateOpenSSL::verifyPeer()
1287{
1288 QList<QSslError> errors;
1289
1290 // Check the whole chain for blacklisting (including root, as we check for
1291 // subjectInfo and issuer)
1292 const auto &peerCertificateChain = dtlsConfiguration.peerCertificateChain();
1293 for (const QSslCertificate &cert : peerCertificateChain) {
1294 if (QSslCertificatePrivate::isBlacklisted(cert))
1295 errors << QSslError(QSslError::CertificateBlacklisted, cert);
1296 }
1297
1298 const auto peerCertificate = dtlsConfiguration.peerCertificate();
1299 if (peerCertificate.isNull()) {
1300 errors << QSslError(QSslError::NoPeerCertificate);
1301 } else if (mode == QSslSocket::SslClientMode) {
1302 // Check the peer certificate itself. First try the subject's common name
1303 // (CN) as a wildcard, then try all alternate subject name DNS entries the
1304 // same way.
1305
1306 // QSslSocket has a rather twisted logic: if verificationPeerName
1307 // is empty, we call QAbstractSocket::peerName(), which returns
1308 // either peerName (can be set by setPeerName) or host name
1309 // (can be set as a result of connectToHost).
1310 QString name = peerVfyName;
1311 if (name.isEmpty()) {
1312 Q_ASSERT(dtls.udpSocket);
1313 name = dtls.udpSocket->peerName();
1314 }
1315
1316 if (!QTlsPrivate::TlsCryptograph::isMatchingHostname(peerCertificate, name))
1317 errors << QSslError(QSslError::HostNameMismatch, peerCertificate);
1318 }
1319
1320 // Translate errors from the error list into QSslErrors
1321 using CertClass = QTlsPrivate::X509CertificateOpenSSL;
1322 errors.reserve(errors.size() + opensslErrors.size());
1323 for (const auto &error : std::as_const(opensslErrors)) {
1324 const auto value = peerCertificateChain.value(error.depth);
1325 errors << CertClass::openSSLErrorToQSslError(error.code, value);
1326 }
1327
1328 tlsErrors = errors;
1329 return tlsErrors.isEmpty();
1330}
1331
1332void QDtlsPrivateOpenSSL::storePeerCertificates()
1333{
1334 Q_ASSERT(dtls.tlsConnection.data());
1335 // Store the peer certificate and chain. For clients, the peer certificate
1336 // chain includes the peer certificate; for servers, it doesn't. Both the
1337 // peer certificate and the chain may be empty if the peer didn't present
1338 // any certificate.
1339 X509 *x509 = q_SSL_get_peer_certificate(dtls.tlsConnection.data());
1340 const auto peerCertificate = QTlsPrivate::X509CertificateOpenSSL::certificateFromX509(x509);
1341 QTlsBackend::storePeerCertificate(dtlsConfiguration, peerCertificate);
1342 q_X509_free(x509);
1343
1344 auto peerCertificateChain = dtlsConfiguration.peerCertificateChain();
1345 if (peerCertificateChain.isEmpty()) {
1346 auto stack = q_SSL_get_peer_cert_chain(dtls.tlsConnection.data());
1347 peerCertificateChain = QTlsPrivate::X509CertificateOpenSSL::stackOfX509ToQSslCertificates(stack);
1348 if (!peerCertificate.isNull() && mode == QSslSocket::SslServerMode)
1349 peerCertificateChain.prepend(peerCertificate);
1350 QTlsBackend::storePeerCertificateChain(dtlsConfiguration, peerCertificateChain);
1351 }
1352}
1353
1354bool QDtlsPrivateOpenSSL::tlsErrorsWereIgnored() const
1355{
1356 // check whether the errors we got are all in the list of expected errors
1357 // (applies only if the method QDtlsConnection::ignoreTlsErrors(const
1358 // QList<QSslError> &errors) was called)
1359 for (const QSslError &error : tlsErrors) {
1360 if (!tlsErrorsToIgnore.contains(error))
1361 return false;
1362 }
1363
1364 return !tlsErrorsToIgnore.empty();
1365}
1366
1367void QDtlsPrivateOpenSSL::fetchNegotiatedParameters()
1368{
1369 Q_ASSERT(dtls.tlsConnection.data());
1370
1371 if (const SSL_CIPHER *cipher = q_SSL_get_current_cipher(dtls.tlsConnection.data()))
1372 sessionCipher = QTlsBackendOpenSSL::qt_OpenSSL_cipher_to_QSslCipher(cipher);
1373 else
1374 sessionCipher = {};
1375
1376 // Note: cipher's protocol version will be reported as either TLS 1.0 or
1377 // TLS 1.2, that's how it's set by OpenSSL (and that's what they are?).
1378
1379 switch (q_SSL_version(dtls.tlsConnection.data())) {
1380QT_WARNING_PUSH
1381QT_WARNING_DISABLE_DEPRECATED
1382 case DTLS1_VERSION:
1383 sessionProtocol = QSsl::DtlsV1_0;
1384 break;
1385QT_WARNING_POP
1386 case DTLS1_2_VERSION:
1387 sessionProtocol = QSsl::DtlsV1_2;
1388 break;
1389 default:
1390 qCWarning(lcTlsBackend, "unknown protocol version");
1391 sessionProtocol = QSsl::UnknownProtocol;
1392 }
1393}
1394
1395void QDtlsPrivateOpenSSL::reportTimeout()
1396{
1397 emit q->handshakeTimeout();
1398}
1399
1400void QDtlsPrivateOpenSSL::resetDtls()
1401{
1402 dtls.reset();
1403 connectionEncrypted = false;
1404 tlsErrors.clear();
1405 tlsErrorsToIgnore.clear();
1406 QTlsBackend::clearPeerCertificates(dtlsConfiguration);
1407 connectionWasShutdown = false;
1408 handshakeState = QDtls::HandshakeNotStarted;
1409 sessionCipher = {};
1410 sessionProtocol = QSsl::UnknownProtocol;
1411}
1412
1413QT_END_NAMESPACE
QByteArray verifiedHello() const override
bool verifyClient(QUdpSocket *socket, const QByteArray &dgram, const QHostAddress &address, quint16 port) override
void abortHandshake(QUdpSocket *socket) override
virtual QDtls::HandshakeState state() const override
QHostAddress peerAddress() const override
QSslSocket::SslMode cryptographMode() const override
void ignoreVerificationErrors(const QList< QSslError > &errorsToIgnore) override
QSslCipher dtlsSessionCipher() const override
bool startHandshake(QUdpSocket *socket, const QByteArray &datagram) override
QDtlsPrivateOpenSSL(QDtls *qObject, QSslSocket::SslMode mode)
bool resumeHandshake(QUdpSocket *socket) override
unsigned pskServerCallback(const char *identity, unsigned char *psk, unsigned max_psk_len)
bool handleTimeout(QUdpSocket *socket) override
virtual void setDtlsMtuHint(quint16 mtu) override
quint16 peerPort() const override
qint64 writeDatagramEncrypted(QUdpSocket *socket, const QByteArray &datagram) override
void sendShutdownAlert(QUdpSocket *socket) override
unsigned pskClientCallback(const char *hint, char *identity, unsigned max_identity_len, unsigned char *psk, unsigned max_psk_len)
void setPeer(const QHostAddress &addr, quint16 port, const QString &name) override
QByteArray decryptDatagram(QUdpSocket *socket, const QByteArray &tlsdgram) override
QSsl::SslProtocol dtlsSessionProtocol() const override
virtual bool isConnectionEncrypted() const override
bool continueHandshake(QUdpSocket *socket, const QByteArray &datagram) override
QList< QSslError > peerVerificationErrors() const override
void setPeerVerificationName(const QString &name) override
virtual quint16 dtlsMtuHint() const override
QString peerVerificationName() const override
static QString getErrorsFromOpenSsl()
static QSslErrorEntry errorEntryFromStoreContext(X509_STORE_CTX *ctx)
bool init(QDtlsBasePrivate *dtlsBase, QUdpSocket *socket, const QHostAddress &remote, quint16 port, const QByteArray &receivedMessage)
QDtlsPrivateOpenSSL * dtlsPrivate
Namespace containing onternal types that TLS backends implement.
int q_dgram_create(BIO *bio)
int q_dgram_read(BIO *bio, char *dst, int bytesToRead)
int q_dgram_write(BIO *bio, const char *src, int bytesToWrite)
int q_dgram_puts(BIO *bio, const char *src)
long q_dgram_ctrl(BIO *bio, int cmd, long num, void *ptr)
int q_dgram_destroy(BIO *bio)
const char *const qdtlsMethodName
unsigned q_PSK_client_callback(SSL *ssl, const char *hint, char *identity, unsigned max_identity_len, unsigned char *psk, unsigned max_psk_len)
unsigned q_PSK_server_callback(SSL *ssl, const char *identity, unsigned char *psk, unsigned max_psk_len)
int q_X509DtlsCallback(int ok, X509_STORE_CTX *ctx)
int q_generate_cookie_callback(SSL *ssl, unsigned char *dst, unsigned *cookieLength)
int q_verify_cookie_callback(SSL *ssl, const unsigned char *cookie, unsigned cookieLength)
static QString msgFunctionFailed(const char *function)
void delete_connection(SSL *ssl)
void delete_bio_method(BIO_METHOD *method)
QByteArray cookie_for_peer(SSL *ssl)
QByteArray fallbackSecret()
int next_timeoutMs(SSL *tlsConnection)
void delete_BIO_ADDR(BIO_ADDR *bio)
#define QT_DTLS_VERBOSE
#define qDtlsWarning(arg)
#define qDtlsDebug(arg)
void q_SSL_free(SSL *a)
int q_SSL_get_ex_data_X509_STORE_CTX_idx()
unsigned long q_ERR_get_error()
void * q_X509_STORE_CTX_get_ex_data(X509_STORE_CTX *ctx, int idx)
#define q_BIO_get_app_data(s)
#define q_BIO_set_retry_read(b)
void q_BIO_set_init(BIO *a, int init)
BIO * q_BIO_new(const BIO_METHOD *a)
#define q_BIO_set_retry_write(b)
void * q_SSL_get_ex_data(const SSL *ssl, int idx)
#define q_BIO_set_app_data(s, arg)
BIO * q_SSL_get_rbio(const SSL *s)
void q_X509_free(X509 *a)
#define q_BIO_clear_retry_flags(b)