129
208
return buffer_capacity;
211
/* Add server to set of servers to retry periodically */
212
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
215
server *new_server = malloc(sizeof(server));
216
if(new_server == NULL){
217
perror_plus("malloc");
220
*new_server = (server){ .ip = strdup(ip),
222
.if_index = if_index,
224
if(new_server->ip == NULL){
225
perror_plus("strdup");
228
/* Special case of first server */
229
if (mc.current_server == NULL){
230
new_server->next = new_server;
231
new_server->prev = new_server;
232
mc.current_server = new_server;
233
/* Place the new server last in the list */
235
new_server->next = mc.current_server;
236
new_server->prev = mc.current_server->prev;
237
new_server->prev->next = new_server;
238
mc.current_server->prev = new_server;
240
ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
242
perror_plus("clock_gettime");
133
* Decrypt OpenPGP data using keyrings in HOMEDIR.
134
* Returns -1 on error
136
static ssize_t pgp_packet_decrypt (const char *cryptotext,
139
const char *homedir){
140
gpgme_data_t dh_crypto, dh_plain;
251
static bool init_gpgme(const char *seckey, const char *pubkey,
252
const char *tempdir){
142
253
gpgme_error_t rc;
144
size_t plaintext_capacity = 0;
145
ssize_t plaintext_length = 0;
146
254
gpgme_engine_info_t engine_info;
149
fprintf(stderr, "Trying to decrypt OpenPGP data\n");
257
* Helper function to insert pub and seckey to the engine keyring.
259
bool import_key(const char *filename){
262
gpgme_data_t pgp_data;
264
fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
270
rc = gpgme_data_new_from_fd(&pgp_data, fd);
271
if(rc != GPG_ERR_NO_ERROR){
272
fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
273
gpgme_strsource(rc), gpgme_strerror(rc));
277
rc = gpgme_op_import(mc.ctx, pgp_data);
278
if(rc != GPG_ERR_NO_ERROR){
279
fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
280
gpgme_strsource(rc), gpgme_strerror(rc));
284
ret = (int)TEMP_FAILURE_RETRY(close(fd));
286
perror_plus("close");
288
gpgme_data_release(pgp_data);
293
fprintf_plus(stderr, "Initializing GPGME\n");
153
297
gpgme_check_version(NULL);
154
298
rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
155
if (rc != GPG_ERR_NO_ERROR){
156
fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
157
gpgme_strsource(rc), gpgme_strerror(rc));
299
if(rc != GPG_ERR_NO_ERROR){
300
fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
301
gpgme_strsource(rc), gpgme_strerror(rc));
161
305
/* Set GPGME home directory for the OpenPGP engine only */
162
rc = gpgme_get_engine_info (&engine_info);
163
if (rc != GPG_ERR_NO_ERROR){
164
fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
165
gpgme_strsource(rc), gpgme_strerror(rc));
306
rc = gpgme_get_engine_info(&engine_info);
307
if(rc != GPG_ERR_NO_ERROR){
308
fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
309
gpgme_strsource(rc), gpgme_strerror(rc));
168
312
while(engine_info != NULL){
169
313
if(engine_info->protocol == GPGME_PROTOCOL_OpenPGP){
170
314
gpgme_set_engine_info(GPGME_PROTOCOL_OpenPGP,
171
engine_info->file_name, homedir);
315
engine_info->file_name, tempdir);
174
318
engine_info = engine_info->next;
176
320
if(engine_info == NULL){
177
fprintf(stderr, "Could not set GPGME home dir to %s\n", homedir);
321
fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
326
/* Create new GPGME "context" */
327
rc = gpgme_new(&(mc.ctx));
328
if(rc != GPG_ERR_NO_ERROR){
329
fprintf_plus(stderr, "Mandos plugin mandos-client: "
330
"bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
335
if(not import_key(pubkey) or not import_key(seckey)){
343
* Decrypt OpenPGP data.
344
* Returns -1 on error
346
static ssize_t pgp_packet_decrypt(const char *cryptotext,
349
gpgme_data_t dh_crypto, dh_plain;
352
size_t plaintext_capacity = 0;
353
ssize_t plaintext_length = 0;
356
fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
181
359
/* Create new GPGME data buffer from memory cryptotext */
182
360
rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
184
if (rc != GPG_ERR_NO_ERROR){
185
fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
186
gpgme_strsource(rc), gpgme_strerror(rc));
362
if(rc != GPG_ERR_NO_ERROR){
363
fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
364
gpgme_strsource(rc), gpgme_strerror(rc));
190
368
/* Create new empty GPGME data buffer for the plaintext */
191
369
rc = gpgme_data_new(&dh_plain);
192
if (rc != GPG_ERR_NO_ERROR){
193
fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
194
gpgme_strsource(rc), gpgme_strerror(rc));
370
if(rc != GPG_ERR_NO_ERROR){
371
fprintf_plus(stderr, "Mandos plugin mandos-client: "
372
"bad gpgme_data_new: %s: %s\n",
373
gpgme_strsource(rc), gpgme_strerror(rc));
195
374
gpgme_data_release(dh_crypto);
199
/* Create new GPGME "context" */
200
rc = gpgme_new(&ctx);
201
if (rc != GPG_ERR_NO_ERROR){
202
fprintf(stderr, "bad gpgme_new: %s: %s\n",
203
gpgme_strsource(rc), gpgme_strerror(rc));
204
plaintext_length = -1;
208
378
/* Decrypt data from the cryptotext data buffer to the plaintext
210
rc = gpgme_op_decrypt(ctx, dh_crypto, dh_plain);
211
if (rc != GPG_ERR_NO_ERROR){
212
fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
213
gpgme_strsource(rc), gpgme_strerror(rc));
380
rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
381
if(rc != GPG_ERR_NO_ERROR){
382
fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
383
gpgme_strsource(rc), gpgme_strerror(rc));
214
384
plaintext_length = -1;
219
fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
223
gpgme_decrypt_result_t result;
224
result = gpgme_op_decrypt_result(ctx);
226
fprintf(stderr, "gpgme_op_decrypt_result failed\n");
228
fprintf(stderr, "Unsupported algorithm: %s\n",
229
result->unsupported_algorithm);
230
fprintf(stderr, "Wrong key usage: %u\n",
231
result->wrong_key_usage);
232
if(result->file_name != NULL){
233
fprintf(stderr, "File name: %s\n", result->file_name);
235
gpgme_recipient_t recipient;
236
recipient = result->recipients;
386
gpgme_decrypt_result_t result;
387
result = gpgme_op_decrypt_result(mc.ctx);
389
fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
391
fprintf_plus(stderr, "Unsupported algorithm: %s\n",
392
result->unsupported_algorithm);
393
fprintf_plus(stderr, "Wrong key usage: %u\n",
394
result->wrong_key_usage);
395
if(result->file_name != NULL){
396
fprintf_plus(stderr, "File name: %s\n", result->file_name);
398
gpgme_recipient_t recipient;
399
recipient = result->recipients;
238
400
while(recipient != NULL){
239
fprintf(stderr, "Public key algorithm: %s\n",
240
gpgme_pubkey_algo_name(recipient->pubkey_algo));
241
fprintf(stderr, "Key ID: %s\n", recipient->keyid);
242
fprintf(stderr, "Secret key available: %s\n",
243
recipient->status == GPG_ERR_NO_SECKEY
401
fprintf_plus(stderr, "Public key algorithm: %s\n",
402
gpgme_pubkey_algo_name
403
(recipient->pubkey_algo));
404
fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
405
fprintf_plus(stderr, "Secret key available: %s\n",
406
recipient->status == GPG_ERR_NO_SECKEY
245
408
recipient = recipient->next;
416
fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
251
419
/* Seek back to the beginning of the GPGME plaintext data buffer */
252
if (gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET) == -1){
253
perror("pgpme_data_seek");
420
if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
421
perror_plus("gpgme_data_seek");
254
422
plaintext_length = -1;
255
423
goto decrypt_end;
258
426
*plaintext = NULL;
260
plaintext_capacity = adjustbuffer(plaintext,
261
(size_t)plaintext_length,
263
if (plaintext_capacity == 0){
264
perror("adjustbuffer");
265
plaintext_length = -1;
428
plaintext_capacity = incbuffer(plaintext,
429
(size_t)plaintext_length,
431
if(plaintext_capacity == 0){
432
perror_plus("incbuffer");
433
plaintext_length = -1;
269
437
ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
271
439
/* Print the data, if any */
277
perror("gpgme_data_read");
445
perror_plus("gpgme_data_read");
278
446
plaintext_length = -1;
279
447
goto decrypt_end;
281
449
plaintext_length += ret;
285
fprintf(stderr, "Decrypted password is: ");
453
fprintf_plus(stderr, "Decrypted password is: ");
286
454
for(ssize_t i = 0; i < plaintext_length; i++){
287
455
fprintf(stderr, "%02hhX ", (*plaintext)[i]);
433
619
__attribute__((unused)) const char *txt){}
435
621
/* Called when a Mandos server is found */
436
static int start_mandos_communication(const char *ip, uint16_t port,
622
static int start_mandos_communication(const char *ip, in_port_t port,
437
623
AvahiIfIndex if_index,
440
union { struct sockaddr in; struct sockaddr_in6 in6; } to;
625
int ret, tcp_sd = -1;
628
struct sockaddr_in in;
629
struct sockaddr_in6 in6;
441
631
char *buffer = NULL;
442
char *decrypted_buffer;
632
char *decrypted_buffer = NULL;
443
633
size_t buffer_length = 0;
444
634
size_t buffer_capacity = 0;
445
ssize_t decrypted_buffer_size;
448
char interface[IF_NAMESIZE];
449
637
gnutls_session_t session;
451
ret = init_gnutls_session (mc, &session);
457
fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
461
tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
468
if(if_indextoname((unsigned int)if_index, interface) == NULL){
469
perror("if_indextoname");
472
fprintf(stderr, "Binding to interface %s\n", interface);
475
memset(&to,0,sizeof(to)); /* Spurious warning */
476
to.in6.sin6_family = AF_INET6;
477
/* It would be nice to have a way to detect if we were passed an
478
IPv4 address here. Now we assume an IPv6 address. */
479
ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
638
int pf; /* Protocol family */
655
fprintf_plus(stderr, "Bad address family: %d\n", af);
660
ret = init_gnutls_session(&session);
666
fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
667
PRIuMAX "\n", ip, (uintmax_t)port);
670
tcp_sd = socket(pf, SOCK_STREAM, 0);
673
perror_plus("socket");
683
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);
693
perror_plus("inet_pton");
485
fprintf(stderr, "Bad address: %s\n", ip);
488
to.in6.sin6_port = htons(port); /* Spurious warning */
699
fprintf_plus(stderr, "Bad address: %s\n", ip);
704
to.in6.sin6_port = htons(port);
705
if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
706
(&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
708
if(if_index == AVAHI_IF_UNSPEC){
709
fprintf_plus(stderr, "An IPv6 link-local address is"
710
" incomplete without a network interface\n");
714
/* Set the network interface number as scope */
715
to.in6.sin6_scope_id = (uint32_t)if_index;
718
to.in.sin_port = htons(port); /* Spurious warnings from
720
-Wunreachable-code */
490
to.in6.sin6_scope_id = (uint32_t)if_index;
493
fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
495
char addrstr[INET6_ADDRSTRLEN] = "";
496
if(inet_ntop(to.in6.sin6_family, &(to.in6.sin6_addr), addrstr,
497
sizeof(addrstr)) == NULL){
729
if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
730
char interface[IF_NAMESIZE];
731
if(if_indextoname((unsigned int)if_index, interface) == NULL){
732
perror_plus("if_indextoname");
734
fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
735
"\n", ip, interface, (uintmax_t)port);
738
fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
739
ip, (uintmax_t)port);
741
char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
742
INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
745
pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
748
pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
752
perror_plus("inet_ntop");
500
754
if(strcmp(addrstr, ip) != 0){
501
fprintf(stderr, "Canonical address form: %s\n", addrstr);
755
fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
506
ret = connect(tcp_sd, &to.in, sizeof(to));
766
ret = connect(tcp_sd, &to.in6, sizeof(to));
768
ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
771
if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
773
perror_plus("connect");
512
784
const char *out = mandos_protocol_version;
515
787
size_t out_size = strlen(out);
516
ret = TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
517
out_size - written));
788
ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
789
out_size - written));
792
perror_plus("write");
523
796
written += (size_t)ret;
524
797
if(written < out_size){
527
if (out == mandos_protocol_version){
800
if(out == mandos_protocol_version){
537
fprintf(stderr, "Establishing TLS session with %s\n", ip);
540
gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) tcp_sd);
543
ret = gnutls_handshake (session);
815
fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
823
/* This casting via intptr_t is to eliminate warning about casting
824
an int to a pointer type. This is exactly how the GnuTLS Guile
825
function "set-session-transport-fd!" does it. */
826
gnutls_transport_set_ptr(session,
827
(gnutls_transport_ptr_t)(intptr_t)tcp_sd);
835
ret = gnutls_handshake(session);
544
840
} while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
546
if (ret != GNUTLS_E_SUCCESS){
842
if(ret != GNUTLS_E_SUCCESS){
548
fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
844
fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
555
851
/* Read OpenPGP packet that contains the wanted password */
558
fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
854
fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
563
buffer_capacity = adjustbuffer(&buffer, buffer_length,
565
if (buffer_capacity == 0){
566
perror("adjustbuffer");
571
ret = gnutls_record_recv(session, buffer+buffer_length,
865
buffer_capacity = incbuffer(&buffer, buffer_length,
867
if(buffer_capacity == 0){
869
perror_plus("incbuffer");
879
sret = gnutls_record_recv(session, buffer+buffer_length,
578
886
case GNUTLS_E_INTERRUPTED:
579
887
case GNUTLS_E_AGAIN:
581
889
case GNUTLS_E_REHANDSHAKE:
583
ret = gnutls_handshake (session);
891
ret = gnutls_handshake(session);
584
897
} while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
586
fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
899
fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
593
fprintf(stderr, "Unknown error while reading data from"
594
" encrypted session with Mandos server\n");
596
gnutls_bye (session, GNUTLS_SHUT_RDWR);
907
fprintf_plus(stderr, "Unknown error while reading data from"
908
" encrypted session with Mandos server\n");
909
gnutls_bye(session, GNUTLS_SHUT_RDWR);
600
buffer_length += (size_t) ret;
914
buffer_length += (size_t) sret;
605
fprintf(stderr, "Closing TLS session\n");
608
gnutls_bye (session, GNUTLS_SHUT_RDWR);
610
if (buffer_length > 0){
611
decrypted_buffer_size = pgp_packet_decrypt(buffer,
615
if (decrypted_buffer_size >= 0){
919
fprintf_plus(stderr, "Closing TLS session\n");
928
ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
933
} while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
935
if(buffer_length > 0){
936
ssize_t decrypted_buffer_size;
937
decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
939
if(decrypted_buffer_size >= 0){
617
942
while(written < (size_t) decrypted_buffer_size){
618
ret = (int)fwrite (decrypted_buffer + written, 1,
619
(size_t)decrypted_buffer_size - written,
948
ret = (int)fwrite(decrypted_buffer + written, 1,
949
(size_t)decrypted_buffer_size - written,
621
951
if(ret == 0 and ferror(stdout)){
623
fprintf(stderr, "Error writing encrypted data: %s\n",
954
fprintf_plus(stderr, "Error writing encrypted data: %s\n",
629
960
written += (size_t)ret;
631
free(decrypted_buffer);
637
966
/* Shutdown procedure */
642
gnutls_deinit (session);
971
free(decrypted_buffer);
974
ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
980
perror_plus("close");
982
gnutls_deinit(session);
646
992
static void resolve_callback(AvahiSServiceResolver *r,
647
993
AvahiIfIndex interface,
648
AVAHI_GCC_UNUSED AvahiProtocol protocol,
649
995
AvahiResolverEvent event,
650
996
const char *name,
651
997
const char *type,
734
1099
case AVAHI_BROWSER_ALL_FOR_NOW:
735
1100
case AVAHI_BROWSER_CACHE_EXHAUSTED:
737
fprintf(stderr, "No Mandos server found, still searching...\n");
1102
fprintf_plus(stderr, "No Mandos server found, still"
743
/* Combines file name and path and returns the malloced new
744
string. some sane checks could/should be added */
745
static const char *combinepath(const char *first, const char *second){
746
size_t f_len = strlen(first);
747
size_t s_len = strlen(second);
748
char *tmp = malloc(f_len + s_len + 2);
753
memcpy(tmp, first, f_len); /* Spurious warning */
757
memcpy(tmp + f_len + 1, second, s_len); /* Spurious warning */
759
tmp[f_len + 1 + s_len] = '\0';
1109
/* Signal handler that stops main loop after SIGTERM */
1110
static void handle_sigterm(int sig){
1115
signal_received = sig;
1116
int old_errno = errno;
1117
/* set main loop to exit */
1118
if(simple_poll != NULL){
1119
avahi_simple_poll_quit(simple_poll);
1124
bool get_flags(const char *ifname, struct ifreq *ifr){
1128
int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1131
perror_plus("socket");
1135
strcpy(ifr->ifr_name, ifname);
1136
ret = ioctl(s, SIOCGIFFLAGS, ifr);
1140
perror_plus("ioctl SIOCGIFFLAGS");
1148
bool good_flags(const char *ifname, const struct ifreq *ifr){
1150
/* Reject the loopback device */
1151
if(ifr->ifr_flags & IFF_LOOPBACK){
1153
fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1158
/* Accept point-to-point devices only if connect_to is specified */
1159
if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1161
fprintf_plus(stderr, "Accepting point-to-point interface"
1162
" \"%s\"\n", ifname);
1166
/* Otherwise, reject non-broadcast-capable devices */
1167
if(not (ifr->ifr_flags & IFF_BROADCAST)){
1169
fprintf_plus(stderr, "Rejecting non-broadcast interface"
1170
" \"%s\"\n", ifname);
1174
/* Reject non-ARP interfaces (including dummy interfaces) */
1175
if(ifr->ifr_flags & IFF_NOARP){
1177
fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1183
/* Accept this device */
1185
fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1191
* This function determines if a directory entry in /sys/class/net
1192
* corresponds to an acceptable network device.
1193
* (This function is passed to scandir(3) as a filter function.)
1195
int good_interface(const struct dirent *if_entry){
1196
if(if_entry->d_name[0] == '.'){
1201
if(not get_flags(if_entry->d_name, &ifr)){
1203
fprintf_plus(stderr, "Failed to get flags for interface "
1204
"\"%s\"\n", if_entry->d_name);
1209
if(not good_flags(if_entry->d_name, &ifr)){
1216
* This function determines if a network interface is up.
1218
bool interface_is_up(const char *interface){
1220
if(not get_flags(interface, &ifr)){
1222
fprintf_plus(stderr, "Failed to get flags for interface "
1223
"\"%s\"\n", interface);
1228
return (bool)(ifr.ifr_flags & IFF_UP);
1232
* This function determines if a network interface is running
1234
bool interface_is_running(const char *interface){
1236
if(not get_flags(interface, &ifr)){
1238
fprintf_plus(stderr, "Failed to get flags for interface "
1239
"\"%s\"\n", interface);
1244
return (bool)(ifr.ifr_flags & IFF_RUNNING);
1247
int notdotentries(const struct dirent *direntry){
1248
/* Skip "." and ".." */
1249
if(direntry->d_name[0] == '.'
1250
and (direntry->d_name[1] == '\0'
1251
or (direntry->d_name[1] == '.'
1252
and direntry->d_name[2] == '\0'))){
1258
/* Is this directory entry a runnable program? */
1259
int runnable_hook(const struct dirent *direntry){
1264
if((direntry->d_name)[0] == '\0'){
1269
sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1270
"abcdefghijklmnopqrstuvwxyz"
1273
if((direntry->d_name)[sret] != '\0'){
1274
/* Contains non-allowed characters */
1276
fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
1282
char *fullname = NULL;
1283
ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1285
perror_plus("asprintf");
1289
ret = stat(fullname, &st);
1292
perror_plus("Could not stat hook");
1296
if(not (S_ISREG(st.st_mode))){
1297
/* Not a regular file */
1299
fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
1304
if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1305
/* Not executable */
1307
fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
1313
fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
1319
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1321
struct timespec now;
1322
struct timespec waited_time;
1323
intmax_t block_time;
1326
if(mc.current_server == NULL){
1328
fprintf_plus(stderr, "Wait until first server is found."
1331
ret = avahi_simple_poll_iterate(s, -1);
1334
fprintf_plus(stderr, "Check current_server if we should run"
1337
/* the current time */
1338
ret = clock_gettime(CLOCK_MONOTONIC, &now);
1340
perror_plus("clock_gettime");
1343
/* Calculating in ms how long time between now and server
1344
who we visted longest time ago. Now - last seen. */
1345
waited_time.tv_sec = (now.tv_sec
1346
- mc.current_server->last_seen.tv_sec);
1347
waited_time.tv_nsec = (now.tv_nsec
1348
- mc.current_server->last_seen.tv_nsec);
1349
/* total time is 10s/10,000ms.
1350
Converting to s from ms by dividing by 1,000,
1351
and ns to ms by dividing by 1,000,000. */
1352
block_time = ((retry_interval
1353
- ((intmax_t)waited_time.tv_sec * 1000))
1354
- ((intmax_t)waited_time.tv_nsec / 1000000));
1357
fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1361
if(block_time <= 0){
1362
ret = start_mandos_communication(mc.current_server->ip,
1363
mc.current_server->port,
1364
mc.current_server->if_index,
1365
mc.current_server->af);
1367
avahi_simple_poll_quit(simple_poll);
1370
ret = clock_gettime(CLOCK_MONOTONIC,
1371
&mc.current_server->last_seen);
1373
perror_plus("clock_gettime");
1376
mc.current_server = mc.current_server->next;
1377
block_time = 0; /* Call avahi to find new Mandos
1378
servers, but don't block */
1381
ret = avahi_simple_poll_iterate(s, (int)block_time);
1384
if (ret > 0 or errno != EINTR){
1385
return (ret != 1) ? ret : 0;
1391
/* Set effective uid to 0, return errno */
1392
error_t raise_privileges(void){
1393
error_t old_errno = errno;
1394
error_t ret_errno = 0;
1395
if(seteuid(0) == -1){
1397
perror_plus("seteuid");
1403
/* Set effective and real user ID to 0. Return errno. */
1404
error_t raise_privileges_permanently(void){
1405
error_t old_errno = errno;
1406
error_t ret_errno = raise_privileges();
1411
if(setuid(0) == -1){
1413
perror_plus("seteuid");
1419
/* Set effective user ID to unprivileged saved user ID */
1420
error_t lower_privileges(void){
1421
error_t old_errno = errno;
1422
error_t ret_errno = 0;
1423
if(seteuid(uid) == -1){
1425
perror_plus("seteuid");
1431
/* Lower privileges permanently */
1432
error_t lower_privileges_permanently(void){
1433
error_t old_errno = errno;
1434
error_t ret_errno = 0;
1435
if(setuid(uid) == -1){
1437
perror_plus("setuid");
1443
bool run_network_hooks(const char *mode, const char *interface,
1445
struct dirent **direntries;
1446
struct dirent *direntry;
1448
int numhooks = scandir(hookdir, &direntries, runnable_hook,
1451
if(errno == ENOENT){
1453
fprintf_plus(stderr, "Network hook directory \"%s\" not"
1454
" found\n", hookdir);
1457
perror_plus("scandir");
1460
int devnull = open("/dev/null", O_RDONLY);
1461
for(int i = 0; i < numhooks; i++){
1462
direntry = direntries[i];
1463
char *fullname = NULL;
1464
ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1466
perror_plus("asprintf");
1470
fprintf_plus(stderr, "Running network hook \"%s\"\n",
1473
pid_t hook_pid = fork();
1476
/* Raise privileges */
1477
raise_privileges_permanently();
1482
perror_plus("setgid");
1484
/* Reset supplementary groups */
1486
ret = setgroups(0, NULL);
1488
perror_plus("setgroups");
1490
dup2(devnull, STDIN_FILENO);
1492
dup2(STDERR_FILENO, STDOUT_FILENO);
1493
ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1495
perror_plus("setenv");
1498
ret = setenv("DEVICE", interface, 1);
1500
perror_plus("setenv");
1503
ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1505
perror_plus("setenv");
1508
ret = setenv("MODE", mode, 1);
1510
perror_plus("setenv");
1514
ret = asprintf(&delaystring, "%f", delay);
1516
perror_plus("asprintf");
1519
ret = setenv("DELAY", delaystring, 1);
1522
perror_plus("setenv");
1526
if(connect_to != NULL){
1527
ret = setenv("CONNECT", connect_to, 1);
1529
perror_plus("setenv");
1533
if(execl(fullname, direntry->d_name, mode, NULL) == -1){
1534
perror_plus("execl");
1535
_exit(EXIT_FAILURE);
1539
if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1540
perror_plus("waitpid");
1544
if(WIFEXITED(status)){
1545
if(WEXITSTATUS(status) != 0){
1546
fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1547
" with status %d\n", direntry->d_name,
1548
WEXITSTATUS(status));
1552
} else if(WIFSIGNALED(status)){
1553
fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1554
" signal %d\n", direntry->d_name,
1559
fprintf_plus(stderr, "Warning: network hook \"%s\""
1560
" crashed\n", direntry->d_name);
1567
fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1576
error_t bring_up_interface(const char *const interface,
1579
error_t old_errno = errno;
1580
error_t ret_errno = 0;
1581
int ret, ret_setflags;
1582
struct ifreq network;
1583
unsigned int if_index = if_nametoindex(interface);
1585
fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1595
if(not interface_is_up(interface)){
1596
if(not get_flags(interface, &network) and debug){
1598
fprintf_plus(stderr, "Failed to get flags for interface "
1599
"\"%s\"\n", interface);
1602
network.ifr_flags |= IFF_UP;
1604
sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1607
perror_plus("socket");
1619
fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
1623
/* Raise priviliges */
1627
/* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1628
messages about the network interface to mess up the prompt */
1629
int ret_linux = klogctl(8, NULL, 5);
1630
bool restore_loglevel = true;
1631
if(ret_linux == -1){
1632
restore_loglevel = false;
1633
perror_plus("klogctl");
1635
#endif /* __linux__ */
1636
ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1639
if(restore_loglevel){
1640
ret_linux = klogctl(7, NULL, 0);
1641
if(ret_linux == -1){
1642
perror_plus("klogctl");
1645
#endif /* __linux__ */
1647
/* Lower privileges */
1650
/* Close the socket */
1651
ret = (int)TEMP_FAILURE_RETRY(close(sd));
1653
perror_plus("close");
1656
if(ret_setflags == -1){
1658
perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1663
fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
1667
/* Sleep checking until interface is running.
1668
Check every 0.25s, up to total time of delay */
1669
for(int i=0; i < delay * 4; i++){
1670
if(interface_is_running(interface)){
1673
struct timespec sleeptime = { .tv_nsec = 250000000 };
1674
ret = nanosleep(&sleeptime, NULL);
1675
if(ret == -1 and errno != EINTR){
1676
perror_plus("nanosleep");
1684
error_t take_down_interface(const char *const interface){
1686
error_t old_errno = errno;
1687
error_t ret_errno = 0;
1688
int ret, ret_setflags;
1689
struct ifreq network;
1690
unsigned int if_index = if_nametoindex(interface);
1692
fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1696
if(interface_is_up(interface)){
1697
if(not get_flags(interface, &network) and debug){
1699
fprintf_plus(stderr, "Failed to get flags for interface "
1700
"\"%s\"\n", interface);
1703
network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1705
sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1708
perror_plus("socket");
1714
fprintf_plus(stderr, "Taking down interface \"%s\"\n",
1718
/* Raise priviliges */
1721
ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1724
/* Lower privileges */
1727
/* Close the socket */
1728
ret = (int)TEMP_FAILURE_RETRY(close(sd));
1730
perror_plus("close");
1733
if(ret_setflags == -1){
1735
perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1740
fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
764
1748
int main(int argc, char *argv[]){
765
AvahiSServiceBrowser *sb = NULL;
768
int exitcode = EXIT_SUCCESS;
769
const char *interface = "eth0";
770
struct ifreq network;
774
char *connect_to = NULL;
775
AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
776
const char *pubkeyfile = "pubkey.txt";
777
const char *seckeyfile = "seckey.txt";
778
mandos_context mc = { .simple_poll = NULL, .server = NULL,
779
.dh_bits = 1024, .priority = "SECURE256"};
780
bool gnutls_initalized = false;
783
struct argp_option options[] = {
784
{ .name = "debug", .key = 128,
785
.doc = "Debug mode", .group = 3 },
786
{ .name = "connect", .key = 'c',
788
.doc = "Connect directly to a sepcified mandos server",
790
{ .name = "interface", .key = 'i',
792
.doc = "Interface that Avahi will conntect through",
794
{ .name = "keydir", .key = 'd',
796
.doc = "Directory where the openpgp keyring is",
798
{ .name = "seckey", .key = 's',
800
.doc = "Secret openpgp key for gnutls authentication",
802
{ .name = "pubkey", .key = 'p',
804
.doc = "Public openpgp key for gnutls authentication",
806
{ .name = "dh-bits", .key = 129,
808
.doc = "dh-bits to use in gnutls communication",
810
{ .name = "priority", .key = 130,
812
.doc = "GNUTLS priority", .group = 1 },
817
error_t parse_opt (int key, char *arg,
818
struct argp_state *state) {
819
/* Get the INPUT argument from `argp_parse', which we know is
820
a pointer to our plugin list pointer. */
842
mc.dh_bits = (unsigned int) strtol(arg, NULL, 10);
856
return ARGP_ERR_UNKNOWN;
861
struct argp argp = { .options = options, .parser = parse_opt,
863
.doc = "Mandos client -- Get and decrypt"
864
" passwords from mandos server" };
865
ret = argp_parse (&argp, argc, argv, 0, 0, NULL);
866
if (ret == ARGP_ERR_UNKNOWN){
867
fprintf(stderr, "Unknown error while parsing arguments\n");
868
exitcode = EXIT_FAILURE;
873
pubkeyfile = combinepath(keydir, pubkeyfile);
874
if (pubkeyfile == NULL){
875
perror("combinepath");
876
exitcode = EXIT_FAILURE;
880
seckeyfile = combinepath(keydir, seckeyfile);
881
if (seckeyfile == NULL){
882
perror("combinepath");
883
exitcode = EXIT_FAILURE;
887
ret = init_gnutls_global(&mc, pubkeyfile, seckeyfile);
889
fprintf(stderr, "init_gnutls_global failed\n");
890
exitcode = EXIT_FAILURE;
893
gnutls_initalized = true;
896
/* If the interface is down, bring it up */
898
sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
901
exitcode = EXIT_FAILURE;
904
strcpy(network.ifr_name, interface); /* Spurious warning */
905
ret = ioctl(sd, SIOCGIFFLAGS, &network);
1749
AvahiSServiceBrowser *sb = NULL;
1754
int exitcode = EXIT_SUCCESS;
1755
char *interfaces = NULL;
1756
size_t interfaces_size = 0;
1757
char *interfaces_to_take_down = NULL;
1758
size_t interfaces_to_take_down_size = 0;
1759
char tempdir[] = "/tmp/mandosXXXXXX";
1760
bool tempdir_created = false;
1761
AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1762
const char *seckey = PATHDIR "/" SECKEY;
1763
const char *pubkey = PATHDIR "/" PUBKEY;
1764
char *interfaces_hooks = NULL;
1765
size_t interfaces_hooks_size = 0;
1767
bool gnutls_initialized = false;
1768
bool gpgme_initialized = false;
1770
double retry_interval = 10; /* 10s between trying a server and
1771
retrying the same server again */
1773
struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1774
struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1779
/* Lower any group privileges we might have, just to be safe */
1783
perror_plus("setgid");
1786
/* Lower user privileges (temporarily) */
1790
perror_plus("seteuid");
1798
struct argp_option options[] = {
1799
{ .name = "debug", .key = 128,
1800
.doc = "Debug mode", .group = 3 },
1801
{ .name = "connect", .key = 'c',
1802
.arg = "ADDRESS:PORT",
1803
.doc = "Connect directly to a specific Mandos server",
1805
{ .name = "interface", .key = 'i',
1807
.doc = "Network interface that will be used to search for"
1810
{ .name = "seckey", .key = 's',
1812
.doc = "OpenPGP secret key file base name",
1814
{ .name = "pubkey", .key = 'p',
1816
.doc = "OpenPGP public key file base name",
1818
{ .name = "dh-bits", .key = 129,
1820
.doc = "Bit length of the prime number used in the"
1821
" Diffie-Hellman key exchange",
1823
{ .name = "priority", .key = 130,
1825
.doc = "GnuTLS priority string for the TLS handshake",
1827
{ .name = "delay", .key = 131,
1829
.doc = "Maximum delay to wait for interface startup",
1831
{ .name = "retry", .key = 132,
1833
.doc = "Retry interval used when denied by the Mandos server",
1835
{ .name = "network-hook-dir", .key = 133,
1837
.doc = "Directory where network hooks are located",
1840
* These reproduce what we would get without ARGP_NO_HELP
1842
{ .name = "help", .key = '?',
1843
.doc = "Give this help list", .group = -1 },
1844
{ .name = "usage", .key = -3,
1845
.doc = "Give a short usage message", .group = -1 },
1846
{ .name = "version", .key = 'V',
1847
.doc = "Print program version", .group = -1 },
1851
error_t parse_opt(int key, char *arg,
1852
struct argp_state *state){
1855
case 128: /* --debug */
1858
case 'c': /* --connect */
1861
case 'i': /* --interface */
1862
ret_errno = argz_add_sep(&interfaces, &interfaces_size, arg,
1865
argp_error(state, "%s", strerror(ret_errno));
1868
case 's': /* --seckey */
1871
case 'p': /* --pubkey */
1874
case 129: /* --dh-bits */
1876
tmpmax = strtoimax(arg, &tmp, 10);
1877
if(errno != 0 or tmp == arg or *tmp != '\0'
1878
or tmpmax != (typeof(mc.dh_bits))tmpmax){
1879
argp_error(state, "Bad number of DH bits");
1881
mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1883
case 130: /* --priority */
1886
case 131: /* --delay */
1888
delay = strtof(arg, &tmp);
1889
if(errno != 0 or tmp == arg or *tmp != '\0'){
1890
argp_error(state, "Bad delay");
1892
case 132: /* --retry */
1894
retry_interval = strtod(arg, &tmp);
1895
if(errno != 0 or tmp == arg or *tmp != '\0'
1896
or (retry_interval * 1000) > INT_MAX
1897
or retry_interval < 0){
1898
argp_error(state, "Bad retry interval");
1901
case 133: /* --network-hook-dir */
1905
* These reproduce what we would get without ARGP_NO_HELP
1907
case '?': /* --help */
1908
argp_state_help(state, state->out_stream,
1909
(ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
1910
& ~(unsigned int)ARGP_HELP_EXIT_OK);
1911
case -3: /* --usage */
1912
argp_state_help(state, state->out_stream,
1913
ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1914
case 'V': /* --version */
1915
fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1916
exit(argp_err_exit_status);
1919
return ARGP_ERR_UNKNOWN;
1924
struct argp argp = { .options = options, .parser = parse_opt,
1926
.doc = "Mandos client -- Get and decrypt"
1927
" passwords from a Mandos server" };
1928
ret = argp_parse(&argp, argc, argv,
1929
ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
1936
perror_plus("argp_parse");
1937
exitcode = EX_OSERR;
1940
exitcode = EX_USAGE;
1946
/* Work around Debian bug #633582:
1947
<http://bugs.debian.org/633582> */
1949
/* Re-raise priviliges */
1950
if(raise_privileges() == 0){
1953
if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1954
int seckey_fd = open(seckey, O_RDONLY);
1955
if(seckey_fd == -1){
1956
perror_plus("open");
1958
ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1960
perror_plus("fstat");
1962
if(S_ISREG(st.st_mode)
1963
and st.st_uid == 0 and st.st_gid == 0){
1964
ret = fchown(seckey_fd, uid, gid);
1966
perror_plus("fchown");
1970
TEMP_FAILURE_RETRY(close(seckey_fd));
1974
if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1975
int pubkey_fd = open(pubkey, O_RDONLY);
1976
if(pubkey_fd == -1){
1977
perror_plus("open");
1979
ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1981
perror_plus("fstat");
1983
if(S_ISREG(st.st_mode)
1984
and st.st_uid == 0 and st.st_gid == 0){
1985
ret = fchown(pubkey_fd, uid, gid);
1987
perror_plus("fchown");
1991
TEMP_FAILURE_RETRY(close(pubkey_fd));
1995
/* Lower privileges */
907
perror("ioctl SIOCGIFFLAGS");
908
exitcode = EXIT_FAILURE;
911
if((network.ifr_flags & IFF_UP) == 0){
912
network.ifr_flags |= IFF_UP;
913
ret = ioctl(sd, SIOCSIFFLAGS, &network);
915
perror("ioctl SIOCSIFFLAGS");
916
exitcode = EXIT_FAILURE;
936
if_index = (AvahiIfIndex) if_nametoindex(interface);
938
fprintf(stderr, "No such interface: \"%s\"\n", interface);
942
if(connect_to != NULL){
943
/* Connect directly, do not use Zeroconf */
944
/* (Mainly meant for debugging) */
945
char *address = strrchr(connect_to, ':');
947
fprintf(stderr, "No colon in address\n");
948
exitcode = EXIT_FAILURE;
952
uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
954
perror("Bad port number");
955
exitcode = EXIT_FAILURE;
959
address = connect_to;
960
ret = start_mandos_communication(address, port, if_index, &mc);
962
exitcode = EXIT_FAILURE;
964
exitcode = EXIT_SUCCESS;
970
avahi_set_log_function(empty_log);
973
/* Initialize the pseudo-RNG for Avahi */
974
srand((unsigned int) time(NULL));
976
/* Allocate main Avahi loop object */
977
mc.simple_poll = avahi_simple_poll_new();
978
if (mc.simple_poll == NULL) {
979
fprintf(stderr, "Avahi: Failed to create simple poll"
981
exitcode = EXIT_FAILURE;
986
AvahiServerConfig config;
987
/* Do not publish any local Zeroconf records */
988
avahi_server_config_init(&config);
989
config.publish_hinfo = 0;
990
config.publish_addresses = 0;
991
config.publish_workstation = 0;
992
config.publish_domain = 0;
994
/* Allocate a new server */
995
mc.server = avahi_server_new(avahi_simple_poll_get
996
(mc.simple_poll), &config, NULL,
999
/* Free the Avahi configuration data */
1000
avahi_server_config_free(&config);
1003
/* Check if creating the Avahi server object succeeded */
1004
if (mc.server == NULL) {
1005
fprintf(stderr, "Failed to create Avahi server: %s\n",
1006
avahi_strerror(error));
1007
exitcode = EXIT_FAILURE;
1011
/* Create the Avahi service browser */
1012
sb = avahi_s_service_browser_new(mc.server, if_index,
1014
"_mandos._tcp", NULL, 0,
1015
browse_callback, &mc);
1017
fprintf(stderr, "Failed to create service browser: %s\n",
1018
avahi_strerror(avahi_server_errno(mc.server)));
1019
exitcode = EXIT_FAILURE;
1023
/* Run the main loop */
1026
fprintf(stderr, "Starting Avahi loop search\n");
1029
avahi_simple_poll_loop(mc.simple_poll);
1999
perror_plus("seteuid");
2004
/* Remove empty interface names */
2006
char *interface = NULL;
2007
while((interface = argz_next(interfaces, interfaces_size,
2009
if(if_nametoindex(interface) == 0){
2010
if(interface[0] != '\0' and strcmp(interface, "none") != 0){
2011
fprintf_plus(stderr, "Not using nonexisting interface"
2012
" \"%s\"\n", interface);
2014
argz_delete(&interfaces, &interfaces_size, interface);
2020
/* Run network hooks */
2023
if(interfaces != NULL){
2024
interfaces_hooks = malloc(interfaces_size);
2025
if(interfaces_hooks == NULL){
2026
perror_plus("malloc");
2029
memcpy(interfaces_hooks, interfaces, interfaces_size);
2030
interfaces_hooks_size = interfaces_size;
2031
argz_stringify(interfaces_hooks, interfaces_hooks_size,
2034
if(not run_network_hooks("start", interfaces_hooks != NULL ?
2035
interfaces_hooks : "", delay)){
2041
avahi_set_log_function(empty_log);
2044
/* Initialize Avahi early so avahi_simple_poll_quit() can be called
2045
from the signal handler */
2046
/* Initialize the pseudo-RNG for Avahi */
2047
srand((unsigned int) time(NULL));
2048
simple_poll = avahi_simple_poll_new();
2049
if(simple_poll == NULL){
2050
fprintf_plus(stderr,
2051
"Avahi: Failed to create simple poll object.\n");
2052
exitcode = EX_UNAVAILABLE;
2056
sigemptyset(&sigterm_action.sa_mask);
2057
ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
2059
perror_plus("sigaddset");
2060
exitcode = EX_OSERR;
2063
ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
2065
perror_plus("sigaddset");
2066
exitcode = EX_OSERR;
2069
ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
2071
perror_plus("sigaddset");
2072
exitcode = EX_OSERR;
2075
/* Need to check if the handler is SIG_IGN before handling:
2076
| [[info:libc:Initial Signal Actions]] |
2077
| [[info:libc:Basic Signal Handling]] |
2079
ret = sigaction(SIGINT, NULL, &old_sigterm_action);
2081
perror_plus("sigaction");
2084
if(old_sigterm_action.sa_handler != SIG_IGN){
2085
ret = sigaction(SIGINT, &sigterm_action, NULL);
2087
perror_plus("sigaction");
2088
exitcode = EX_OSERR;
2092
ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
2094
perror_plus("sigaction");
2097
if(old_sigterm_action.sa_handler != SIG_IGN){
2098
ret = sigaction(SIGHUP, &sigterm_action, NULL);
2100
perror_plus("sigaction");
2101
exitcode = EX_OSERR;
2105
ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
2107
perror_plus("sigaction");
2110
if(old_sigterm_action.sa_handler != SIG_IGN){
2111
ret = sigaction(SIGTERM, &sigterm_action, NULL);
2113
perror_plus("sigaction");
2114
exitcode = EX_OSERR;
2119
/* If no interfaces were specified, make a list */
2120
if(interfaces == NULL){
2121
struct dirent **direntries;
2122
/* Look for any good interfaces */
2123
ret = scandir(sys_class_net, &direntries, good_interface,
2126
/* Add all found interfaces to interfaces list */
2127
for(int i = 0; i < ret; ++i){
2128
ret_errno = argz_add(&interfaces, &interfaces_size,
2129
direntries[i]->d_name);
2131
perror_plus("argz_add");
2135
fprintf_plus(stderr, "Will use interface \"%s\"\n",
2136
direntries[i]->d_name);
2142
fprintf_plus(stderr, "Could not find a network interface\n");
2143
exitcode = EXIT_FAILURE;
2148
/* If we only got one interface, explicitly use only that one */
2149
if(argz_count(interfaces, interfaces_size) == 1){
2151
fprintf_plus(stderr, "Using only interface \"%s\"\n",
2154
if_index = (AvahiIfIndex)if_nametoindex(interfaces);
2157
/* Bring up interfaces which are down */
2158
if(not (argz_count(interfaces, interfaces_size) == 1
2159
and strcmp(interfaces, "none") == 0)){
2160
char *interface = NULL;
2161
while((interface = argz_next(interfaces, interfaces_size,
2163
bool interface_was_up = interface_is_up(interface);
2164
ret = bring_up_interface(interface, delay);
2165
if(not interface_was_up){
2168
perror_plus("Failed to bring up interface");
2170
ret_errno = argz_add(&interfaces_to_take_down,
2171
&interfaces_to_take_down_size,
2178
interfaces_size = 0;
2179
if(debug and (interfaces_to_take_down == NULL)){
2180
fprintf_plus(stderr, "No interfaces were brought up\n");
2188
ret = init_gnutls_global(pubkey, seckey);
2190
fprintf_plus(stderr, "init_gnutls_global failed\n");
2191
exitcode = EX_UNAVAILABLE;
2194
gnutls_initialized = true;
2201
if(mkdtemp(tempdir) == NULL){
2202
perror_plus("mkdtemp");
2205
tempdir_created = true;
2211
if(not init_gpgme(pubkey, seckey, tempdir)){
2212
fprintf_plus(stderr, "init_gpgme failed\n");
2213
exitcode = EX_UNAVAILABLE;
2216
gpgme_initialized = true;
2223
if(connect_to != NULL){
2224
/* Connect directly, do not use Zeroconf */
2225
/* (Mainly meant for debugging) */
2226
char *address = strrchr(connect_to, ':');
2228
if(address == NULL){
2229
fprintf_plus(stderr, "No colon in address\n");
2230
exitcode = EX_USAGE;
2240
tmpmax = strtoimax(address+1, &tmp, 10);
2241
if(errno != 0 or tmp == address+1 or *tmp != '\0'
2242
or tmpmax != (in_port_t)tmpmax){
2243
fprintf_plus(stderr, "Bad port number\n");
2244
exitcode = EX_USAGE;
2252
port = (in_port_t)tmpmax;
2254
/* Colon in address indicates IPv6 */
2256
if(strchr(connect_to, ':') != NULL){
2258
/* Accept [] around IPv6 address - see RFC 5952 */
2259
if(connect_to[0] == '[' and address[-1] == ']')
2267
address = connect_to;
2273
while(not quit_now){
2274
ret = start_mandos_communication(address, port, if_index, af);
2275
if(quit_now or ret == 0){
2279
fprintf_plus(stderr, "Retrying in %d seconds\n",
2280
(int)retry_interval);
2282
sleep((int)retry_interval);
2286
exitcode = EXIT_SUCCESS;
2297
AvahiServerConfig config;
2298
/* Do not publish any local Zeroconf records */
2299
avahi_server_config_init(&config);
2300
config.publish_hinfo = 0;
2301
config.publish_addresses = 0;
2302
config.publish_workstation = 0;
2303
config.publish_domain = 0;
2305
/* Allocate a new server */
2306
mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2307
&config, NULL, NULL, &ret_errno);
2309
/* Free the Avahi configuration data */
2310
avahi_server_config_free(&config);
2313
/* Check if creating the Avahi server object succeeded */
2314
if(mc.server == NULL){
2315
fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2316
avahi_strerror(ret_errno));
2317
exitcode = EX_UNAVAILABLE;
2325
/* Create the Avahi service browser */
2326
sb = avahi_s_service_browser_new(mc.server, if_index,
2327
AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2328
NULL, 0, browse_callback, NULL);
2330
fprintf_plus(stderr, "Failed to create service browser: %s\n",
2331
avahi_strerror(avahi_server_errno(mc.server)));
2332
exitcode = EX_UNAVAILABLE;
2340
/* Run the main loop */
2343
fprintf_plus(stderr, "Starting Avahi loop search\n");
2346
ret = avahi_loop_with_timeout(simple_poll,
2347
(int)(retry_interval * 1000));
2349
fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2350
(ret == 0) ? "successfully" : "with error");
1034
fprintf(stderr, "%s exiting\n", argv[0]);
1037
/* Cleanup things */
1039
avahi_s_service_browser_free(sb);
1041
if (mc.server != NULL)
1042
avahi_server_free(mc.server);
1044
if (mc.simple_poll != NULL)
1045
avahi_simple_poll_free(mc.simple_poll);
1049
if (gnutls_initalized){
1050
gnutls_certificate_free_credentials(mc.cred);
1051
gnutls_global_deinit ();
2356
fprintf_plus(stderr, "%s exiting\n", argv[0]);
2359
/* Cleanup things */
2361
avahi_s_service_browser_free(sb);
2363
if(mc.server != NULL)
2364
avahi_server_free(mc.server);
2366
if(simple_poll != NULL)
2367
avahi_simple_poll_free(simple_poll);
2369
if(gnutls_initialized){
2370
gnutls_certificate_free_credentials(mc.cred);
2371
gnutls_global_deinit();
2372
gnutls_dh_params_deinit(mc.dh_params);
2375
if(gpgme_initialized){
2376
gpgme_release(mc.ctx);
2379
/* Cleans up the circular linked list of Mandos servers the client
2381
if(mc.current_server != NULL){
2382
mc.current_server->prev->next = NULL;
2383
while(mc.current_server != NULL){
2384
server *next = mc.current_server->next;
2385
free(mc.current_server);
2386
mc.current_server = next;
2390
/* Re-raise priviliges */
2394
/* Run network hooks */
2395
run_network_hooks("stop", interfaces_hooks != NULL ?
2396
interfaces_hooks : "", delay);
2398
/* Take down the network interfaces which were brought up */
2400
char *interface = NULL;
2401
while((interface=argz_next(interfaces_to_take_down,
2402
interfaces_to_take_down_size,
2404
ret_errno = take_down_interface(interface);
2407
perror_plus("Failed to take down interface");
2410
if(debug and (interfaces_to_take_down == NULL)){
2411
fprintf_plus(stderr, "No interfaces needed to be taken"
2416
lower_privileges_permanently();
2419
free(interfaces_to_take_down);
2420
free(interfaces_hooks);
2422
/* Removes the GPGME temp directory and all files inside */
2423
if(tempdir_created){
2424
struct dirent **direntries = NULL;
2425
struct dirent *direntry = NULL;
2426
int numentries = scandir(tempdir, &direntries, notdotentries,
2428
if (numentries > 0){
2429
for(int i = 0; i < numentries; i++){
2430
direntry = direntries[i];
2431
char *fullname = NULL;
2432
ret = asprintf(&fullname, "%s/%s", tempdir,
2435
perror_plus("asprintf");
2438
ret = remove(fullname);
2440
fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2447
/* need to clean even if 0 because man page doesn't specify */
2449
if (numentries == -1){
2450
perror_plus("scandir");
2452
ret = rmdir(tempdir);
2453
if(ret == -1 and errno != ENOENT){
2454
perror_plus("rmdir");
2459
sigemptyset(&old_sigterm_action.sa_mask);
2460
old_sigterm_action.sa_handler = SIG_DFL;
2461
ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
2462
&old_sigterm_action,
2465
perror_plus("sigaction");
2468
ret = raise(signal_received);
2469
} while(ret != 0 and errno == EINTR);
2471
perror_plus("raise");
2474
TEMP_FAILURE_RETRY(pause());