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