26
26
* along with this program. If not, see
27
27
* <http://www.gnu.org/licenses/>.
29
* Contact the authors at <mandos@recompile.se>.
29
* Contact the authors at <mandos@fukt.bsnet.se>.
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
33
#ifndef _LARGEFILE_SOURCE
34
33
#define _LARGEFILE_SOURCE
36
#ifndef _FILE_OFFSET_BITS
37
34
#define _FILE_OFFSET_BITS 64
40
36
#define _GNU_SOURCE /* TEMP_FAILURE_RETRY(), asprintf() */
42
38
#include <stdio.h> /* fprintf(), stderr, fwrite(),
43
stdout, ferror(), remove() */
44
#include <stdint.h> /* uint16_t, uint32_t, intptr_t */
39
stdout, ferror(), sscanf(),
41
#include <stdint.h> /* uint16_t, uint32_t */
45
42
#include <stddef.h> /* NULL, size_t, ssize_t */
46
#include <stdlib.h> /* free(), EXIT_SUCCESS, srand(),
48
#include <stdbool.h> /* bool, false, true */
43
#include <stdlib.h> /* free(), EXIT_SUCCESS, EXIT_FAILURE,
45
#include <stdbool.h> /* bool, true */
49
46
#include <string.h> /* memset(), strcmp(), strlen(),
50
47
strerror(), asprintf(), strcpy() */
51
#include <sys/ioctl.h> /* ioctl */
48
#include <sys/ioctl.h> /* ioctl */
52
49
#include <sys/types.h> /* socket(), inet_pton(), sockaddr,
53
50
sockaddr_in6, PF_INET6,
54
SOCK_STREAM, uid_t, gid_t, open(),
56
#include <sys/stat.h> /* open(), S_ISREG */
51
SOCK_STREAM, INET6_ADDRSTRLEN,
52
uid_t, gid_t, open(), opendir(),
54
#include <sys/stat.h> /* open() */
57
55
#include <sys/socket.h> /* socket(), struct sockaddr_in6,
58
inet_pton(), connect() */
56
struct in6_addr, inet_pton(),
59
58
#include <fcntl.h> /* open() */
60
59
#include <dirent.h> /* opendir(), struct dirent, readdir()
62
#include <inttypes.h> /* PRIu16, PRIdMAX, intmax_t,
61
#include <inttypes.h> /* PRIu16, intmax_t, SCNdMAX */
64
62
#include <assert.h> /* assert() */
65
#include <errno.h> /* perror(), errno,
66
program_invocation_short_name */
67
#include <time.h> /* nanosleep(), time(), sleep() */
63
#include <errno.h> /* perror(), errno */
64
#include <time.h> /* nanosleep(), time() */
68
65
#include <net/if.h> /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
69
66
SIOCSIFFLAGS, if_indextoname(),
70
67
if_nametoindex(), IF_NAMESIZE */
71
#include <netinet/in.h> /* IN6_IS_ADDR_LINKLOCAL,
72
INET_ADDRSTRLEN, INET6_ADDRSTRLEN
68
#include <netinet/in.h>
74
69
#include <unistd.h> /* close(), SEEK_SET, off_t, write(),
75
getuid(), getgid(), seteuid(),
76
setgid(), pause(), _exit() */
77
#include <arpa/inet.h> /* inet_pton(), htons, inet_ntop() */
78
#include <iso646.h> /* not, or, and */
70
getuid(), getgid(), setuid(),
72
#include <arpa/inet.h> /* inet_pton(), htons */
73
#include <iso646.h> /* not, and, or */
79
74
#include <argp.h> /* struct argp_option, error_t, struct
80
75
argp_state, struct argp,
81
76
argp_parse(), ARGP_KEY_ARG,
82
77
ARGP_KEY_END, ARGP_ERR_UNKNOWN */
83
#include <signal.h> /* sigemptyset(), sigaddset(),
84
sigaction(), SIGTERM, sig_atomic_t,
86
#include <sysexits.h> /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
#include <sys/wait.h> /* waitpid(), WIFEXITED(),
89
WEXITSTATUS(), WTERMSIG() */
90
#include <grp.h> /* setgroups() */
93
79
#include <sys/klog.h> /* klogctl() */
94
#endif /* __linux__ */
97
83
/* All Avahi types, constants and functions
256
160
* Helper function to insert pub and seckey to the engine keyring.
258
162
bool import_key(const char *filename){
261
164
gpgme_data_t pgp_data;
263
166
fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
269
172
rc = gpgme_data_new_from_fd(&pgp_data, fd);
270
173
if(rc != GPG_ERR_NO_ERROR){
271
fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
272
gpgme_strsource(rc), gpgme_strerror(rc));
174
fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
175
gpgme_strsource(rc), gpgme_strerror(rc));
276
rc = gpgme_op_import(mc.ctx, pgp_data);
179
rc = gpgme_op_import(mc->ctx, pgp_data);
277
180
if(rc != GPG_ERR_NO_ERROR){
278
fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
279
gpgme_strsource(rc), gpgme_strerror(rc));
181
fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
182
gpgme_strsource(rc), gpgme_strerror(rc));
283
186
ret = (int)TEMP_FAILURE_RETRY(close(fd));
285
perror_plus("close");
287
190
gpgme_data_release(pgp_data);
292
fprintf_plus(stderr, "Initializing GPGME\n");
195
fprintf(stderr, "Initialize gpgme\n");
296
199
gpgme_check_version(NULL);
297
200
rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
298
201
if(rc != GPG_ERR_NO_ERROR){
299
fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
300
gpgme_strsource(rc), gpgme_strerror(rc));
202
fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
203
gpgme_strsource(rc), gpgme_strerror(rc));
304
/* Set GPGME home directory for the OpenPGP engine only */
207
/* Set GPGME home directory for the OpenPGP engine only */
305
208
rc = gpgme_get_engine_info(&engine_info);
306
209
if(rc != GPG_ERR_NO_ERROR){
307
fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
308
gpgme_strsource(rc), gpgme_strerror(rc));
210
fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
211
gpgme_strsource(rc), gpgme_strerror(rc));
311
214
while(engine_info != NULL){
352
254
ssize_t plaintext_length = 0;
355
fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
257
fprintf(stderr, "Trying to decrypt OpenPGP data\n");
358
260
/* Create new GPGME data buffer from memory cryptotext */
359
261
rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
361
263
if(rc != GPG_ERR_NO_ERROR){
362
fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
363
gpgme_strsource(rc), gpgme_strerror(rc));
264
fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
265
gpgme_strsource(rc), gpgme_strerror(rc));
367
269
/* Create new empty GPGME data buffer for the plaintext */
368
270
rc = gpgme_data_new(&dh_plain);
369
271
if(rc != GPG_ERR_NO_ERROR){
370
fprintf_plus(stderr, "Mandos plugin mandos-client: "
371
"bad gpgme_data_new: %s: %s\n",
372
gpgme_strsource(rc), gpgme_strerror(rc));
272
fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
273
gpgme_strsource(rc), gpgme_strerror(rc));
373
274
gpgme_data_release(dh_crypto);
377
278
/* Decrypt data from the cryptotext data buffer to the plaintext
379
rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
280
rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
380
281
if(rc != GPG_ERR_NO_ERROR){
381
fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
382
gpgme_strsource(rc), gpgme_strerror(rc));
282
fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
283
gpgme_strsource(rc), gpgme_strerror(rc));
383
284
plaintext_length = -1;
385
286
gpgme_decrypt_result_t result;
386
result = gpgme_op_decrypt_result(mc.ctx);
287
result = gpgme_op_decrypt_result(mc->ctx);
387
288
if(result == NULL){
388
fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
289
fprintf(stderr, "gpgme_op_decrypt_result failed\n");
390
fprintf_plus(stderr, "Unsupported algorithm: %s\n",
391
result->unsupported_algorithm);
392
fprintf_plus(stderr, "Wrong key usage: %u\n",
393
result->wrong_key_usage);
291
fprintf(stderr, "Unsupported algorithm: %s\n",
292
result->unsupported_algorithm);
293
fprintf(stderr, "Wrong key usage: %u\n",
294
result->wrong_key_usage);
394
295
if(result->file_name != NULL){
395
fprintf_plus(stderr, "File name: %s\n", result->file_name);
296
fprintf(stderr, "File name: %s\n", result->file_name);
397
298
gpgme_recipient_t recipient;
398
299
recipient = result->recipients;
399
while(recipient != NULL){
400
fprintf_plus(stderr, "Public key algorithm: %s\n",
401
gpgme_pubkey_algo_name
402
(recipient->pubkey_algo));
403
fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
404
fprintf_plus(stderr, "Secret key available: %s\n",
405
recipient->status == GPG_ERR_NO_SECKEY
407
recipient = recipient->next;
301
while(recipient != NULL){
302
fprintf(stderr, "Public key algorithm: %s\n",
303
gpgme_pubkey_algo_name(recipient->pubkey_algo));
304
fprintf(stderr, "Key ID: %s\n", recipient->keyid);
305
fprintf(stderr, "Secret key available: %s\n",
306
recipient->status == GPG_ERR_NO_SECKEY
308
recipient = recipient->next;
506
409
/* OpenPGP credentials */
507
ret = gnutls_certificate_allocate_credentials(&mc.cred);
410
gnutls_certificate_allocate_credentials(&mc->cred);
508
411
if(ret != GNUTLS_E_SUCCESS){
509
fprintf_plus(stderr, "GnuTLS memory error: %s\n",
510
safer_gnutls_strerror(ret));
412
fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
416
safer_gnutls_strerror(ret));
511
417
gnutls_global_deinit();
516
fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
517
" secret key %s as GnuTLS credentials\n",
422
fprintf(stderr, "Attempting to use OpenPGP public key %s and"
423
" secret key %s as GnuTLS credentials\n", pubkeyfilename,
522
427
ret = gnutls_certificate_set_openpgp_key_file
523
(mc.cred, pubkeyfilename, seckeyfilename,
428
(mc->cred, pubkeyfilename, seckeyfilename,
524
429
GNUTLS_OPENPGP_FMT_BASE64);
525
430
if(ret != GNUTLS_E_SUCCESS){
527
"Error[%d] while reading the OpenPGP key pair ('%s',"
528
" '%s')\n", ret, pubkeyfilename, seckeyfilename);
529
fprintf_plus(stderr, "The GnuTLS error is: %s\n",
530
safer_gnutls_strerror(ret));
432
"Error[%d] while reading the OpenPGP key pair ('%s',"
433
" '%s')\n", ret, pubkeyfilename, seckeyfilename);
434
fprintf(stderr, "The GnuTLS error is: %s\n",
435
safer_gnutls_strerror(ret));
534
439
/* GnuTLS server initialization */
535
ret = gnutls_dh_params_init(&mc.dh_params);
440
ret = gnutls_dh_params_init(&mc->dh_params);
536
441
if(ret != GNUTLS_E_SUCCESS){
537
fprintf_plus(stderr, "Error in GnuTLS DH parameter"
538
" initialization: %s\n",
539
safer_gnutls_strerror(ret));
442
fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
443
" %s\n", safer_gnutls_strerror(ret));
542
ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
446
ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
543
447
if(ret != GNUTLS_E_SUCCESS){
544
fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
545
safer_gnutls_strerror(ret));
448
fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
449
safer_gnutls_strerror(ret));
549
gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
453
gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
555
gnutls_certificate_free_credentials(mc.cred);
459
gnutls_certificate_free_credentials(mc->cred);
556
460
gnutls_global_deinit();
557
gnutls_dh_params_deinit(mc.dh_params);
461
gnutls_dh_params_deinit(mc->dh_params);
561
static int init_gnutls_session(gnutls_session_t *session){
465
static int init_gnutls_session(mandos_context *mc,
466
gnutls_session_t *session){
563
468
/* GnuTLS session creation */
565
ret = gnutls_init(session, GNUTLS_SERVER);
569
} while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
469
ret = gnutls_init(session, GNUTLS_SERVER);
570
470
if(ret != GNUTLS_E_SUCCESS){
572
"Error in GnuTLS session initialization: %s\n",
573
safer_gnutls_strerror(ret));
471
fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
472
safer_gnutls_strerror(ret));
579
ret = gnutls_priority_set_direct(*session, mc.priority, &err);
581
gnutls_deinit(*session);
584
} while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
477
ret = gnutls_priority_set_direct(*session, mc->priority, &err);
585
478
if(ret != GNUTLS_E_SUCCESS){
586
fprintf_plus(stderr, "Syntax error at: %s\n", err);
587
fprintf_plus(stderr, "GnuTLS error: %s\n",
588
safer_gnutls_strerror(ret));
479
fprintf(stderr, "Syntax error at: %s\n", err);
480
fprintf(stderr, "GnuTLS error: %s\n",
481
safer_gnutls_strerror(ret));
589
482
gnutls_deinit(*session);
595
ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
598
gnutls_deinit(*session);
601
} while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
487
ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
602
489
if(ret != GNUTLS_E_SUCCESS){
603
fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
604
safer_gnutls_strerror(ret));
490
fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
491
safer_gnutls_strerror(ret));
605
492
gnutls_deinit(*session);
609
496
/* ignore client certificate if any. */
610
gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
497
gnutls_certificate_server_set_request(*session,
612
gnutls_dh_set_prime_bits(*session, mc.dh_bits);
500
gnutls_dh_set_prime_bits(*session, mc->dh_bits);
621
509
/* Called when a Mandos server is found */
622
510
static int start_mandos_communication(const char *ip, uint16_t port,
623
511
AvahiIfIndex if_index,
625
int ret, tcp_sd = -1;
628
struct sockaddr_in in;
629
struct sockaddr_in6 in6;
515
union { struct sockaddr in; struct sockaddr_in6 in6; } to;
631
516
char *buffer = NULL;
632
char *decrypted_buffer = NULL;
517
char *decrypted_buffer;
633
518
size_t buffer_length = 0;
634
519
size_t buffer_capacity = 0;
520
ssize_t decrypted_buffer_size;
523
char interface[IF_NAMESIZE];
637
524
gnutls_session_t session;
638
int pf; /* Protocol family */
655
fprintf_plus(stderr, "Bad address family: %d\n", af);
660
ret = init_gnutls_session(&session);
526
ret = init_gnutls_session(mc, &session);
666
fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
667
PRIu16 "\n", ip, port);
532
fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
670
tcp_sd = socket(pf, SOCK_STREAM, 0);
536
tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
673
perror_plus("socket");
543
if(if_indextoname((unsigned int)if_index, interface) == NULL){
544
perror("if_indextoname");
547
fprintf(stderr, "Binding to interface %s\n", interface);
683
550
memset(&to, 0, sizeof(to));
685
to.in6.sin6_family = (sa_family_t)af;
686
ret = inet_pton(af, ip, &to.in6.sin6_addr);
688
to.in.sin_family = (sa_family_t)af;
689
ret = inet_pton(af, ip, &to.in.sin_addr);
551
to.in6.sin6_family = AF_INET6;
552
/* It would be nice to have a way to detect if we were passed an
553
IPv4 address here. Now we assume an IPv6 address. */
554
ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
693
perror_plus("inet_pton");
699
fprintf_plus(stderr, "Bad address: %s\n", ip);
560
fprintf(stderr, "Bad address: %s\n", ip);
704
to.in6.sin6_port = htons(port); /* Spurious warnings from
706
-Wunreachable-code */
708
if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
709
(&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
711
if(if_index == AVAHI_IF_UNSPEC){
712
fprintf_plus(stderr, "An IPv6 link-local address is"
713
" incomplete without a network interface\n");
717
/* Set the network interface number as scope */
718
to.in6.sin6_scope_id = (uint32_t)if_index;
721
to.in.sin_port = htons(port); /* Spurious warnings from
563
to.in6.sin6_port = htons(port); /* Spurious warnings from
723
565
-Wunreachable-code */
567
to.in6.sin6_scope_id = (uint32_t)if_index;
732
if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
733
char interface[IF_NAMESIZE];
734
if(if_indextoname((unsigned int)if_index, interface) == NULL){
735
perror_plus("if_indextoname");
737
fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
738
"\n", ip, interface, port);
741
fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
744
char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
745
INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
748
pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
751
pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
755
perror_plus("inet_ntop");
570
fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
572
char addrstr[INET6_ADDRSTRLEN] = "";
573
if(inet_ntop(to.in6.sin6_family, &(to.in6.sin6_addr), addrstr,
574
sizeof(addrstr)) == NULL){
757
577
if(strcmp(addrstr, ip) != 0){
758
fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
578
fprintf(stderr, "Canonical address form: %s\n", addrstr);
769
ret = connect(tcp_sd, &to.in6, sizeof(to));
771
ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
583
ret = connect(tcp_sd, &to.in, sizeof(to));
774
if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
776
perror_plus("connect");
787
589
const char *out = mandos_protocol_version;
1097
815
case AVAHI_BROWSER_ALL_FOR_NOW:
1098
816
case AVAHI_BROWSER_CACHE_EXHAUSTED:
1100
fprintf_plus(stderr, "No Mandos server found, still"
818
fprintf(stderr, "No Mandos server found, still searching...\n");
1107
/* Signal handler that stops main loop after SIGTERM */
1108
static void handle_sigterm(int sig){
1113
signal_received = sig;
1114
int old_errno = errno;
1115
/* set main loop to exit */
1116
if(mc.simple_poll != NULL){
1117
avahi_simple_poll_quit(mc.simple_poll);
1122
bool get_flags(const char *ifname, struct ifreq *ifr){
1125
int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1127
perror_plus("socket");
1130
strcpy(ifr->ifr_name, ifname);
1131
ret = ioctl(s, SIOCGIFFLAGS, ifr);
1134
perror_plus("ioctl SIOCGIFFLAGS");
1141
bool good_flags(const char *ifname, const struct ifreq *ifr){
1143
/* Reject the loopback device */
1144
if(ifr->ifr_flags & IFF_LOOPBACK){
1146
fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1151
/* Accept point-to-point devices only if connect_to is specified */
1152
if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1154
fprintf_plus(stderr, "Accepting point-to-point interface"
1155
" \"%s\"\n", ifname);
1159
/* Otherwise, reject non-broadcast-capable devices */
1160
if(not (ifr->ifr_flags & IFF_BROADCAST)){
1162
fprintf_plus(stderr, "Rejecting non-broadcast interface"
1163
" \"%s\"\n", ifname);
1167
/* Reject non-ARP interfaces (including dummy interfaces) */
1168
if(ifr->ifr_flags & IFF_NOARP){
1170
fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1176
/* Accept this device */
1178
fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1184
* This function determines if a directory entry in /sys/class/net
1185
* corresponds to an acceptable network device.
1186
* (This function is passed to scandir(3) as a filter function.)
1188
int good_interface(const struct dirent *if_entry){
1189
if(if_entry->d_name[0] == '.'){
1194
if(not get_flags(if_entry->d_name, &ifr)){
1196
fprintf_plus(stderr, "Failed to get flags for interface "
1197
"\"%s\"\n", if_entry->d_name);
1202
if(not good_flags(if_entry->d_name, &ifr)){
1209
* This function determines if a directory entry in /sys/class/net
1210
* corresponds to an acceptable network device which is up.
1211
* (This function is passed to scandir(3) as a filter function.)
1213
int up_interface(const struct dirent *if_entry){
1214
if(if_entry->d_name[0] == '.'){
1219
if(not get_flags(if_entry->d_name, &ifr)){
1221
fprintf_plus(stderr, "Failed to get flags for interface "
1222
"\"%s\"\n", if_entry->d_name);
1227
/* Reject down interfaces */
1228
if(not (ifr.ifr_flags & IFF_UP)){
1230
fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
1236
/* Reject non-running interfaces */
1237
if(not (ifr.ifr_flags & IFF_RUNNING)){
1239
fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
1245
if(not good_flags(if_entry->d_name, &ifr)){
1251
int notdotentries(const struct dirent *direntry){
1252
/* Skip "." and ".." */
1253
if(direntry->d_name[0] == '.'
1254
and (direntry->d_name[1] == '\0'
1255
or (direntry->d_name[1] == '.'
1256
and direntry->d_name[2] == '\0'))){
1262
/* Is this directory entry a runnable program? */
1263
int runnable_hook(const struct dirent *direntry){
1268
if((direntry->d_name)[0] == '\0'){
1273
sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1274
"abcdefghijklmnopqrstuvwxyz"
1277
if((direntry->d_name)[sret] != '\0'){
1278
/* Contains non-allowed characters */
1280
fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
1286
char *fullname = NULL;
1287
ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1289
perror_plus("asprintf");
1293
ret = stat(fullname, &st);
1296
perror_plus("Could not stat hook");
1300
if(not (S_ISREG(st.st_mode))){
1301
/* Not a regular file */
1303
fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
1308
if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1309
/* Not executable */
1311
fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
1317
fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
1323
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1325
struct timespec now;
1326
struct timespec waited_time;
1327
intmax_t block_time;
1330
if(mc.current_server == NULL){
1332
fprintf_plus(stderr, "Wait until first server is found."
1335
ret = avahi_simple_poll_iterate(s, -1);
1338
fprintf_plus(stderr, "Check current_server if we should run"
1341
/* the current time */
1342
ret = clock_gettime(CLOCK_MONOTONIC, &now);
1344
perror_plus("clock_gettime");
1347
/* Calculating in ms how long time between now and server
1348
who we visted longest time ago. Now - last seen. */
1349
waited_time.tv_sec = (now.tv_sec
1350
- mc.current_server->last_seen.tv_sec);
1351
waited_time.tv_nsec = (now.tv_nsec
1352
- mc.current_server->last_seen.tv_nsec);
1353
/* total time is 10s/10,000ms.
1354
Converting to s from ms by dividing by 1,000,
1355
and ns to ms by dividing by 1,000,000. */
1356
block_time = ((retry_interval
1357
- ((intmax_t)waited_time.tv_sec * 1000))
1358
- ((intmax_t)waited_time.tv_nsec / 1000000));
1361
fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1365
if(block_time <= 0){
1366
ret = start_mandos_communication(mc.current_server->ip,
1367
mc.current_server->port,
1368
mc.current_server->if_index,
1369
mc.current_server->af);
1371
avahi_simple_poll_quit(mc.simple_poll);
1374
ret = clock_gettime(CLOCK_MONOTONIC,
1375
&mc.current_server->last_seen);
1377
perror_plus("clock_gettime");
1380
mc.current_server = mc.current_server->next;
1381
block_time = 0; /* Call avahi to find new Mandos
1382
servers, but don't block */
1385
ret = avahi_simple_poll_iterate(s, (int)block_time);
1388
if (ret > 0 or errno != EINTR){
1389
return (ret != 1) ? ret : 0;
1395
/* Set effective uid to 0, return errno */
1396
int raise_privileges(void){
1397
int old_errno = errno;
1400
if(seteuid(0) == -1){
1401
perror_plus("seteuid");
1408
/* Set effective and real user ID to 0. Return errno. */
1409
int raise_privileges_permanently(void){
1410
int old_errno = errno;
1411
int ret_errno = raise_privileges();
1417
if(setuid(0) == -1){
1418
perror_plus("seteuid");
1425
/* Set effective user ID to unprivileged saved user ID */
1426
int lower_privileges(void){
1427
int old_errno = errno;
1430
if(seteuid(uid) == -1){
1431
perror_plus("seteuid");
1438
bool run_network_hooks(const char *mode, const char *interface,
1440
struct dirent **direntries;
1441
struct dirent *direntry;
1443
int numhooks = scandir(hookdir, &direntries, runnable_hook,
1446
perror_plus("scandir");
1448
int devnull = open("/dev/null", O_RDONLY);
1449
for(int i = 0; i < numhooks; i++){
1450
direntry = direntries[i];
1451
char *fullname = NULL;
1452
ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1454
perror_plus("asprintf");
1458
fprintf_plus(stderr, "Running network hook \"%s\"\n",
1461
pid_t hook_pid = fork();
1464
/* Raise privileges */
1465
raise_privileges_permanently();
1470
perror_plus("setgid");
1472
/* Reset supplementary groups */
1474
ret = setgroups(0, NULL);
1476
perror_plus("setgroups");
1478
dup2(devnull, STDIN_FILENO);
1480
dup2(STDERR_FILENO, STDOUT_FILENO);
1481
ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1483
perror_plus("setenv");
1486
ret = setenv("DEVICE", interface, 1);
1488
perror_plus("setenv");
1491
ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1493
perror_plus("setenv");
1496
ret = setenv("MODE", mode, 1);
1498
perror_plus("setenv");
1502
ret = asprintf(&delaystring, "%f", delay);
1504
perror_plus("asprintf");
1507
ret = setenv("DELAY", delaystring, 1);
1510
perror_plus("setenv");
1514
if(connect_to != NULL){
1515
ret = setenv("CONNECT", connect_to, 1);
1517
perror_plus("setenv");
1521
if(execl(fullname, direntry->d_name, mode, NULL) == -1){
1522
perror_plus("execl");
1523
_exit(EXIT_FAILURE);
1527
if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1528
perror_plus("waitpid");
1532
if(WIFEXITED(status)){
1533
if(WEXITSTATUS(status) != 0){
1534
fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1535
" with status %d\n", direntry->d_name,
1536
WEXITSTATUS(status));
1540
} else if(WIFSIGNALED(status)){
1541
fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1542
" signal %d\n", direntry->d_name,
1547
fprintf_plus(stderr, "Warning: network hook \"%s\""
1548
" crashed\n", direntry->d_name);
1555
fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1564
int bring_up_interface(const char * const interface, const float delay){
1566
int old_errno = errno;
1569
struct ifreq network;
1570
AvahiIfIndex if_index = (AvahiIfIndex)if_nametoindex(interface);
1572
fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1582
/* Re-raise priviliges */
1586
/* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1587
messages about the network interface to mess up the prompt */
1588
ret = klogctl(8, NULL, 5);
1589
bool restore_loglevel = true;
1591
restore_loglevel = false;
1592
perror_plus("klogctl");
1594
#endif /* __linux__ */
1596
sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1599
perror_plus("socket");
1601
if(restore_loglevel){
1602
ret = klogctl(7, NULL, 0);
1604
perror_plus("klogctl");
1607
#endif /* __linux__ */
1608
/* Lower privileges */
1613
strcpy(network.ifr_name, interface);
1614
ret = ioctl(sd, SIOCGIFFLAGS, &network);
1617
perror_plus("ioctl SIOCGIFFLAGS");
1619
if(restore_loglevel){
1620
ret = klogctl(7, NULL, 0);
1622
perror_plus("klogctl");
1625
#endif /* __linux__ */
1626
/* Lower privileges */
1631
if((network.ifr_flags & IFF_UP) == 0){
1632
network.ifr_flags |= IFF_UP;
1633
ret = ioctl(sd, SIOCSIFFLAGS, &network);
1636
perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1638
if(restore_loglevel){
1639
ret = klogctl(7, NULL, 0);
1641
perror_plus("klogctl");
1644
#endif /* __linux__ */
1645
/* Lower privileges */
1651
/* Sleep checking until interface is running.
1652
Check every 0.25s, up to total time of delay */
1653
for(int i=0; i < delay * 4; i++){
1654
ret = ioctl(sd, SIOCGIFFLAGS, &network);
1656
perror_plus("ioctl SIOCGIFFLAGS");
1657
} else if(network.ifr_flags & IFF_RUNNING){
1660
struct timespec sleeptime = { .tv_nsec = 250000000 };
1661
ret = nanosleep(&sleeptime, NULL);
1662
if(ret == -1 and errno != EINTR){
1663
perror_plus("nanosleep");
1666
/* Close the socket */
1667
ret = (int)TEMP_FAILURE_RETRY(close(sd));
1669
perror_plus("close");
1672
if(restore_loglevel){
1673
/* Restores kernel loglevel to default */
1674
ret = klogctl(7, NULL, 0);
1676
perror_plus("klogctl");
1679
#endif /* __linux__ */
1680
/* Lower privileges */
1686
824
int main(int argc, char *argv[]){
1687
825
AvahiSServiceBrowser *sb = NULL;
1690
828
intmax_t tmpmax;
1692
830
int exitcode = EXIT_SUCCESS;
1693
const char *interface = "";
831
const char *interface = "eth0";
1694
832
struct ifreq network;
1696
bool take_down_interface = false;
836
char *connect_to = NULL;
1697
837
char tempdir[] = "/tmp/mandosXXXXXX";
1698
838
bool tempdir_created = false;
1699
839
AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1700
840
const char *seckey = PATHDIR "/" SECKEY;
1701
841
const char *pubkey = PATHDIR "/" PUBKEY;
843
mandos_context mc = { .simple_poll = NULL, .server = NULL,
844
.dh_bits = 1024, .priority = "SECURE256"
845
":!CTYPE-X.509:+CTYPE-OPENPGP" };
1703
846
bool gnutls_initialized = false;
1704
847
bool gpgme_initialized = false;
1706
double retry_interval = 10; /* 10s between trying a server and
1707
retrying the same server again */
1709
struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1710
struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1715
/* Lower any group privileges we might have, just to be safe */
1719
perror_plus("setgid");
1722
/* Lower user privileges (temporarily) */
1726
perror_plus("seteuid");
1734
851
struct argp_option options[] = {
1816
915
mc.priority = arg;
1818
917
case 131: /* --delay */
1820
delay = strtof(arg, &tmp);
1821
if(errno != 0 or tmp == arg or *tmp != '\0'){
1822
argp_error(state, "Bad delay");
1824
case 132: /* --retry */
1826
retry_interval = strtod(arg, &tmp);
1827
if(errno != 0 or tmp == arg or *tmp != '\0'
1828
or (retry_interval * 1000) > INT_MAX
1829
or retry_interval < 0){
1830
argp_error(state, "Bad retry interval");
1833
case 133: /* --network-hook-dir */
1837
* These reproduce what we would get without ARGP_NO_HELP
1839
case '?': /* --help */
1840
argp_state_help(state, state->out_stream,
1841
(ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
1842
& ~(unsigned int)ARGP_HELP_EXIT_OK);
1843
case -3: /* --usage */
1844
argp_state_help(state, state->out_stream,
1845
ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1846
case 'V': /* --version */
1847
fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1848
exit(argp_err_exit_status);
918
ret = sscanf(arg, "%lf%n", &delay, &numchars);
919
if(ret < 1 or arg[numchars] != '\0'){
920
fprintf(stderr, "Bad delay\n");
1851
929
return ARGP_ERR_UNKNOWN;
1856
934
struct argp argp = { .options = options, .parser = parse_opt,
1858
936
.doc = "Mandos client -- Get and decrypt"
1859
937
" passwords from a Mandos server" };
1860
ret = argp_parse(&argp, argc, argv,
1861
ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
1868
perror_plus("argp_parse");
1869
exitcode = EX_OSERR;
1872
exitcode = EX_USAGE;
938
ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
939
if(ret == ARGP_ERR_UNKNOWN){
940
fprintf(stderr, "Unknown error while parsing arguments\n");
941
exitcode = EXIT_FAILURE;
946
/* If the interface is down, bring it up */
1878
/* Work around Debian bug #633582:
1879
<http://bugs.debian.org/633582> */
1881
/* Re-raise priviliges */
1882
if(raise_privileges() == 0){
1885
if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1886
int seckey_fd = open(seckey, O_RDONLY);
1887
if(seckey_fd == -1){
1888
perror_plus("open");
1890
ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1892
perror_plus("fstat");
1894
if(S_ISREG(st.st_mode)
1895
and st.st_uid == 0 and st.st_gid == 0){
1896
ret = fchown(seckey_fd, uid, gid);
1898
perror_plus("fchown");
1902
TEMP_FAILURE_RETRY(close(seckey_fd));
1906
if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1907
int pubkey_fd = open(pubkey, O_RDONLY);
1908
if(pubkey_fd == -1){
1909
perror_plus("open");
1911
ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1913
perror_plus("fstat");
1915
if(S_ISREG(st.st_mode)
1916
and st.st_uid == 0 and st.st_gid == 0){
1917
ret = fchown(pubkey_fd, uid, gid);
1919
perror_plus("fchown");
1923
TEMP_FAILURE_RETRY(close(pubkey_fd));
1927
/* Lower privileges */
1931
perror_plus("seteuid");
1936
/* Run network hooks */
1937
if(not run_network_hooks("start", interface, delay)){
1942
avahi_set_log_function(empty_log);
1945
if(interface[0] == '\0'){
1946
struct dirent **direntries;
1947
/* First look for interfaces that are up */
1948
ret = scandir(sys_class_net, &direntries, up_interface,
1951
/* No up interfaces, look for any good interfaces */
1953
ret = scandir(sys_class_net, &direntries, good_interface,
1957
/* Pick the first interface returned */
1958
interface = strdup(direntries[0]->d_name);
1960
fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1962
if(interface == NULL){
1963
perror_plus("malloc");
949
/* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
950
messages to mess up the prompt */
951
ret = klogctl(8, NULL, 5);
957
sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
960
exitcode = EXIT_FAILURE;
962
ret = klogctl(7, NULL, 0);
969
strcpy(network.ifr_name, interface);
970
ret = ioctl(sd, SIOCGIFFLAGS, &network);
972
perror("ioctl SIOCGIFFLAGS");
974
ret = klogctl(7, NULL, 0);
979
exitcode = EXIT_FAILURE;
982
if((network.ifr_flags & IFF_UP) == 0){
983
network.ifr_flags |= IFF_UP;
984
ret = ioctl(sd, SIOCSIFFLAGS, &network);
986
perror("ioctl SIOCSIFFLAGS");
1965
987
exitcode = EXIT_FAILURE;
989
ret = klogctl(7, NULL, 0);
1971
fprintf_plus(stderr, "Could not find a network interface\n");
1972
exitcode = EXIT_FAILURE;
1977
/* Initialize Avahi early so avahi_simple_poll_quit() can be called
1978
from the signal handler */
1979
/* Initialize the pseudo-RNG for Avahi */
1980
srand((unsigned int) time(NULL));
1981
mc.simple_poll = avahi_simple_poll_new();
1982
if(mc.simple_poll == NULL){
1983
fprintf_plus(stderr,
1984
"Avahi: Failed to create simple poll object.\n");
1985
exitcode = EX_UNAVAILABLE;
1989
sigemptyset(&sigterm_action.sa_mask);
1990
ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1992
perror_plus("sigaddset");
1993
exitcode = EX_OSERR;
1996
ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1998
perror_plus("sigaddset");
1999
exitcode = EX_OSERR;
2002
ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
2004
perror_plus("sigaddset");
2005
exitcode = EX_OSERR;
2008
/* Need to check if the handler is SIG_IGN before handling:
2009
| [[info:libc:Initial Signal Actions]] |
2010
| [[info:libc:Basic Signal Handling]] |
2012
ret = sigaction(SIGINT, NULL, &old_sigterm_action);
2014
perror_plus("sigaction");
2017
if(old_sigterm_action.sa_handler != SIG_IGN){
2018
ret = sigaction(SIGINT, &sigterm_action, NULL);
2020
perror_plus("sigaction");
2021
exitcode = EX_OSERR;
2025
ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
2027
perror_plus("sigaction");
2030
if(old_sigterm_action.sa_handler != SIG_IGN){
2031
ret = sigaction(SIGHUP, &sigterm_action, NULL);
2033
perror_plus("sigaction");
2034
exitcode = EX_OSERR;
2038
ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
2040
perror_plus("sigaction");
2043
if(old_sigterm_action.sa_handler != SIG_IGN){
2044
ret = sigaction(SIGTERM, &sigterm_action, NULL);
2046
perror_plus("sigaction");
2047
exitcode = EX_OSERR;
2052
/* If the interface is down, bring it up */
2053
if((interface[0] != '\0') and (strcmp(interface, "none") != 0)){
2054
ret = bring_up_interface(interface, delay);
2057
perror_plus("Failed to bring up interface");
2065
ret = init_gnutls_global(pubkey, seckey);
2067
fprintf_plus(stderr, "init_gnutls_global failed\n");
2068
exitcode = EX_UNAVAILABLE;
997
/* sleep checking until interface is running */
998
for(int i=0; i < delay * 4; i++){
999
ret = ioctl(sd, SIOCGIFFLAGS, &network);
1001
perror("ioctl SIOCGIFFLAGS");
1002
} else if(network.ifr_flags & IFF_RUNNING){
1005
struct timespec sleeptime = { .tv_nsec = 250000000 };
1006
ret = nanosleep(&sleeptime, NULL);
1007
if(ret == -1 and errno != EINTR){
1008
perror("nanosleep");
1011
ret = (int)TEMP_FAILURE_RETRY(close(sd));
1016
/* Restores kernel loglevel to default */
1017
ret = klogctl(7, NULL, 0);
1037
ret = init_gnutls_global(&mc, pubkey, seckey);
1039
fprintf(stderr, "init_gnutls_global failed\n");
1040
exitcode = EXIT_FAILURE;
2071
1043
gnutls_initialized = true;
2078
1046
if(mkdtemp(tempdir) == NULL){
2079
perror_plus("mkdtemp");
2082
1050
tempdir_created = true;
2088
if(not init_gpgme(pubkey, seckey, tempdir)){
2089
fprintf_plus(stderr, "init_gpgme failed\n");
2090
exitcode = EX_UNAVAILABLE;
1052
if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
1053
fprintf(stderr, "init_gpgme failed\n");
1054
exitcode = EXIT_FAILURE;
2093
1057
gpgme_initialized = true;
1060
if_index = (AvahiIfIndex) if_nametoindex(interface);
1062
fprintf(stderr, "No such interface: \"%s\"\n", interface);
1063
exitcode = EXIT_FAILURE;
2254
1179
gpgme_release(mc.ctx);
2257
/* Cleans up the circular linked list of Mandos servers the client
2259
if(mc.current_server != NULL){
2260
mc.current_server->prev->next = NULL;
2261
while(mc.current_server != NULL){
2262
server *next = mc.current_server->next;
2263
free(mc.current_server);
2264
mc.current_server = next;
2268
/* Run network hooks */
2269
run_network_hooks("stop", interface, delay);
2271
/* Re-raise priviliges */
2275
/* Take down the network interface */
2276
if(take_down_interface and geteuid() == 0){
2277
ret = ioctl(sd, SIOCGIFFLAGS, &network);
2279
perror_plus("ioctl SIOCGIFFLAGS");
2280
} else if(network.ifr_flags & IFF_UP){
2281
network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2282
ret = ioctl(sd, SIOCSIFFLAGS, &network);
2284
perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
2287
ret = (int)TEMP_FAILURE_RETRY(close(sd));
2289
perror_plus("close");
2293
/* Lower privileges permanently */
2297
perror_plus("setuid");
2300
/* Removes the GPGME temp directory and all files inside */
1182
/* Removes the temp directory used by GPGME */
2301
1183
if(tempdir_created){
2302
struct dirent **direntries = NULL;
2303
struct dirent *direntry = NULL;
2304
int numentries = scandir(tempdir, &direntries, notdotentries,
2306
if (numentries > 0){
2307
for(int i = 0; i < numentries; i++){
2308
direntry = direntries[i];
1185
struct dirent *direntry;
1186
d = opendir(tempdir);
1188
if(errno != ENOENT){
1193
direntry = readdir(d);
1194
if(direntry == NULL){
1197
/* Skip "." and ".." */
1198
if(direntry->d_name[0] == '.'
1199
and (direntry->d_name[1] == '\0'
1200
or (direntry->d_name[1] == '.'
1201
and direntry->d_name[2] == '\0'))){
2309
1204
char *fullname = NULL;
2310
1205
ret = asprintf(&fullname, "%s/%s", tempdir,
2311
1206
direntry->d_name);
2313
perror_plus("asprintf");
2316
1211
ret = remove(fullname);
2318
fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
1213
fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
2321
1216
free(fullname);
2325
/* need to clean even if 0 because man page doesn't specify */
2327
if (numentries == -1){
2328
perror_plus("scandir");
2330
1220
ret = rmdir(tempdir);
2331
1221
if(ret == -1 and errno != ENOENT){
2332
perror_plus("rmdir");
2337
sigemptyset(&old_sigterm_action.sa_mask);
2338
old_sigterm_action.sa_handler = SIG_DFL;
2339
ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
2340
&old_sigterm_action,
2343
perror_plus("sigaction");
2346
ret = raise(signal_received);
2347
} while(ret != 0 and errno == EINTR);
2349
perror_plus("raise");
2352
TEMP_FAILURE_RETRY(pause());
2355
1226
return exitcode;