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