forked from actor-framework/actor-framework
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsession.cpp
More file actions
376 lines (343 loc) · 12.6 KB
/
session.cpp
File metadata and controls
376 lines (343 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#include "caf/openssl/session.hpp"
#include <optional>
#include <openssl/decoder.h>
CAF_PUSH_WARNINGS
#include <openssl/err.h>
CAF_POP_WARNINGS
#include "caf/actor_system_config.hpp"
#include "caf/io/network/default_multiplexer.hpp"
#include "caf/openssl/manager.hpp"
// On Linux we need to block SIGPIPE whenever we access OpenSSL functions.
// Unfortunately there's no sane way to configure OpenSSL properly.
#ifdef CAF_LINUX
# include "caf/detail/scope_guard.hpp"
# include <signal.h>
# define CAF_BLOCK_SIGPIPE() \
sigset_t sigpipe_mask; \
sigemptyset(&sigpipe_mask); \
sigaddset(&sigpipe_mask, SIGPIPE); \
sigset_t saved_mask; \
if (pthread_sigmask(SIG_BLOCK, &sigpipe_mask, &saved_mask) == -1) { \
perror("pthread_sigmask"); \
exit(1); \
} \
auto sigpipe_restore_guard = ::caf::detail::make_scope_guard([&] { \
struct timespec zerotime = {}; \
sigtimedwait(&sigpipe_mask, 0, &zerotime); \
if (pthread_sigmask(SIG_SETMASK, &saved_mask, 0) == -1) { \
perror("pthread_sigmask"); \
exit(1); \
} \
})
#else
# define CAF_BLOCK_SIGPIPE() static_cast<void>(0)
#endif // CAF_LINUX
namespace caf::openssl {
namespace {
int pem_passwd_cb(char* buf, int size, int, void* ptr) {
auto passphrase = reinterpret_cast<session*>(ptr)->openssl_passphrase();
strncpy(buf, passphrase, static_cast<size_t>(size));
buf[size - 1] = '\0';
return static_cast<int>(strlen(buf));
}
// If the input is a string like `env:SOME_VARIABLE` and the environment variable
// `SOME_VARIABLE` exists, returns a string with the value of `SOME_VARIABLE`.
// Otherwise, returns `std::nullopt`.
std::optional<std::string> contents_from_indirect_envvar(const std::string& str) {
if (str.find("env:") != 0)
return std::nullopt;
auto var = str.substr(4);
auto const* contents = ::getenv(var.c_str());
if (contents == nullptr)
return std::nullopt;
return std::string{contents};
}
// If the input is a string like `env:SOME_VARIABLE` and the environment variable
// `SOME_VARIABLE` exists, returns a string with the value of `SOME_VARIABLE`.
std::optional<std::string> tmpfile_from_indirect_envvar(const std::string& str) {
auto contents = contents_from_indirect_envvar(str);
if (!contents)
return contents;
auto filename = std::string{"/tmp/caf-openssl.XXXXXX"};
::mkstemp(&filename[0]);
std::ofstream ofs(filename);
ofs << *contents;
ofs.close();
return filename;
}
} // namespace
session::session(actor_system& sys)
: sys_(sys),
ctx_(nullptr),
ssl_(nullptr),
connecting_(false),
accepting_(false) {
// nop
}
bool session::init() {
CAF_LOG_TRACE("");
ctx_ = create_ssl_context();
ssl_ = SSL_new(ctx_);
if (ssl_ == nullptr) {
CAF_LOG_ERROR("cannot create SSL session");
return false;
}
return true;
}
session::~session() {
SSL_free(ssl_);
SSL_CTX_free(ctx_);
}
rw_state session::do_some(int (*f)(SSL*, void*, int), size_t& result, void* buf,
size_t len, const char* debug_name) {
CAF_BLOCK_SIGPIPE();
auto check_ssl_res = [&](int res) -> rw_state {
result = 0;
switch (SSL_get_error(ssl_, res)) {
default:
CAF_LOG_INFO("SSL error:" << get_ssl_error());
return rw_state::failure;
case SSL_ERROR_WANT_READ:
CAF_LOG_DEBUG("SSL_ERROR_WANT_READ reported");
return rw_state::want_read;
case SSL_ERROR_WANT_WRITE:
CAF_LOG_DEBUG("SSL_ERROR_WANT_WRITE reported");
// Report success to poll on this socket.
return rw_state::success;
}
};
CAF_LOG_TRACE(CAF_ARG(len) << CAF_ARG(debug_name));
CAF_IGNORE_UNUSED(debug_name);
if (connecting_) {
CAF_LOG_DEBUG(debug_name << ": connecting");
auto res = SSL_connect(ssl_);
if (res == 1) {
CAF_LOG_DEBUG("SSL connection established");
connecting_ = false;
} else {
result = 0;
return check_ssl_res(res);
}
}
if (accepting_) {
CAF_LOG_DEBUG(debug_name << ": accepting");
auto res = SSL_accept(ssl_);
if (res == 1) {
CAF_LOG_DEBUG("SSL connection accepted");
accepting_ = false;
} else {
result = 0;
return check_ssl_res(res);
}
}
CAF_LOG_DEBUG(debug_name << ": calling SSL_write or SSL_read");
if (len == 0) {
result = 0;
return rw_state::indeterminate;
}
auto ret = f(ssl_, buf, static_cast<int>(len));
if (ret > 0) {
result = static_cast<size_t>(ret);
return rw_state::success;
}
result = 0;
return handle_ssl_result(ret) ? rw_state::success : rw_state::failure;
}
rw_state session::read_some(size_t& result, native_socket, void* buf,
size_t len) {
CAF_LOG_TRACE(CAF_ARG(len));
return do_some(SSL_read, result, buf, len, "read_some");
}
rw_state session::write_some(size_t& result, native_socket, const void* buf,
size_t len) {
CAF_LOG_TRACE(CAF_ARG(len));
auto wr_fun = [](SSL* sptr, void* vptr, int ptr_size) {
return SSL_write(sptr, vptr, ptr_size);
};
return do_some(wr_fun, result, const_cast<void*>(buf), len, "write_some");
}
bool session::try_connect(native_socket fd, const std::string& sni_servername) {
CAF_LOG_TRACE(CAF_ARG(fd));
CAF_BLOCK_SIGPIPE();
SSL_set_fd(ssl_, fd);
SSL_set_connect_state(ssl_);
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
// FIXME: Re-enable this.
// Enable hostname validation.
// SSL_set_hostflags(ssl_, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
// if (SSL_set1_host(ssl_, sni_servername.c_str()) != 1)
// return false;
#endif
// Send SNI when connecting.
SSL_set_tlsext_host_name(ssl_, sni_servername.c_str());
auto ret = SSL_connect(ssl_);
if (ret == 1)
return true;
connecting_ = true;
return handle_ssl_result(ret);
}
bool session::try_accept(native_socket fd) {
CAF_LOG_TRACE(CAF_ARG(fd));
CAF_BLOCK_SIGPIPE();
SSL_set_fd(ssl_, fd);
SSL_set_accept_state(ssl_);
auto ret = SSL_accept(ssl_);
if (ret == 1)
return true;
accepting_ = true;
return handle_ssl_result(ret);
}
bool session::must_read_more(native_socket, size_t threshold) {
return static_cast<size_t>(SSL_pending(ssl_)) >= threshold;
}
const char* session::openssl_passphrase() {
return openssl_passphrase_.c_str();
}
SSL_CTX* session::create_ssl_context() {
CAF_BLOCK_SIGPIPE();
#ifdef CAF_SSL_HAS_NON_VERSIONED_TLS_FUN
auto ctx = SSL_CTX_new(TLS_method());
#else
auto ctx = SSL_CTX_new(TLSv1_2_method());
#endif
if (!ctx)
CAF_RAISE_ERROR("cannot create OpenSSL context");
if (sys_.openssl_manager().authentication_enabled()) {
// Require valid certificates on both sides.
auto& cfg = sys_.config();
// OpenSSL doesn't expose an API to read a certificate chain PEM from
// memory (as far as I can tell, there might be something in OSSL_DECODER)
// and the implementation of `SSL_CTX_use_certificate_chain_file`
// is huge, so we just write into a temporary file.
if (auto filename = tmpfile_from_indirect_envvar(cfg.openssl_certificate)) {
if (SSL_CTX_use_certificate_chain_file(ctx, filename->c_str())
!= 1)
CAF_RAISE_ERROR("cannot load certificate from environt variable");
} else if (!cfg.openssl_certificate.empty()
&& SSL_CTX_use_certificate_chain_file(ctx,
cfg.openssl_certificate.c_str())
!= 1) {
CAF_RAISE_ERROR("cannot load certificate");
}
if (!cfg.openssl_passphrase.empty()) {
openssl_passphrase_ = cfg.openssl_passphrase;
SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
SSL_CTX_set_default_passwd_cb_userdata(ctx, this);
}
if (auto var = contents_from_indirect_envvar(cfg.openssl_key)) {
EVP_PKEY *pkey = nullptr;
const char *format = "PEM"; // NULL for any format
const char *structure = nullptr; // Any structure
const char *keytype = nullptr; // Any key
auto const* datap = reinterpret_cast<const unsigned char*>(var->data());
auto len = var->size();
int selection = 0; // Autodetect selection.
// TODO: We might as well read `openssl_passphrase` here and pass it
// to the decoder.
auto* dctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, format, structure,
keytype,
selection,
nullptr, nullptr);
if (dctx == nullptr)
CAF_RAISE_ERROR("couldn't create openssl decoder context");
if (OSSL_DECODER_from_data(dctx, &datap, &len) != 0)
CAF_RAISE_ERROR("failed to decode private key");
// Use the private key.
SSL_CTX_use_PrivateKey(ctx, pkey);
OSSL_DECODER_CTX_free(dctx);
}
if (!cfg.openssl_key.empty()
&& SSL_CTX_use_PrivateKey_file(ctx, cfg.openssl_key.c_str(),
SSL_FILETYPE_PEM)
!= 1)
CAF_RAISE_ERROR("cannot load private key");
auto cafile = (!cfg.openssl_cafile.empty() ? cfg.openssl_cafile.c_str()
: nullptr);
auto capath = (!cfg.openssl_capath.empty() ? cfg.openssl_capath.c_str()
: nullptr);
auto tmpfile = tmpfile_from_indirect_envvar(cafile);
if (tmpfile)
cafile = tmpfile->c_str();
if (cafile || capath) {
if (SSL_CTX_load_verify_locations(ctx, cafile, capath) != 1)
CAF_RAISE_ERROR("cannot load trusted CA certificates");
}
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
nullptr);
if (SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!MD5") != 1)
CAF_RAISE_ERROR("cannot set cipher list");
} else {
// No authentication.
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, nullptr);
#if defined(CAF_SSL_HAS_ECDH_AUTO) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
SSL_CTX_set_ecdh_auto(ctx, 1);
#else
# if OPENSSL_VERSION_NUMBER < 0x10101000L
auto ecdh = EC_KEY_new_by_curve_name(NID_secp384r1);
if (!ecdh)
CAF_RAISE_ERROR("cannot get ECDH curve");
CAF_PUSH_WARNINGS
SSL_CTX_set_tmp_ecdh(ctx, ecdh);
EC_KEY_free(ecdh);
CAF_POP_WARNINGS
# else /* OPENSSL_VERSION_NUMBER < 0x10101000L */
SSL_CTX_set1_groups_list(ctx, "P-384");
# endif /* OPENSSL_VERSION_NUMBER < 0x10101000L */
#endif
#ifdef CAF_SSL_HAS_SECURITY_LEVEL
const char* cipher = "AECDH-AES256-SHA@SECLEVEL=0";
#else
const char* cipher = "AECDH-AES256-SHA";
#endif
if (SSL_CTX_set_cipher_list(ctx, cipher) != 1)
CAF_RAISE_ERROR("cannot set anonymous cipher");
}
return ctx;
}
std::string session::get_ssl_error() {
std::string msg = "";
while (auto err = ERR_get_error()) {
if (!msg.empty())
msg += " ";
char buf[256];
ERR_error_string_n(err, buf, sizeof(buf));
msg += buf;
}
return msg;
}
bool session::handle_ssl_result(int ret) {
auto err = SSL_get_error(ssl_, ret);
switch (err) {
case SSL_ERROR_WANT_READ:
CAF_LOG_DEBUG("Nonblocking call to SSL returned want_read");
return true;
case SSL_ERROR_WANT_WRITE:
CAF_LOG_DEBUG("Nonblocking call to SSL returned want_write");
return true;
case SSL_ERROR_ZERO_RETURN: // Regular remote connection shutdown.
case SSL_ERROR_SYSCALL: // Socket connection closed.
return false;
default: // Other error
CAF_LOG_INFO("SSL call failed:" << get_ssl_error());
return false;
}
}
session_ptr make_session(actor_system& sys, native_socket fd,
const std::string& servername,
bool from_accepted_socket) {
session_ptr ptr{new session(sys)};
if (!ptr->init())
return nullptr;
if (from_accepted_socket) {
if (!ptr->try_accept(fd))
return nullptr;
} else {
if (!ptr->try_connect(fd, servername))
return nullptr;
}
return ptr;
}
} // namespace caf::openssl