]> granicus.if.org Git - icinga2/blob - lib/base/tlsstream.cpp
Merge pull request #6148 from gunnarbeutner/fix/api-unit-test
[icinga2] / lib / base / tlsstream.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012-2018 Icinga Development Team (https://www.icinga.com/)  *
4  *                                                                            *
5  * This program is free software; you can redistribute it and/or              *
6  * modify it under the terms of the GNU General Public License                *
7  * as published by the Free Software Foundation; either version 2             *
8  * of the License, or (at your option) any later version.                     *
9  *                                                                            *
10  * This program is distributed in the hope that it will be useful,            *
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of             *
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              *
13  * GNU General Public License for more details.                               *
14  *                                                                            *
15  * You should have received a copy of the GNU General Public License          *
16  * along with this program; if not, write to the Free Software Foundation     *
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.             *
18  ******************************************************************************/
19
20 #include "base/tlsstream.hpp"
21 #include "base/utility.hpp"
22 #include "base/exception.hpp"
23 #include "base/logger.hpp"
24 #include <iostream>
25
26 #ifndef _WIN32
27 #       include <poll.h>
28 #endif /* _WIN32 */
29
30 #define TLS_TIMEOUT_SECONDS 10
31
32 using namespace icinga;
33
34 int TlsStream::m_SSLIndex;
35 bool TlsStream::m_SSLIndexInitialized = false;
36
37 /**
38  * Constructor for the TlsStream class.
39  *
40  * @param role The role of the client.
41  * @param sslContext The SSL context for the client.
42  */
43 TlsStream::TlsStream(const Socket::Ptr& socket, const String& hostname, ConnectionRole role, const std::shared_ptr<SSL_CTX>& sslContext)
44         : SocketEvents(socket, this), m_Eof(false), m_HandshakeOK(false), m_VerifyOK(true), m_ErrorCode(0),
45         m_ErrorOccurred(false),  m_Socket(socket), m_Role(role), m_SendQ(new FIFO()), m_RecvQ(new FIFO()),
46         m_CurrentAction(TlsActionNone), m_Retry(false), m_Shutdown(false)
47 {
48         std::ostringstream msgbuf;
49         char errbuf[120];
50
51         m_SSL = std::shared_ptr<SSL>(SSL_new(sslContext.get()), SSL_free);
52
53         if (!m_SSL) {
54                 msgbuf << "SSL_new() failed with code " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
55                 Log(LogCritical, "TlsStream", msgbuf.str());
56
57                 BOOST_THROW_EXCEPTION(openssl_error()
58                         << boost::errinfo_api_function("SSL_new")
59                         << errinfo_openssl_error(ERR_peek_error()));
60         }
61
62         if (!m_SSLIndexInitialized) {
63                 m_SSLIndex = SSL_get_ex_new_index(0, const_cast<char *>("TlsStream"), nullptr, nullptr, nullptr);
64                 m_SSLIndexInitialized = true;
65         }
66
67         SSL_set_ex_data(m_SSL.get(), m_SSLIndex, this);
68
69         SSL_set_verify(m_SSL.get(), SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, &TlsStream::ValidateCertificate);
70
71         socket->MakeNonBlocking();
72
73         SSL_set_fd(m_SSL.get(), socket->GetFD());
74
75         if (m_Role == RoleServer)
76                 SSL_set_accept_state(m_SSL.get());
77         else {
78 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
79                 if (!hostname.IsEmpty())
80                         SSL_set_tlsext_host_name(m_SSL.get(), hostname.CStr());
81 #endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
82
83                 SSL_set_connect_state(m_SSL.get());
84         }
85 }
86
87 TlsStream::~TlsStream()
88 {
89         CloseInternal(true);
90 }
91
92 int TlsStream::ValidateCertificate(int preverify_ok, X509_STORE_CTX *ctx)
93 {
94         auto *ssl = static_cast<SSL *>(X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
95         auto *stream = static_cast<TlsStream *>(SSL_get_ex_data(ssl, m_SSLIndex));
96
97         if (!preverify_ok) {
98                 stream->m_VerifyOK = false;
99
100                 std::ostringstream msgbuf;
101                 int err = X509_STORE_CTX_get_error(ctx);
102                 msgbuf << "code " << err << ": " << X509_verify_cert_error_string(err);
103                 stream->m_VerifyError = msgbuf.str();
104         }
105
106         return 1;
107 }
108
109 bool TlsStream::IsVerifyOK() const
110 {
111         return m_VerifyOK;
112 }
113
114 String TlsStream::GetVerifyError() const
115 {
116         return m_VerifyError;
117 }
118
119 /**
120  * Retrieves the X509 certficate for this client.
121  *
122  * @returns The X509 certificate.
123  */
124 std::shared_ptr<X509> TlsStream::GetClientCertificate() const
125 {
126         boost::mutex::scoped_lock lock(m_Mutex);
127         return std::shared_ptr<X509>(SSL_get_certificate(m_SSL.get()), &Utility::NullDeleter);
128 }
129
130 /**
131  * Retrieves the X509 certficate for the peer.
132  *
133  * @returns The X509 certificate.
134  */
135 std::shared_ptr<X509> TlsStream::GetPeerCertificate() const
136 {
137         boost::mutex::scoped_lock lock(m_Mutex);
138         return std::shared_ptr<X509>(SSL_get_peer_certificate(m_SSL.get()), X509_free);
139 }
140
141 void TlsStream::OnEvent(int revents)
142 {
143         int rc;
144         size_t count;
145
146         boost::mutex::scoped_lock lock(m_Mutex);
147
148         if (!m_SSL)
149                 return;
150
151         char buffer[64 * 1024];
152
153         if (m_CurrentAction == TlsActionNone) {
154                 bool corked = IsCorked();
155                 if (!corked && (revents & (POLLIN | POLLERR | POLLHUP)))
156                         m_CurrentAction = TlsActionRead;
157                 else if (m_SendQ->GetAvailableBytes() > 0 && (revents & POLLOUT))
158                         m_CurrentAction = TlsActionWrite;
159                 else {
160                         if (corked)
161                                 ChangeEvents(0);
162                         else
163                                 ChangeEvents(POLLIN);
164
165                         return;
166                 }
167         }
168
169         bool success = false;
170
171         /* Clear error queue for this thread before using SSL_{read,write,do_handshake}.
172          * Otherwise SSL_*_error() does not work reliably.
173          */
174         ERR_clear_error();
175
176         size_t readTotal = 0;
177
178         switch (m_CurrentAction) {
179                 case TlsActionRead:
180                         do {
181                                 rc = SSL_read(m_SSL.get(), buffer, sizeof(buffer));
182
183                                 if (rc > 0) {
184                                         m_RecvQ->Write(buffer, rc);
185                                         success = true;
186
187                                         readTotal += rc;
188                                 }
189                         } while (rc > 0 && readTotal < 64 * 1024);
190
191                         if (success)
192                                 m_CV.notify_all();
193
194                         break;
195                 case TlsActionWrite:
196                         count = m_SendQ->Peek(buffer, sizeof(buffer), true);
197
198                         rc = SSL_write(m_SSL.get(), buffer, count);
199
200                         if (rc > 0) {
201                                 m_SendQ->Read(nullptr, rc, true);
202                                 success = true;
203                         }
204
205                         break;
206                 case TlsActionHandshake:
207                         rc = SSL_do_handshake(m_SSL.get());
208
209                         if (rc > 0) {
210                                 success = true;
211                                 m_HandshakeOK = true;
212                                 m_CV.notify_all();
213                         }
214
215                         break;
216                 default:
217                         VERIFY(!"Invalid TlsAction");
218         }
219
220         if (rc <= 0) {
221                 int err = SSL_get_error(m_SSL.get(), rc);
222
223                 switch (err) {
224                         case SSL_ERROR_WANT_READ:
225                                 m_Retry = true;
226                                 ChangeEvents(POLLIN);
227
228                                 break;
229                         case SSL_ERROR_WANT_WRITE:
230                                 m_Retry = true;
231                                 ChangeEvents(POLLOUT);
232
233                                 break;
234                         case SSL_ERROR_ZERO_RETURN:
235                                 lock.unlock();
236
237                                 Close();
238
239                                 return;
240                         default:
241                                 m_ErrorCode = ERR_peek_error();
242                                 m_ErrorOccurred = true;
243
244                                 if (m_ErrorCode != 0) {
245                                         Log(LogWarning, "TlsStream")
246                                                 << "OpenSSL error: " << ERR_error_string(m_ErrorCode, nullptr);
247                                 } else {
248                                         Log(LogWarning, "TlsStream", "TLS stream was disconnected.");
249                                 }
250
251                                 lock.unlock();
252
253                                 Close();
254
255                                 return;
256                 }
257         }
258
259         if (success) {
260                 m_CurrentAction = TlsActionNone;
261
262                 if (!m_Eof) {
263                         if (m_SendQ->GetAvailableBytes() > 0)
264                                 ChangeEvents(POLLIN|POLLOUT);
265                         else
266                                 ChangeEvents(POLLIN);
267                 }
268
269                 lock.unlock();
270
271                 while (!IsCorked() && m_RecvQ->IsDataAvailable() && IsHandlingEvents())
272                         SignalDataAvailable();
273         }
274
275         if (m_Shutdown && !m_SendQ->IsDataAvailable()) {
276                 if (!success)
277                         lock.unlock();
278
279                 Close();
280         }
281 }
282
283 void TlsStream::HandleError() const
284 {
285         if (m_ErrorOccurred) {
286                 BOOST_THROW_EXCEPTION(openssl_error()
287                         << boost::errinfo_api_function("TlsStream::OnEvent")
288                         << errinfo_openssl_error(m_ErrorCode));
289         }
290 }
291
292 void TlsStream::Handshake()
293 {
294         boost::mutex::scoped_lock lock(m_Mutex);
295
296         m_CurrentAction = TlsActionHandshake;
297         ChangeEvents(POLLOUT);
298
299         boost::system_time const timeout = boost::get_system_time() + boost::posix_time::seconds(TLS_TIMEOUT_SECONDS);
300
301         while (!m_HandshakeOK && !m_ErrorOccurred && !m_Eof && timeout > boost::get_system_time())
302                 m_CV.timed_wait(lock, timeout);
303
304         // We should _NOT_ (underline, bold, itallic and wordart) throw an exception for a timeout.
305         if (timeout < boost::get_system_time())
306                 BOOST_THROW_EXCEPTION(std::runtime_error("Timeout during handshake."));
307
308         if (m_Eof)
309                 BOOST_THROW_EXCEPTION(std::runtime_error("Socket was closed during TLS handshake."));
310
311         HandleError();
312 }
313
314 /**
315  * Processes data for the stream.
316  */
317 size_t TlsStream::Peek(void *buffer, size_t count, bool allow_partial)
318 {
319         boost::mutex::scoped_lock lock(m_Mutex);
320
321         if (!allow_partial)
322                 while (m_RecvQ->GetAvailableBytes() < count && !m_ErrorOccurred && !m_Eof)
323                         m_CV.wait(lock);
324
325         HandleError();
326
327         return m_RecvQ->Peek(buffer, count, true);
328 }
329
330 size_t TlsStream::Read(void *buffer, size_t count, bool allow_partial)
331 {
332         boost::mutex::scoped_lock lock(m_Mutex);
333
334         if (!allow_partial)
335                 while (m_RecvQ->GetAvailableBytes() < count && !m_ErrorOccurred && !m_Eof)
336                         m_CV.wait(lock);
337
338         HandleError();
339
340         return m_RecvQ->Read(buffer, count, true);
341 }
342
343 void TlsStream::Write(const void *buffer, size_t count)
344 {
345         boost::mutex::scoped_lock lock(m_Mutex);
346
347         m_SendQ->Write(buffer, count);
348
349         ChangeEvents(POLLIN|POLLOUT);
350 }
351
352 void TlsStream::Shutdown()
353 {
354         m_Shutdown = true;
355         ChangeEvents(POLLOUT);
356 }
357
358 /**
359  * Closes the stream.
360  */
361 void TlsStream::Close()
362 {
363         CloseInternal(false);
364 }
365
366 void TlsStream::CloseInternal(bool inDestructor)
367 {
368         if (m_Eof)
369                 return;
370
371         m_Eof = true;
372
373         if (!inDestructor)
374                 SignalDataAvailable();
375
376         SocketEvents::Unregister();
377
378         Stream::Close();
379
380         boost::mutex::scoped_lock lock(m_Mutex);
381
382         if (!m_SSL)
383                 return;
384
385         (void)SSL_shutdown(m_SSL.get());
386         m_SSL.reset();
387
388         m_Socket->Close();
389         m_Socket.reset();
390
391         m_CV.notify_all();
392 }
393
394 bool TlsStream::IsEof() const
395 {
396         return m_Eof;
397 }
398
399 bool TlsStream::SupportsWaiting() const
400 {
401         return true;
402 }
403
404 bool TlsStream::IsDataAvailable() const
405 {
406         boost::mutex::scoped_lock lock(m_Mutex);
407
408         return m_RecvQ->GetAvailableBytes() > 0;
409 }
410
411 void TlsStream::SetCorked(bool corked)
412 {
413         Stream::SetCorked(corked);
414
415         boost::mutex::scoped_lock lock(m_Mutex);
416
417         if (corked)
418                 m_CurrentAction = TlsActionNone;
419         else
420                 ChangeEvents(POLLIN | POLLOUT);
421 }
422
423 Socket::Ptr TlsStream::GetSocket() const
424 {
425         return m_Socket;
426 }