122
132
#define PATHDIR "/conf/conf.d/mandos"
123
133
#define SECKEY "seckey.txt"
124
134
#define PUBKEY "pubkey.txt"
135
#define HOOKDIR "/lib/mandos/network-hooks.d"
126
137
bool debug = false;
127
138
static const char mandos_protocol_version[] = "1";
128
139
const char *argp_program_version = "mandos-client " VERSION;
129
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
140
const char *argp_program_bug_address = "<mandos@recompile.se>";
141
static const char sys_class_net[] = "/sys/class/net";
142
char *connect_to = NULL;
143
const char *hookdir = HOOKDIR;
148
/* Doubly linked list that need to be circularly linked when used */
149
typedef struct server{
152
AvahiIfIndex if_index;
154
struct timespec last_seen;
131
159
/* Used for passing in values through the Avahi callback functions */
133
AvahiSimplePoll *simple_poll;
134
161
AvahiServer *server;
135
162
gnutls_certificate_credentials_t cred;
136
163
unsigned int dh_bits;
137
164
gnutls_dh_params_t dh_params;
138
165
const char *priority;
167
server *current_server;
169
size_t interfaces_size;
140
170
} mandos_context;
142
/* global context so signal handler can reach it*/
143
mandos_context mc = { .simple_poll = NULL, .server = NULL,
144
.dh_bits = 1024, .priority = "SECURE256"
145
":!CTYPE-X.509:+CTYPE-OPENPGP" };
172
/* global so signal handler can reach it*/
173
AvahiSimplePoll *simple_poll;
147
175
sig_atomic_t quit_now = 0;
148
176
int signal_received = 0;
178
/* Function to use when printing errors */
179
void perror_plus(const char *print_text){
181
fprintf(stderr, "Mandos plugin %s: ",
182
program_invocation_short_name);
187
__attribute__((format (gnu_printf, 2, 3), nonnull))
188
int fprintf_plus(FILE *stream, const char *format, ...){
190
va_start (ap, format);
192
TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
193
program_invocation_short_name));
194
return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
151
198
* Make additional room in "buffer" for at least BUFFER_SIZE more
152
199
* bytes. "buffer_capacity" is how much is currently allocated,
153
200
* "buffer_length" is how much is already used.
202
__attribute__((nonnull, warn_unused_result))
155
203
size_t incbuffer(char **buffer, size_t buffer_length,
156
size_t buffer_capacity){
204
size_t buffer_capacity){
157
205
if(buffer_length + BUFFER_SIZE > buffer_capacity){
158
*buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
206
char *new_buf = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
208
int old_errno = errno;
162
215
buffer_capacity += BUFFER_SIZE;
164
217
return buffer_capacity;
220
/* Add server to set of servers to retry periodically */
221
__attribute__((nonnull, warn_unused_result))
222
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
223
int af, server **current_server){
225
server *new_server = malloc(sizeof(server));
226
if(new_server == NULL){
227
perror_plus("malloc");
230
*new_server = (server){ .ip = strdup(ip),
232
.if_index = if_index,
234
if(new_server->ip == NULL){
235
perror_plus("strdup");
238
ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
240
perror_plus("clock_gettime");
243
/* Special case of first server */
244
if(*current_server == NULL){
245
new_server->next = new_server;
246
new_server->prev = new_server;
247
*current_server = new_server;
249
/* Place the new server last in the list */
250
new_server->next = *current_server;
251
new_server->prev = (*current_server)->prev;
252
new_server->prev->next = new_server;
253
(*current_server)->prev = new_server;
168
259
* Initialize GPGME.
170
static bool init_gpgme(const char *seckey,
171
const char *pubkey, const char *tempdir){
261
__attribute__((nonnull, warn_unused_result))
262
static bool init_gpgme(const char * const seckey,
263
const char * const pubkey,
264
const char * const tempdir,
172
266
gpgme_error_t rc;
173
267
gpgme_engine_info_t engine_info;
177
270
* Helper function to insert pub and seckey to the engine keyring.
179
bool import_key(const char *filename){
272
bool import_key(const char * const filename){
182
275
gpgme_data_t pgp_data;
184
277
fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
190
283
rc = gpgme_data_new_from_fd(&pgp_data, fd);
191
284
if(rc != GPG_ERR_NO_ERROR){
192
fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
193
gpgme_strsource(rc), gpgme_strerror(rc));
285
fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
286
gpgme_strsource(rc), gpgme_strerror(rc));
197
rc = gpgme_op_import(mc.ctx, pgp_data);
290
rc = gpgme_op_import(mc->ctx, pgp_data);
198
291
if(rc != GPG_ERR_NO_ERROR){
199
fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
200
gpgme_strsource(rc), gpgme_strerror(rc));
292
fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
293
gpgme_strsource(rc), gpgme_strerror(rc));
204
297
ret = (int)TEMP_FAILURE_RETRY(close(fd));
299
perror_plus("close");
208
301
gpgme_data_release(pgp_data);
213
fprintf(stderr, "Initializing GPGME\n");
306
fprintf_plus(stderr, "Initializing GPGME\n");
217
310
gpgme_check_version(NULL);
218
311
rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
219
312
if(rc != GPG_ERR_NO_ERROR){
220
fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
221
gpgme_strsource(rc), gpgme_strerror(rc));
313
fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
314
gpgme_strsource(rc), gpgme_strerror(rc));
225
/* Set GPGME home directory for the OpenPGP engine only */
318
/* Set GPGME home directory for the OpenPGP engine only */
226
319
rc = gpgme_get_engine_info(&engine_info);
227
320
if(rc != GPG_ERR_NO_ERROR){
228
fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
229
gpgme_strsource(rc), gpgme_strerror(rc));
321
fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
322
gpgme_strsource(rc), gpgme_strerror(rc));
232
325
while(engine_info != NULL){
271
368
ssize_t plaintext_length = 0;
274
fprintf(stderr, "Trying to decrypt OpenPGP data\n");
371
fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
277
374
/* Create new GPGME data buffer from memory cryptotext */
278
375
rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
280
377
if(rc != GPG_ERR_NO_ERROR){
281
fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
282
gpgme_strsource(rc), gpgme_strerror(rc));
378
fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
379
gpgme_strsource(rc), gpgme_strerror(rc));
286
383
/* Create new empty GPGME data buffer for the plaintext */
287
384
rc = gpgme_data_new(&dh_plain);
288
385
if(rc != GPG_ERR_NO_ERROR){
289
fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
290
gpgme_strsource(rc), gpgme_strerror(rc));
386
fprintf_plus(stderr, "Mandos plugin mandos-client: "
387
"bad gpgme_data_new: %s: %s\n",
388
gpgme_strsource(rc), gpgme_strerror(rc));
291
389
gpgme_data_release(dh_crypto);
295
393
/* Decrypt data from the cryptotext data buffer to the plaintext
297
rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
395
rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
298
396
if(rc != GPG_ERR_NO_ERROR){
299
fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
300
gpgme_strsource(rc), gpgme_strerror(rc));
397
fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
398
gpgme_strsource(rc), gpgme_strerror(rc));
301
399
plaintext_length = -1;
303
401
gpgme_decrypt_result_t result;
304
result = gpgme_op_decrypt_result(mc.ctx);
402
result = gpgme_op_decrypt_result(mc->ctx);
305
403
if(result == NULL){
306
fprintf(stderr, "gpgme_op_decrypt_result failed\n");
404
fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
308
fprintf(stderr, "Unsupported algorithm: %s\n",
309
result->unsupported_algorithm);
310
fprintf(stderr, "Wrong key usage: %u\n",
311
result->wrong_key_usage);
406
fprintf_plus(stderr, "Unsupported algorithm: %s\n",
407
result->unsupported_algorithm);
408
fprintf_plus(stderr, "Wrong key usage: %u\n",
409
result->wrong_key_usage);
312
410
if(result->file_name != NULL){
313
fprintf(stderr, "File name: %s\n", result->file_name);
411
fprintf_plus(stderr, "File name: %s\n", result->file_name);
315
413
gpgme_recipient_t recipient;
316
414
recipient = result->recipients;
317
415
while(recipient != NULL){
318
fprintf(stderr, "Public key algorithm: %s\n",
319
gpgme_pubkey_algo_name(recipient->pubkey_algo));
320
fprintf(stderr, "Key ID: %s\n", recipient->keyid);
321
fprintf(stderr, "Secret key available: %s\n",
322
recipient->status == GPG_ERR_NO_SECKEY
416
fprintf_plus(stderr, "Public key algorithm: %s\n",
417
gpgme_pubkey_algo_name
418
(recipient->pubkey_algo));
419
fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
420
fprintf_plus(stderr, "Secret key available: %s\n",
421
recipient->status == GPG_ERR_NO_SECKEY
324
423
recipient = recipient->next;
423
525
/* OpenPGP credentials */
424
gnutls_certificate_allocate_credentials(&mc.cred);
526
ret = gnutls_certificate_allocate_credentials(&mc->cred);
425
527
if(ret != GNUTLS_E_SUCCESS){
426
fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
430
safer_gnutls_strerror(ret));
528
fprintf_plus(stderr, "GnuTLS memory error: %s\n",
529
safer_gnutls_strerror(ret));
431
530
gnutls_global_deinit();
436
fprintf(stderr, "Attempting to use OpenPGP public key %s and"
437
" secret key %s as GnuTLS credentials\n", pubkeyfilename,
535
fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
536
" secret key %s as GnuTLS credentials\n",
441
541
ret = gnutls_certificate_set_openpgp_key_file
442
(mc.cred, pubkeyfilename, seckeyfilename,
542
(mc->cred, pubkeyfilename, seckeyfilename,
443
543
GNUTLS_OPENPGP_FMT_BASE64);
444
544
if(ret != GNUTLS_E_SUCCESS){
446
"Error[%d] while reading the OpenPGP key pair ('%s',"
447
" '%s')\n", ret, pubkeyfilename, seckeyfilename);
448
fprintf(stderr, "The GnuTLS error is: %s\n",
449
safer_gnutls_strerror(ret));
546
"Error[%d] while reading the OpenPGP key pair ('%s',"
547
" '%s')\n", ret, pubkeyfilename, seckeyfilename);
548
fprintf_plus(stderr, "The GnuTLS error is: %s\n",
549
safer_gnutls_strerror(ret));
453
553
/* GnuTLS server initialization */
454
ret = gnutls_dh_params_init(&mc.dh_params);
554
ret = gnutls_dh_params_init(&mc->dh_params);
455
555
if(ret != GNUTLS_E_SUCCESS){
456
fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
457
" %s\n", safer_gnutls_strerror(ret));
556
fprintf_plus(stderr, "Error in GnuTLS DH parameter"
557
" initialization: %s\n",
558
safer_gnutls_strerror(ret));
460
ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
561
ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
461
562
if(ret != GNUTLS_E_SUCCESS){
462
fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
463
safer_gnutls_strerror(ret));
563
fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
564
safer_gnutls_strerror(ret));
467
gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
568
gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
473
gnutls_certificate_free_credentials(mc.cred);
574
gnutls_certificate_free_credentials(mc->cred);
474
575
gnutls_global_deinit();
475
gnutls_dh_params_deinit(mc.dh_params);
576
gnutls_dh_params_deinit(mc->dh_params);
479
static int init_gnutls_session(gnutls_session_t *session){
580
__attribute__((nonnull, warn_unused_result))
581
static int init_gnutls_session(gnutls_session_t *session,
481
584
/* GnuTLS session creation */
1015
1175
signal_received = sig;
1016
1176
int old_errno = errno;
1017
if(mc.simple_poll != NULL){
1018
avahi_simple_poll_quit(mc.simple_poll);
1177
/* set main loop to exit */
1178
if(simple_poll != NULL){
1179
avahi_simple_poll_quit(simple_poll);
1184
__attribute__((nonnull, warn_unused_result))
1185
bool get_flags(const char *ifname, struct ifreq *ifr){
1189
int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1192
perror_plus("socket");
1196
strcpy(ifr->ifr_name, ifname);
1197
ret = ioctl(s, SIOCGIFFLAGS, ifr);
1201
perror_plus("ioctl SIOCGIFFLAGS");
1209
__attribute__((nonnull, warn_unused_result))
1210
bool good_flags(const char *ifname, const struct ifreq *ifr){
1212
/* Reject the loopback device */
1213
if(ifr->ifr_flags & IFF_LOOPBACK){
1215
fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1220
/* Accept point-to-point devices only if connect_to is specified */
1221
if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1223
fprintf_plus(stderr, "Accepting point-to-point interface"
1224
" \"%s\"\n", ifname);
1228
/* Otherwise, reject non-broadcast-capable devices */
1229
if(not (ifr->ifr_flags & IFF_BROADCAST)){
1231
fprintf_plus(stderr, "Rejecting non-broadcast interface"
1232
" \"%s\"\n", ifname);
1236
/* Reject non-ARP interfaces (including dummy interfaces) */
1237
if(ifr->ifr_flags & IFF_NOARP){
1239
fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1245
/* Accept this device */
1247
fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1253
* This function determines if a directory entry in /sys/class/net
1254
* corresponds to an acceptable network device.
1255
* (This function is passed to scandir(3) as a filter function.)
1257
__attribute__((nonnull, warn_unused_result))
1258
int good_interface(const struct dirent *if_entry){
1259
if(if_entry->d_name[0] == '.'){
1264
if(not get_flags(if_entry->d_name, &ifr)){
1266
fprintf_plus(stderr, "Failed to get flags for interface "
1267
"\"%s\"\n", if_entry->d_name);
1272
if(not good_flags(if_entry->d_name, &ifr)){
1279
* This function determines if a network interface is up.
1281
__attribute__((nonnull, warn_unused_result))
1282
bool interface_is_up(const char *interface){
1284
if(not get_flags(interface, &ifr)){
1286
fprintf_plus(stderr, "Failed to get flags for interface "
1287
"\"%s\"\n", interface);
1292
return (bool)(ifr.ifr_flags & IFF_UP);
1296
* This function determines if a network interface is running
1298
__attribute__((nonnull, warn_unused_result))
1299
bool interface_is_running(const char *interface){
1301
if(not get_flags(interface, &ifr)){
1303
fprintf_plus(stderr, "Failed to get flags for interface "
1304
"\"%s\"\n", interface);
1309
return (bool)(ifr.ifr_flags & IFF_RUNNING);
1312
__attribute__((nonnull, pure, warn_unused_result))
1313
int notdotentries(const struct dirent *direntry){
1314
/* Skip "." and ".." */
1315
if(direntry->d_name[0] == '.'
1316
and (direntry->d_name[1] == '\0'
1317
or (direntry->d_name[1] == '.'
1318
and direntry->d_name[2] == '\0'))){
1324
/* Is this directory entry a runnable program? */
1325
__attribute__((nonnull, warn_unused_result))
1326
int runnable_hook(const struct dirent *direntry){
1331
if((direntry->d_name)[0] == '\0'){
1336
sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1337
"abcdefghijklmnopqrstuvwxyz"
1340
if((direntry->d_name)[sret] != '\0'){
1341
/* Contains non-allowed characters */
1343
fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
1349
char *fullname = NULL;
1350
ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1352
perror_plus("asprintf");
1356
ret = stat(fullname, &st);
1359
perror_plus("Could not stat hook");
1364
if(not (S_ISREG(st.st_mode))){
1365
/* Not a regular file */
1367
fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
1372
if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1373
/* Not executable */
1375
fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
1381
fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
1387
__attribute__((nonnull, warn_unused_result))
1388
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
1389
mandos_context *mc){
1391
struct timespec now;
1392
struct timespec waited_time;
1393
intmax_t block_time;
1396
if(mc->current_server == NULL){
1398
fprintf_plus(stderr, "Wait until first server is found."
1401
ret = avahi_simple_poll_iterate(s, -1);
1404
fprintf_plus(stderr, "Check current_server if we should run"
1407
/* the current time */
1408
ret = clock_gettime(CLOCK_MONOTONIC, &now);
1410
perror_plus("clock_gettime");
1413
/* Calculating in ms how long time between now and server
1414
who we visted longest time ago. Now - last seen. */
1415
waited_time.tv_sec = (now.tv_sec
1416
- mc->current_server->last_seen.tv_sec);
1417
waited_time.tv_nsec = (now.tv_nsec
1418
- mc->current_server->last_seen.tv_nsec);
1419
/* total time is 10s/10,000ms.
1420
Converting to s from ms by dividing by 1,000,
1421
and ns to ms by dividing by 1,000,000. */
1422
block_time = ((retry_interval
1423
- ((intmax_t)waited_time.tv_sec * 1000))
1424
- ((intmax_t)waited_time.tv_nsec / 1000000));
1427
fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1431
if(block_time <= 0){
1432
ret = start_mandos_communication(mc->current_server->ip,
1433
mc->current_server->port,
1434
mc->current_server->if_index,
1435
mc->current_server->af, mc);
1437
avahi_simple_poll_quit(s);
1440
ret = clock_gettime(CLOCK_MONOTONIC,
1441
&mc->current_server->last_seen);
1443
perror_plus("clock_gettime");
1446
mc->current_server = mc->current_server->next;
1447
block_time = 0; /* Call avahi to find new Mandos
1448
servers, but don't block */
1451
ret = avahi_simple_poll_iterate(s, (int)block_time);
1454
if(ret > 0 or errno != EINTR){
1455
return (ret != 1) ? ret : 0;
1461
/* Set effective uid to 0, return errno */
1462
__attribute__((warn_unused_result))
1463
error_t raise_privileges(void){
1464
error_t old_errno = errno;
1465
error_t ret_errno = 0;
1466
if(seteuid(0) == -1){
1468
perror_plus("seteuid");
1474
/* Set effective and real user ID to 0. Return errno. */
1475
__attribute__((warn_unused_result))
1476
error_t raise_privileges_permanently(void){
1477
error_t old_errno = errno;
1478
error_t ret_errno = raise_privileges();
1483
if(setuid(0) == -1){
1485
perror_plus("seteuid");
1491
/* Set effective user ID to unprivileged saved user ID */
1492
__attribute__((warn_unused_result))
1493
error_t lower_privileges(void){
1494
error_t old_errno = errno;
1495
error_t ret_errno = 0;
1496
if(seteuid(uid) == -1){
1498
perror_plus("seteuid");
1504
/* Lower privileges permanently */
1505
__attribute__((warn_unused_result))
1506
error_t lower_privileges_permanently(void){
1507
error_t old_errno = errno;
1508
error_t ret_errno = 0;
1509
if(setuid(uid) == -1){
1511
perror_plus("setuid");
1519
* Based on the example in the GNU LibC manual chapter 13.13 "File
1520
* Descriptor Flags".
1521
| [[info:libc:Descriptor%20Flags][File Descriptor Flags]] |
1523
__attribute__((warn_unused_result))
1524
static int set_cloexec_flag(int fd){
1525
int ret = (int)TEMP_FAILURE_RETRY(fcntl(fd, F_GETFD, 0));
1526
/* If reading the flags failed, return error indication now. */
1530
/* Store modified flag word in the descriptor. */
1531
return (int)TEMP_FAILURE_RETRY(fcntl(fd, F_SETFD,
1534
#endif /* not O_CLOEXEC */
1536
__attribute__((nonnull))
1537
void run_network_hooks(const char *mode, const char *interface,
1539
struct dirent **direntries;
1540
if(hookdir_fd == -1){
1541
hookdir_fd = open(hookdir, O_RDONLY |
1544
#else /* not O_CLOEXEC */
1546
#endif /* not O_CLOEXEC */
1548
if(hookdir_fd == -1){
1549
if(errno == ENOENT){
1551
fprintf_plus(stderr, "Network hook directory \"%s\" not"
1552
" found\n", hookdir);
1555
perror_plus("open");
1560
if(set_cloexec_flag(hookdir_fd) < 0){
1561
perror_plus("set_cloexec_flag");
1562
if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
1563
perror_plus("close");
1569
#endif /* not O_CLOEXEC */
1572
#if __GLIBC_PREREQ(2, 15)
1573
int numhooks = scandirat(hookdir_fd, ".", &direntries,
1574
runnable_hook, alphasort);
1575
#else /* not __GLIBC_PREREQ(2, 15) */
1576
int numhooks = scandir(hookdir, &direntries, runnable_hook,
1578
#endif /* not __GLIBC_PREREQ(2, 15) */
1579
#else /* not __GLIBC__ */
1580
int numhooks = scandir(hookdir, &direntries, runnable_hook,
1582
#endif /* not __GLIBC__ */
1584
perror_plus("scandir");
1587
struct dirent *direntry;
1589
int devnull = open("/dev/null", O_RDONLY);
1590
for(int i = 0; i < numhooks; i++){
1591
direntry = direntries[i];
1592
char *fullname = NULL;
1593
ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1595
perror_plus("asprintf");
1599
fprintf_plus(stderr, "Running network hook \"%s\"\n",
1602
pid_t hook_pid = fork();
1605
/* Raise privileges */
1606
if(raise_privileges_permanently() != 0){
1607
perror_plus("Failed to raise privileges");
1614
perror_plus("setgid");
1617
/* Reset supplementary groups */
1619
ret = setgroups(0, NULL);
1621
perror_plus("setgroups");
1624
ret = dup2(devnull, STDIN_FILENO);
1626
perror_plus("dup2(devnull, STDIN_FILENO)");
1629
ret = close(devnull);
1631
perror_plus("close");
1634
ret = dup2(STDERR_FILENO, STDOUT_FILENO);
1636
perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
1639
ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1641
perror_plus("setenv");
1644
ret = setenv("DEVICE", interface, 1);
1646
perror_plus("setenv");
1649
ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1651
perror_plus("setenv");
1654
ret = setenv("MODE", mode, 1);
1656
perror_plus("setenv");
1660
ret = asprintf(&delaystring, "%f", (double)delay);
1662
perror_plus("asprintf");
1665
ret = setenv("DELAY", delaystring, 1);
1668
perror_plus("setenv");
1672
if(connect_to != NULL){
1673
ret = setenv("CONNECT", connect_to, 1);
1675
perror_plus("setenv");
1679
if(execl(fullname, direntry->d_name, mode, NULL) == -1){
1680
perror_plus("execl");
1681
_exit(EXIT_FAILURE);
1685
if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1686
perror_plus("waitpid");
1690
if(WIFEXITED(status)){
1691
if(WEXITSTATUS(status) != 0){
1692
fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1693
" with status %d\n", direntry->d_name,
1694
WEXITSTATUS(status));
1698
} else if(WIFSIGNALED(status)){
1699
fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1700
" signal %d\n", direntry->d_name,
1705
fprintf_plus(stderr, "Warning: network hook \"%s\""
1706
" crashed\n", direntry->d_name);
1713
fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1717
if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
1718
perror_plus("close");
1725
__attribute__((nonnull, warn_unused_result))
1726
error_t bring_up_interface(const char *const interface,
1728
error_t old_errno = errno;
1730
struct ifreq network;
1731
unsigned int if_index = if_nametoindex(interface);
1733
fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1743
if(not interface_is_up(interface)){
1744
error_t ret_errno = 0, ioctl_errno = 0;
1745
if(not get_flags(interface, &network)){
1747
fprintf_plus(stderr, "Failed to get flags for interface "
1748
"\"%s\"\n", interface);
1752
network.ifr_flags |= IFF_UP; /* set flag */
1754
int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1757
perror_plus("socket");
1763
ret = (int)TEMP_FAILURE_RETRY(close(sd));
1765
perror_plus("close");
1772
fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
1776
/* Raise privileges */
1777
ret_errno = raise_privileges();
1779
perror_plus("Failed to raise privileges");
1784
bool restore_loglevel = false;
1786
/* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1787
messages about the network interface to mess up the prompt */
1788
ret_linux = klogctl(8, NULL, 5);
1789
if(ret_linux == -1){
1790
perror_plus("klogctl");
1792
restore_loglevel = true;
1795
#endif /* __linux__ */
1796
int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1797
ioctl_errno = errno;
1799
if(restore_loglevel){
1800
ret_linux = klogctl(7, NULL, 0);
1801
if(ret_linux == -1){
1802
perror_plus("klogctl");
1805
#endif /* __linux__ */
1807
/* If raise_privileges() succeeded above */
1809
/* Lower privileges */
1810
ret_errno = lower_privileges();
1813
perror_plus("Failed to lower privileges");
1817
/* Close the socket */
1818
ret = (int)TEMP_FAILURE_RETRY(close(sd));
1820
perror_plus("close");
1823
if(ret_setflags == -1){
1824
errno = ioctl_errno;
1825
perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1830
fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
1834
/* Sleep checking until interface is running.
1835
Check every 0.25s, up to total time of delay */
1836
for(int i=0; i < delay * 4; i++){
1837
if(interface_is_running(interface)){
1840
struct timespec sleeptime = { .tv_nsec = 250000000 };
1841
ret = nanosleep(&sleeptime, NULL);
1842
if(ret == -1 and errno != EINTR){
1843
perror_plus("nanosleep");
1851
__attribute__((nonnull, warn_unused_result))
1852
error_t take_down_interface(const char *const interface){
1853
error_t old_errno = errno;
1854
struct ifreq network;
1855
unsigned int if_index = if_nametoindex(interface);
1857
fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1861
if(interface_is_up(interface)){
1862
error_t ret_errno = 0, ioctl_errno = 0;
1863
if(not get_flags(interface, &network) and debug){
1865
fprintf_plus(stderr, "Failed to get flags for interface "
1866
"\"%s\"\n", interface);
1870
network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1872
int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1875
perror_plus("socket");
1881
fprintf_plus(stderr, "Taking down interface \"%s\"\n",
1885
/* Raise privileges */
1886
ret_errno = raise_privileges();
1888
perror_plus("Failed to raise privileges");
1891
int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1892
ioctl_errno = errno;
1894
/* If raise_privileges() succeeded above */
1896
/* Lower privileges */
1897
ret_errno = lower_privileges();
1900
perror_plus("Failed to lower privileges");
1904
/* Close the socket */
1905
int ret = (int)TEMP_FAILURE_RETRY(close(sd));
1907
perror_plus("close");
1910
if(ret_setflags == -1){
1911
errno = ioctl_errno;
1912
perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1917
fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
1023
1925
int main(int argc, char *argv[]){
1926
mandos_context mc = { .server = NULL, .dh_bits = 1024,
1927
.priority = "SECURE256:!CTYPE-X.509:"
1928
"+CTYPE-OPENPGP", .current_server = NULL,
1929
.interfaces = NULL, .interfaces_size = 0 };
1024
1930
AvahiSServiceBrowser *sb = NULL;
1027
1933
intmax_t tmpmax;
1029
1935
int exitcode = EXIT_SUCCESS;
1030
const char *interface = "eth0";
1031
struct ifreq network;
1033
bool take_down_interface = false;
1036
char *connect_to = NULL;
1037
char tempdir[] = "/tmp/mandosXXXXXX";
1038
bool tempdir_created = false;
1936
char *interfaces_to_take_down = NULL;
1937
size_t interfaces_to_take_down_size = 0;
1938
char run_tempdir[] = "/run/tmp/mandosXXXXXX";
1939
char old_tempdir[] = "/tmp/mandosXXXXXX";
1940
char *tempdir = NULL;
1039
1941
AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1040
1942
const char *seckey = PATHDIR "/" SECKEY;
1041
1943
const char *pubkey = PATHDIR "/" PUBKEY;
1944
char *interfaces_hooks = NULL;
1043
1946
bool gnutls_initialized = false;
1044
1947
bool gpgme_initialized = false;
1045
1948
float delay = 2.5f;
1949
double retry_interval = 10; /* 10s between trying a server and
1950
retrying the same server again */
1047
1952
struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1048
1953
struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1234
2258
ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1236
perror("sigaction");
2260
perror_plus("sigaction");
1237
2261
return EX_OSERR;
1239
2263
if(old_sigterm_action.sa_handler != SIG_IGN){
1240
2264
ret = sigaction(SIGINT, &sigterm_action, NULL);
1242
perror("sigaction");
2266
perror_plus("sigaction");
1243
2267
exitcode = EX_OSERR;
1247
2271
ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1249
perror("sigaction");
2273
perror_plus("sigaction");
1250
2274
return EX_OSERR;
1252
2276
if(old_sigterm_action.sa_handler != SIG_IGN){
1253
2277
ret = sigaction(SIGHUP, &sigterm_action, NULL);
1255
perror("sigaction");
2279
perror_plus("sigaction");
1256
2280
exitcode = EX_OSERR;
1260
2284
ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1262
perror("sigaction");
2286
perror_plus("sigaction");
1263
2287
return EX_OSERR;
1265
2289
if(old_sigterm_action.sa_handler != SIG_IGN){
1266
2290
ret = sigaction(SIGTERM, &sigterm_action, NULL);
1268
perror("sigaction");
1269
exitcode = EX_OSERR;
1274
/* If the interface is down, bring it up */
1275
if(interface[0] != '\0'){
1276
if_index = (AvahiIfIndex) if_nametoindex(interface);
1278
fprintf(stderr, "No such interface: \"%s\"\n", interface);
1279
exitcode = EX_UNAVAILABLE;
1287
/* Re-raise priviliges */
1295
/* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1296
messages about the network interface to mess up the prompt */
1297
ret = klogctl(8, NULL, 5);
1298
bool restore_loglevel = true;
1300
restore_loglevel = false;
1303
#endif /* __linux__ */
1305
sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1308
exitcode = EX_OSERR;
1310
if(restore_loglevel){
1311
ret = klogctl(7, NULL, 0);
1316
#endif /* __linux__ */
1317
/* Lower privileges */
1325
strcpy(network.ifr_name, interface);
1326
ret = ioctl(sd, SIOCGIFFLAGS, &network);
1328
perror("ioctl SIOCGIFFLAGS");
1330
if(restore_loglevel){
1331
ret = klogctl(7, NULL, 0);
1336
#endif /* __linux__ */
1337
exitcode = EX_OSERR;
1338
/* Lower privileges */
1346
if((network.ifr_flags & IFF_UP) == 0){
1347
network.ifr_flags |= IFF_UP;
1348
take_down_interface = true;
1349
ret = ioctl(sd, SIOCSIFFLAGS, &network);
1351
take_down_interface = false;
1352
perror("ioctl SIOCSIFFLAGS");
1353
exitcode = EX_OSERR;
1355
if(restore_loglevel){
1356
ret = klogctl(7, NULL, 0);
2292
perror_plus("sigaction");
2293
exitcode = EX_OSERR;
2298
/* If no interfaces were specified, make a list */
2299
if(mc.interfaces == NULL){
2300
struct dirent **direntries;
2301
/* Look for any good interfaces */
2302
ret = scandir(sys_class_net, &direntries, good_interface,
2305
/* Add all found interfaces to interfaces list */
2306
for(int i = 0; i < ret; ++i){
2307
ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
2308
direntries[i]->d_name);
2311
perror_plus("argz_add");
2315
fprintf_plus(stderr, "Will use interface \"%s\"\n",
2316
direntries[i]->d_name);
2322
fprintf_plus(stderr, "Could not find a network interface\n");
2323
exitcode = EXIT_FAILURE;
2328
/* Bring up interfaces which are down, and remove any "none"s */
2330
char *interface = NULL;
2331
while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2333
/* If interface name is "none", stop bringing up interfaces.
2334
Also remove all instances of "none" from the list */
2335
if(strcmp(interface, "none") == 0){
2336
argz_delete(&mc.interfaces, &mc.interfaces_size,
2339
while((interface = argz_next(mc.interfaces,
2340
mc.interfaces_size, interface))){
2341
if(strcmp(interface, "none") == 0){
2342
argz_delete(&mc.interfaces, &mc.interfaces_size,
1361
#endif /* __linux__ */
1362
/* Lower privileges */
1371
/* sleep checking until interface is running */
1372
for(int i=0; i < delay * 4; i++){
1373
ret = ioctl(sd, SIOCGIFFLAGS, &network);
1375
perror("ioctl SIOCGIFFLAGS");
1376
} else if(network.ifr_flags & IFF_RUNNING){
1379
struct timespec sleeptime = { .tv_nsec = 250000000 };
1380
ret = nanosleep(&sleeptime, NULL);
1381
if(ret == -1 and errno != EINTR){
1382
perror("nanosleep");
1385
if(not take_down_interface){
1386
/* We won't need the socket anymore */
1387
ret = (int)TEMP_FAILURE_RETRY(close(sd));
1393
if(restore_loglevel){
1394
/* Restores kernel loglevel to default */
1395
ret = klogctl(7, NULL, 0);
1400
#endif /* __linux__ */
1401
/* Lower privileges */
1403
if(take_down_interface){
1404
/* Lower privileges */
1410
/* Lower privileges permanently */
2349
bool interface_was_up = interface_is_up(interface);
2350
errno = bring_up_interface(interface, delay);
2351
if(not interface_was_up){
2353
perror_plus("Failed to bring up interface");
2355
errno = argz_add(&interfaces_to_take_down,
2356
&interfaces_to_take_down_size,
2359
perror_plus("argz_add");
2364
if(debug and (interfaces_to_take_down == NULL)){
2365
fprintf_plus(stderr, "No interfaces were brought up\n");
2369
/* If we only got one interface, explicitly use only that one */
2370
if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
2372
fprintf_plus(stderr, "Using only interface \"%s\"\n",
2375
if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
1422
ret = init_gnutls_global(pubkey, seckey);
2382
ret = init_gnutls_global(pubkey, seckey, &mc);
1424
fprintf(stderr, "init_gnutls_global failed\n");
2384
fprintf_plus(stderr, "init_gnutls_global failed\n");
1425
2385
exitcode = EX_UNAVAILABLE;