-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtls_cert.h
More file actions
451 lines (388 loc) · 15.1 KB
/
Copy pathtls_cert.h
File metadata and controls
451 lines (388 loc) · 15.1 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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
#pragma once
#include <atomic>
#include <condition_variable>
#include <cstdio>
#include <cstring>
#include <mutex>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#ifdef __APPLE__
# include <mach-o/dyld.h>
#endif
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/rand.h>
#include <openssl/err.h>
namespace prodigy_tls {
static inline std::string get_exe_dir() {
#ifdef __APPLE__
char path[4096];
uint32_t size = sizeof(path);
if (_NSGetExecutablePath(path, &size) == 0) {
char* last_slash = strrchr(path, '/');
if (last_slash) { *last_slash = '\0'; return std::string(path); }
}
#endif
return ".";
}
static inline std::string tls_dir() {
return get_exe_dir() + "/tls";
}
static inline std::string cert_file_path() {
return tls_dir() + "/server.crt";
}
static inline bool file_exists(const std::string& path) {
struct stat st;
return stat(path.c_str(), &st) == 0;
}
static inline bool read_file(const std::string& path, std::string& out) {
std::ifstream f(path);
if (!f.is_open()) return false;
std::ostringstream ss;
ss << f.rdbuf();
out = ss.str();
return !out.empty();
}
static inline bool generate_self_signed_cert_impl(const std::string& cert_path,
const std::string& key_path,
long validity_seconds) {
EVP_PKEY* pkey = EVP_PKEY_new();
if (!pkey) return false;
EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, nullptr);
if (!ctx) { EVP_PKEY_free(pkey); return false; }
if (EVP_PKEY_keygen_init(ctx) <= 0 ||
EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx, NID_X9_62_prime256v1) <= 0 ||
EVP_PKEY_keygen(ctx, &pkey) <= 0) {
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_free(pkey);
return false;
}
EVP_PKEY_CTX_free(ctx);
X509* x509 = X509_new();
if (!x509) { EVP_PKEY_free(pkey); return false; }
ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
X509_gmtime_adj(X509_get_notBefore(x509), 0);
X509_gmtime_adj(X509_get_notAfter(x509), validity_seconds);
X509_set_pubkey(x509, pkey);
X509_NAME* name = X509_get_subject_name(x509);
X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
(const unsigned char*)"Prodigy Local Service", -1, -1, 0);
X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC,
(const unsigned char*)"Prodigy", -1, -1, 0);
X509_set_issuer_name(x509, name);
X509V3_CTX v3ctx;
X509V3_set_ctx_nodb(&v3ctx);
X509V3_set_ctx(&v3ctx, x509, x509, nullptr, nullptr, 0);
X509_EXTENSION* san_ext = X509V3_EXT_conf_nid(nullptr, &v3ctx, NID_subject_alt_name,
const_cast<char*>("DNS:localhost,IP:127.0.0.1"));
if (san_ext) {
X509_add_ext(x509, san_ext, -1);
X509_EXTENSION_free(san_ext);
}
X509_sign(x509, pkey, EVP_sha256());
FILE* f_key = fopen(key_path.c_str(), "w");
if (!f_key) { X509_free(x509); EVP_PKEY_free(pkey); return false; }
PEM_write_PrivateKey(f_key, pkey, nullptr, nullptr, 0, nullptr, nullptr);
fclose(f_key);
chmod(key_path.c_str(), 0600);
FILE* f_cert = fopen(cert_path.c_str(), "w");
if (!f_cert) { X509_free(x509); EVP_PKEY_free(pkey); return false; }
PEM_write_X509(f_cert, x509);
fclose(f_cert);
X509_free(x509);
EVP_PKEY_free(pkey);
std::fprintf(stderr, "[tls_cert] Generated self-signed TLS certificate: %s\n",
cert_path.c_str());
return true;
}
static inline bool generate_self_signed_cert(const std::string& cert_path,
const std::string& key_path) {
return generate_self_signed_cert_impl(cert_path, key_path, 365L * 24 * 60 * 60 * 10);
}
static inline bool generate_self_signed_cert_90d(const std::string& cert_path,
const std::string& key_path) {
return generate_self_signed_cert_impl(cert_path, key_path, 90L * 24 * 60 * 60);
}
static inline time_t get_cert_expiry(const std::string& cert_path) {
FILE* f = fopen(cert_path.c_str(), "r");
if (!f) return 0;
X509* x509 = PEM_read_X509(f, nullptr, nullptr, nullptr);
fclose(f);
if (!x509) return 0;
const ASN1_TIME* not_after = X509_get0_notAfter(x509);
struct tm tm_val{};
int ret = ASN1_TIME_to_tm(not_after, &tm_val);
X509_free(x509);
if (ret != 1) return 0;
return timegm(&tm_val);
}
static inline bool validate_pem_cert(const std::string& pem) {
BIO* bio = BIO_new_mem_buf(pem.data(), (int)pem.size());
if (!bio) return false;
X509* x = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
BIO_free(bio);
if (!x) return false;
X509_free(x);
return true;
}
static inline bool validate_pem_key(const std::string& pem) {
BIO* bio = BIO_new_mem_buf(pem.data(), (int)pem.size());
if (!bio) return false;
EVP_PKEY* k = PEM_read_bio_PrivateKey(bio, nullptr, nullptr, nullptr);
BIO_free(bio);
if (!k) return false;
EVP_PKEY_free(k);
return true;
}
static inline std::vector<std::string> list_certs_in_dir(const std::string& dir) {
std::vector<std::string> result;
DIR* d = opendir(dir.c_str());
if (!d) return result;
struct dirent* entry;
while ((entry = readdir(d)) != nullptr) {
std::string name = entry->d_name;
if (name.size() > 4 && name.substr(name.size() - 4) == ".crt") {
result.push_back(name);
}
}
closedir(d);
std::sort(result.begin(), result.end());
return result;
}
struct CertData {
std::string cert_pem;
std::string key_pem;
};
static std::mutex g_cert_mutex;
static std::condition_variable g_cert_cv;
static CertData g_cert_data;
static bool g_cert_loaded = false;
static bool g_cert_generating = false;
static inline bool reload_certs(const std::string& cert_path, const std::string& key_path) {
CertData tmp;
if (!read_file(cert_path, tmp.cert_pem) || !read_file(key_path, tmp.key_pem)) {
std::fprintf(stderr, "[tls_cert] Cannot read cert/key: %s / %s\n",
cert_path.c_str(), key_path.c_str());
return false;
}
std::lock_guard<std::mutex> lk(g_cert_mutex);
g_cert_data = std::move(tmp);
g_cert_loaded = true;
std::fprintf(stderr, "[tls_cert] Loaded TLS certificate from %s\n", cert_path.c_str());
return true;
}
static inline const CertData& ensure_certs() {
std::unique_lock<std::mutex> lk(g_cert_mutex);
g_cert_cv.wait(lk, []{ return g_cert_loaded || !g_cert_generating; });
if (g_cert_loaded) return g_cert_data;
g_cert_generating = true;
lk.unlock();
std::string dir = tls_dir();
mkdir(dir.c_str(), 0700);
std::string cert_path = dir + "/server.crt";
std::string key_path = dir + "/server.key";
bool ok = true;
if (!file_exists(cert_path) || !file_exists(key_path)) {
if (!generate_self_signed_cert_90d(cert_path, key_path)) {
std::fprintf(stderr, "[tls_cert] FATAL: cannot generate TLS certificate\n");
ok = false;
}
}
if (ok) reload_certs(cert_path, key_path);
lk.lock();
g_cert_generating = false;
lk.unlock();
g_cert_cv.notify_all();
lk.lock();
return g_cert_data;
}
static inline CertData get_certs() {
std::unique_lock<std::mutex> lk(g_cert_mutex);
if (g_cert_loaded) return g_cert_data;
lk.unlock();
ensure_certs();
lk.lock();
return g_cert_data;
}
static std::string g_ic_key;
static std::once_flag g_ic_key_once;
static inline std::string ic_encryption_flag_path() {
return get_exe_dir() + "/ic_encryption.flag";
}
// Interconnect traffic encryption is OPT-IN. Default is OFF (plaintext
// framing) — especially for debug purposes on a fresh install. Operators
// enable it via the TLS Certificates tab in the web frontend, which
// writes "1" to ic_encryption.flag; disabling deletes the file or
// writes "0". Services read the flag once on startup (call_once),
// so a change requires restarting every pipeline service for the new
// setting to take effect.
static std::atomic<int> g_ic_encryption_enabled{-1};
static std::once_flag g_ic_encryption_once;
static inline bool ic_encryption_enabled() {
std::call_once(g_ic_encryption_once, []() {
std::string path = ic_encryption_flag_path();
FILE* f = fopen(path.c_str(), "rb");
int enabled = 0;
if (f) {
char buf[4] = {0};
size_t n = fread(buf, 1, sizeof(buf) - 1, f);
fclose(f);
if (n > 0 && buf[0] == '1') enabled = 1;
}
g_ic_encryption_enabled.store(enabled, std::memory_order_release);
if (enabled) {
std::fprintf(stderr, "[ic_key] Interconnect traffic encryption: ENABLED (AES-256-GCM)\n");
} else {
std::fprintf(stderr,
"[ic_key] *** WARNING *** Interconnect traffic encryption is DISABLED (plaintext framing).\n"
"[ic_key] *** WARNING *** Enable it in the web frontend (TLS Certificates tab) and restart all pipeline services for production deployments.\n");
}
});
return g_ic_encryption_enabled.load(std::memory_order_acquire) == 1;
}
static inline bool ic_encryption_set_persistent(bool enabled) {
std::string path = ic_encryption_flag_path();
int fd = open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600);
if (fd < 0) return false;
const char* v = enabled ? "1" : "0";
ssize_t n = write(fd, v, 1);
close(fd);
return n == 1;
}
static inline void secure_zero_tls(void* ptr, std::size_t len) noexcept {
volatile unsigned char* p = static_cast<volatile unsigned char*>(ptr);
while (len--) *p++ = 0;
}
static inline std::string ic_key_file_path() {
return get_exe_dir() + "/ic_key.bin";
}
static inline std::string ic_file_load() {
std::string path = ic_key_file_path();
FILE* f = fopen(path.c_str(), "rb");
if (!f) return {};
char buf[32];
size_t n = fread(buf, 1, sizeof(buf), f);
fclose(f);
if (n != 32) return {};
std::string key(buf, 32);
secure_zero_tls(buf, sizeof(buf));
return key;
}
// Atomically create the key file with mode 0600 via O_EXCL so two racing
// processes cannot both write different keys; the loser sees EEXIST and
// falls back to reading the winner's key from disk. Permissions are set
// at creation time (no fopen→chmod TOCTOU window).
static inline bool ic_file_store(const std::string& key) {
if (key.size() != 32) return false;
std::string path = ic_key_file_path();
int fd = open(path.c_str(), O_WRONLY | O_CREAT | O_EXCL, 0600);
if (fd < 0) return false;
ssize_t written = 0;
const char* buf = key.data();
while (written < 32) {
ssize_t n = write(fd, buf + written, 32 - written);
if (n <= 0) { close(fd); unlink(path.c_str()); return false; }
written += n;
}
close(fd);
return true;
}
static inline const std::string& get_interconnect_key() {
std::call_once(g_ic_key_once, []() {
g_ic_key = ic_file_load();
if (!g_ic_key.empty() && g_ic_key.size() == 32) {
std::fprintf(stderr, "[ic_key] Loaded interconnect AES-256 key from key file\n");
return;
}
unsigned char raw[32];
#ifdef __APPLE__
arc4random_buf(raw, sizeof(raw));
#else
if (RAND_bytes(raw, sizeof(raw)) != 1) {
std::fprintf(stderr, "[ic_key] FATAL: RAND_bytes failed for interconnect key\n");
}
#endif
g_ic_key.assign(reinterpret_cast<char*>(raw), 32);
secure_zero_tls(raw, sizeof(raw));
if (ic_file_store(g_ic_key)) {
std::fprintf(stderr, "[ic_key] Generated new interconnect AES-256 key and stored in key file\n");
} else {
g_ic_key = ic_file_load();
if (!g_ic_key.empty() && g_ic_key.size() == 32) {
std::fprintf(stderr, "[ic_key] Race detected — loaded winner's key from key file\n");
} else {
std::fprintf(stderr, "[ic_key] Warning: interconnect key file storage failed\n");
}
}
});
return g_ic_key;
}
static constexpr int IC_GCM_IV_LEN = 12;
static constexpr int IC_GCM_TAG_LEN = 16;
static inline bool ic_encrypt(const uint8_t* plaintext, size_t plain_len,
uint8_t* ciphertext, size_t& cipher_len) {
const std::string& key = get_interconnect_key();
if (key.size() != 32) return false;
uint8_t iv[IC_GCM_IV_LEN];
if (RAND_bytes(iv, IC_GCM_IV_LEN) != 1) return false;
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
if (!ctx) return false;
int len = 0;
bool ok = true;
ok = ok && (EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), nullptr, nullptr, nullptr) == 1);
ok = ok && (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, IC_GCM_IV_LEN, nullptr) == 1);
ok = ok && (EVP_EncryptInit_ex(ctx, nullptr, nullptr,
reinterpret_cast<const unsigned char*>(key.data()), iv) == 1);
ok = ok && (EVP_EncryptUpdate(ctx, ciphertext + IC_GCM_IV_LEN,
&len, plaintext, static_cast<int>(plain_len)) == 1);
int clen = len;
ok = ok && (EVP_EncryptFinal_ex(ctx, ciphertext + IC_GCM_IV_LEN + clen, &len) == 1);
clen += len;
ok = ok && (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, IC_GCM_TAG_LEN,
ciphertext + IC_GCM_IV_LEN + clen) == 1);
memcpy(ciphertext, iv, IC_GCM_IV_LEN);
cipher_len = IC_GCM_IV_LEN + clen + IC_GCM_TAG_LEN;
EVP_CIPHER_CTX_free(ctx);
return ok;
}
static inline bool ic_decrypt(const uint8_t* ciphertext, size_t cipher_len,
uint8_t* plaintext, size_t& plain_len) {
const std::string& key = get_interconnect_key();
if (key.size() != 32) return false;
if (cipher_len < (size_t)(IC_GCM_IV_LEN + IC_GCM_TAG_LEN)) return false;
const uint8_t* iv = ciphertext;
size_t enc_len = cipher_len - IC_GCM_IV_LEN - IC_GCM_TAG_LEN;
const uint8_t* enc_data = ciphertext + IC_GCM_IV_LEN;
const uint8_t* tag = ciphertext + IC_GCM_IV_LEN + enc_len;
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
if (!ctx) return false;
int len = 0;
bool ok = true;
ok = ok && (EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), nullptr, nullptr, nullptr) == 1);
ok = ok && (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, IC_GCM_IV_LEN, nullptr) == 1);
ok = ok && (EVP_DecryptInit_ex(ctx, nullptr, nullptr,
reinterpret_cast<const unsigned char*>(key.data()), iv) == 1);
ok = ok && (EVP_DecryptUpdate(ctx, plaintext, &len,
enc_data, static_cast<int>(enc_len)) == 1);
int plen = len;
ok = ok && (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, IC_GCM_TAG_LEN,
const_cast<uint8_t*>(tag)) == 1);
ok = ok && (EVP_DecryptFinal_ex(ctx, plaintext + plen, &len) == 1);
plen += len;
plain_len = static_cast<size_t>(plen);
EVP_CIPHER_CTX_free(ctx);
return ok;
}
static inline size_t ic_encrypted_size(size_t plain_len) {
return IC_GCM_IV_LEN + plain_len + IC_GCM_TAG_LEN;
}
}