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