129
199
return buffer_capacity;
202
/* Add server to set of servers to retry periodically */
203
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
206
server *new_server = malloc(sizeof(server));
207
if(new_server == NULL){
208
perror_plus("malloc");
211
*new_server = (server){ .ip = strdup(ip),
213
.if_index = if_index,
215
if(new_server->ip == NULL){
216
perror_plus("strdup");
219
/* Special case of first server */
220
if (mc.current_server == NULL){
221
new_server->next = new_server;
222
new_server->prev = new_server;
223
mc.current_server = new_server;
224
/* Place the new server last in the list */
226
new_server->next = mc.current_server;
227
new_server->prev = mc.current_server->prev;
228
new_server->prev->next = new_server;
229
mc.current_server->prev = new_server;
231
ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
233
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;
242
static bool init_gpgme(const char *seckey, const char *pubkey,
243
const char *tempdir){
142
244
gpgme_error_t rc;
144
size_t plaintext_capacity = 0;
145
ssize_t plaintext_length = 0;
146
245
gpgme_engine_info_t engine_info;
149
fprintf(stderr, "Trying to decrypt OpenPGP data\n");
249
* Helper function to insert pub and seckey to the engine keyring.
251
bool import_key(const char *filename){
254
gpgme_data_t pgp_data;
256
fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
262
rc = gpgme_data_new_from_fd(&pgp_data, fd);
263
if(rc != GPG_ERR_NO_ERROR){
264
fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
265
gpgme_strsource(rc), gpgme_strerror(rc));
269
rc = gpgme_op_import(mc.ctx, pgp_data);
270
if(rc != GPG_ERR_NO_ERROR){
271
fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
272
gpgme_strsource(rc), gpgme_strerror(rc));
276
ret = (int)TEMP_FAILURE_RETRY(close(fd));
278
perror_plus("close");
280
gpgme_data_release(pgp_data);
285
fprintf_plus(stderr, "Initializing GPGME\n");
153
289
gpgme_check_version(NULL);
154
290
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",
291
if(rc != GPG_ERR_NO_ERROR){
292
fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
157
293
gpgme_strsource(rc), gpgme_strerror(rc));
161
297
/* 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",
298
rc = gpgme_get_engine_info(&engine_info);
299
if(rc != GPG_ERR_NO_ERROR){
300
fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
165
301
gpgme_strsource(rc), gpgme_strerror(rc));
168
304
while(engine_info != NULL){
169
305
if(engine_info->protocol == GPGME_PROTOCOL_OpenPGP){
170
306
gpgme_set_engine_info(GPGME_PROTOCOL_OpenPGP,
171
engine_info->file_name, homedir);
307
engine_info->file_name, tempdir);
174
310
engine_info = engine_info->next;
176
312
if(engine_info == NULL){
177
fprintf(stderr, "Could not set GPGME home dir to %s\n", homedir);
313
fprintf_plus(stderr, "Could not set GPGME home dir to %s\n", tempdir);
317
/* Create new GPGME "context" */
318
rc = gpgme_new(&(mc.ctx));
319
if(rc != GPG_ERR_NO_ERROR){
320
fprintf_plus(stderr, "Mandos plugin mandos-client: "
321
"bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
326
if(not import_key(pubkey) or not import_key(seckey)){
334
* Decrypt OpenPGP data.
335
* Returns -1 on error
337
static ssize_t pgp_packet_decrypt(const char *cryptotext,
340
gpgme_data_t dh_crypto, dh_plain;
343
size_t plaintext_capacity = 0;
344
ssize_t plaintext_length = 0;
347
fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
181
350
/* Create new GPGME data buffer from memory cryptotext */
182
351
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",
353
if(rc != GPG_ERR_NO_ERROR){
354
fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
186
355
gpgme_strsource(rc), gpgme_strerror(rc));
190
359
/* Create new empty GPGME data buffer for the plaintext */
191
360
rc = gpgme_data_new(&dh_plain);
192
if (rc != GPG_ERR_NO_ERROR){
193
fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
361
if(rc != GPG_ERR_NO_ERROR){
362
fprintf_plus(stderr, "Mandos plugin mandos-client: "
363
"bad gpgme_data_new: %s: %s\n",
194
364
gpgme_strsource(rc), gpgme_strerror(rc));
195
365
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
369
/* 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",
371
rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
372
if(rc != GPG_ERR_NO_ERROR){
373
fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
213
374
gpgme_strsource(rc), gpgme_strerror(rc));
214
375
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;
377
gpgme_decrypt_result_t result;
378
result = gpgme_op_decrypt_result(mc.ctx);
380
fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
382
fprintf_plus(stderr, "Unsupported algorithm: %s\n",
383
result->unsupported_algorithm);
384
fprintf_plus(stderr, "Wrong key usage: %u\n",
385
result->wrong_key_usage);
386
if(result->file_name != NULL){
387
fprintf_plus(stderr, "File name: %s\n", result->file_name);
389
gpgme_recipient_t recipient;
390
recipient = result->recipients;
238
391
while(recipient != NULL){
239
fprintf(stderr, "Public key algorithm: %s\n",
392
fprintf_plus(stderr, "Public key algorithm: %s\n",
240
393
gpgme_pubkey_algo_name(recipient->pubkey_algo));
241
fprintf(stderr, "Key ID: %s\n", recipient->keyid);
242
fprintf(stderr, "Secret key available: %s\n",
394
fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
395
fprintf_plus(stderr, "Secret key available: %s\n",
243
396
recipient->status == GPG_ERR_NO_SECKEY
245
398
recipient = recipient->next;
406
fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
251
409
/* 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");
410
if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
411
perror_plus("gpgme_data_seek");
254
412
plaintext_length = -1;
255
413
goto decrypt_end;
258
416
*plaintext = NULL;
260
plaintext_capacity = adjustbuffer(plaintext,
261
(size_t)plaintext_length,
263
if (plaintext_capacity == 0){
264
perror("adjustbuffer");
265
plaintext_length = -1;
418
plaintext_capacity = incbuffer(plaintext,
419
(size_t)plaintext_length,
421
if(plaintext_capacity == 0){
422
perror_plus("incbuffer");
423
plaintext_length = -1;
269
427
ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
271
429
/* Print the data, if any */
277
perror("gpgme_data_read");
435
perror_plus("gpgme_data_read");
278
436
plaintext_length = -1;
279
437
goto decrypt_end;
281
439
plaintext_length += ret;
285
fprintf(stderr, "Decrypted password is: ");
443
fprintf_plus(stderr, "Decrypted password is: ");
286
444
for(ssize_t i = 0; i < plaintext_length; i++){
287
445
fprintf(stderr, "%02hhX ", (*plaintext)[i]);
435
605
/* Called when a Mandos server is found */
436
606
static int start_mandos_communication(const char *ip, uint16_t port,
437
607
AvahiIfIndex if_index,
440
union { struct sockaddr in; struct sockaddr_in6 in6; } to;
609
int ret, tcp_sd = -1;
612
struct sockaddr_in in;
613
struct sockaddr_in6 in6;
441
615
char *buffer = NULL;
442
char *decrypted_buffer;
616
char *decrypted_buffer = NULL;
443
617
size_t buffer_length = 0;
444
618
size_t buffer_capacity = 0;
445
ssize_t decrypted_buffer_size;
448
char interface[IF_NAMESIZE];
449
621
gnutls_session_t session;
451
ret = init_gnutls_session (mc, &session);
622
int pf; /* Protocol family */
639
fprintf_plus(stderr, "Bad address family: %d\n", af);
644
ret = init_gnutls_session(&session);
457
fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
650
fprintf_plus(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);
654
tcp_sd = socket(pf, SOCK_STREAM, 0);
657
perror_plus("socket");
667
memset(&to, 0, sizeof(to));
669
to.in6.sin6_family = (sa_family_t)af;
670
ret = inet_pton(af, ip, &to.in6.sin6_addr);
672
to.in.sin_family = (sa_family_t)af;
673
ret = inet_pton(af, ip, &to.in.sin_addr);
677
perror_plus("inet_pton");
485
fprintf(stderr, "Bad address: %s\n", ip);
488
to.in6.sin6_port = htons(port); /* Spurious warning */
683
fprintf_plus(stderr, "Bad address: %s\n", ip);
688
to.in6.sin6_port = htons(port); /* Spurious warnings from
690
-Wunreachable-code */
692
if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
693
(&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
695
if(if_index == AVAHI_IF_UNSPEC){
696
fprintf_plus(stderr, "An IPv6 link-local address is incomplete"
697
" without a network interface\n");
701
/* Set the network interface number as scope */
702
to.in6.sin6_scope_id = (uint32_t)if_index;
705
to.in.sin_port = htons(port); /* Spurious warnings from
707
-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){
716
if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
717
char interface[IF_NAMESIZE];
718
if(if_indextoname((unsigned int)if_index, interface) == NULL){
719
perror_plus("if_indextoname");
721
fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
722
ip, interface, port);
725
fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n", ip, port);
727
char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
728
INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
731
pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
734
pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
738
perror_plus("inet_ntop");
500
740
if(strcmp(addrstr, ip) != 0){
501
fprintf(stderr, "Canonical address form: %s\n", addrstr);
741
fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
506
ret = connect(tcp_sd, &to.in, sizeof(to));
752
ret = connect(tcp_sd, &to.in6, sizeof(to));
754
ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
757
if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
759
perror_plus("connect");
512
770
const char *out = mandos_protocol_version;
515
773
size_t out_size = strlen(out);
516
ret = TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
517
out_size - written));
774
ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
775
out_size - written));
778
perror_plus("write");
523
782
written += (size_t)ret;
524
783
if(written < out_size){
527
if (out == mandos_protocol_version){
786
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);
801
fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
809
/* Spurious warning from -Wint-to-pointer-cast */
810
gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
818
ret = gnutls_handshake(session);
544
823
} while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
546
if (ret != GNUTLS_E_SUCCESS){
825
if(ret != GNUTLS_E_SUCCESS){
548
fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
827
fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
555
834
/* Read OpenPGP packet that contains the wanted password */
558
fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
837
fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from %s\n", ip);
563
buffer_capacity = adjustbuffer(&buffer, buffer_length,
565
if (buffer_capacity == 0){
566
perror("adjustbuffer");
571
ret = gnutls_record_recv(session, buffer+buffer_length,
847
buffer_capacity = incbuffer(&buffer, buffer_length,
849
if(buffer_capacity == 0){
851
perror_plus("incbuffer");
861
sret = gnutls_record_recv(session, buffer+buffer_length,
578
868
case GNUTLS_E_INTERRUPTED:
579
869
case GNUTLS_E_AGAIN:
581
871
case GNUTLS_E_REHANDSHAKE:
583
ret = gnutls_handshake (session);
873
ret = gnutls_handshake(session);
584
879
} while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
586
fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
881
fprintf_plus(stderr, "*** GnuTLS Re-handshake failed ***\n");
593
fprintf(stderr, "Unknown error while reading data from"
888
fprintf_plus(stderr, "Unknown error while reading data from"
594
889
" encrypted session with Mandos server\n");
596
gnutls_bye (session, GNUTLS_SHUT_RDWR);
890
gnutls_bye(session, GNUTLS_SHUT_RDWR);
600
buffer_length += (size_t) ret;
895
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){
900
fprintf_plus(stderr, "Closing TLS session\n");
909
ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
914
} while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
916
if(buffer_length > 0){
917
ssize_t decrypted_buffer_size;
918
decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
920
if(decrypted_buffer_size >= 0){
617
923
while(written < (size_t) decrypted_buffer_size){
618
ret = (int)fwrite (decrypted_buffer + written, 1,
619
(size_t)decrypted_buffer_size - written,
929
ret = (int)fwrite(decrypted_buffer + written, 1,
930
(size_t)decrypted_buffer_size - written,
621
932
if(ret == 0 and ferror(stdout)){
623
fprintf(stderr, "Error writing encrypted data: %s\n",
935
fprintf_plus(stderr, "Error writing encrypted data: %s\n",
624
936
strerror(errno));
629
941
written += (size_t)ret;
631
free(decrypted_buffer);
637
947
/* Shutdown procedure */
642
gnutls_deinit (session);
952
free(decrypted_buffer);
955
ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
961
perror_plus("close");
963
gnutls_deinit(session);
646
973
static void resolve_callback(AvahiSServiceResolver *r,
647
974
AvahiIfIndex interface,
648
AVAHI_GCC_UNUSED AvahiProtocol protocol,
649
976
AvahiResolverEvent event,
650
977
const char *name,
651
978
const char *type,
734
1070
case AVAHI_BROWSER_ALL_FOR_NOW:
735
1071
case AVAHI_BROWSER_CACHE_EXHAUSTED:
737
fprintf(stderr, "No Mandos server found, still searching...\n");
1073
fprintf_plus(stderr, "No Mandos server found, still searching...\n");
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';
1079
/* Signal handler that stops main loop after SIGTERM */
1080
static void handle_sigterm(int sig){
1085
signal_received = sig;
1086
int old_errno = errno;
1087
/* set main loop to exit */
1088
if(mc.simple_poll != NULL){
1089
avahi_simple_poll_quit(mc.simple_poll);
1094
bool get_flags(const char *ifname, struct ifreq *ifr){
1097
int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1099
perror_plus("socket");
1102
strcpy(ifr->ifr_name, ifname);
1103
ret = ioctl(s, SIOCGIFFLAGS, ifr);
1106
perror_plus("ioctl SIOCGIFFLAGS");
1113
bool good_flags(const char *ifname, const struct ifreq *ifr){
1115
/* Reject the loopback device */
1116
if(ifr->ifr_flags & IFF_LOOPBACK){
1118
fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n", ifname);
1122
/* Accept point-to-point devices only if connect_to is specified */
1123
if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1125
fprintf_plus(stderr, "Accepting point-to-point interface \"%s\"\n", ifname);
1129
/* Otherwise, reject non-broadcast-capable devices */
1130
if(not (ifr->ifr_flags & IFF_BROADCAST)){
1132
fprintf_plus(stderr, "Rejecting non-broadcast interface \"%s\"\n", ifname);
1136
/* Reject non-ARP interfaces (including dummy interfaces) */
1137
if(ifr->ifr_flags & IFF_NOARP){
1139
fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
1144
/* Accept this device */
1146
fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1152
* This function determines if a directory entry in /sys/class/net
1153
* corresponds to an acceptable network device.
1154
* (This function is passed to scandir(3) as a filter function.)
1156
int good_interface(const struct dirent *if_entry){
1157
if(if_entry->d_name[0] == '.'){
1162
if(not get_flags(if_entry->d_name, &ifr)){
1164
fprintf_plus(stderr, "Failed to get flags for interface \"%s\"\n",
1170
if(not good_flags(if_entry->d_name, &ifr)){
1177
* This function determines if a directory entry in /sys/class/net
1178
* corresponds to an acceptable network device which is up.
1179
* (This function is passed to scandir(3) as a filter function.)
1181
int up_interface(const struct dirent *if_entry){
1182
if(if_entry->d_name[0] == '.'){
1187
if(not get_flags(if_entry->d_name, &ifr)){
1189
fprintf_plus(stderr, "Failed to get flags for interface \"%s\"\n",
1195
/* Reject down interfaces */
1196
if(not (ifr.ifr_flags & IFF_UP)){
1198
fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
1204
/* Reject non-running interfaces */
1205
if(not (ifr.ifr_flags & IFF_RUNNING)){
1207
fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
1213
if(not good_flags(if_entry->d_name, &ifr)){
1219
int notdotentries(const struct dirent *direntry){
1220
/* Skip "." and ".." */
1221
if(direntry->d_name[0] == '.'
1222
and (direntry->d_name[1] == '\0'
1223
or (direntry->d_name[1] == '.'
1224
and direntry->d_name[2] == '\0'))){
1230
/* Is this directory entry a runnable program? */
1231
int runnable_hook(const struct dirent *direntry){
1236
if((direntry->d_name)[0] == '\0'){
1241
sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1242
"abcdefghijklmnopqrstuvwxyz"
1245
if((direntry->d_name)[sret] != '\0'){
1246
/* Contains non-allowed characters */
1248
fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
1254
char *fullname = NULL;
1255
ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1257
perror_plus("asprintf");
1261
ret = stat(fullname, &st);
1264
perror_plus("Could not stat hook");
1268
if(not (S_ISREG(st.st_mode))){
1269
/* Not a regular file */
1271
fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
1276
if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1277
/* Not executable */
1279
fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
1287
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1289
struct timespec now;
1290
struct timespec waited_time;
1291
intmax_t block_time;
1294
if(mc.current_server == NULL){
1296
fprintf_plus(stderr, "Wait until first server is found. No timeout!\n");
1298
ret = avahi_simple_poll_iterate(s, -1);
1301
fprintf_plus(stderr, "Check current_server if we should run it,"
1304
/* the current time */
1305
ret = clock_gettime(CLOCK_MONOTONIC, &now);
1307
perror_plus("clock_gettime");
1310
/* Calculating in ms how long time between now and server
1311
who we visted longest time ago. Now - last seen. */
1312
waited_time.tv_sec = (now.tv_sec
1313
- mc.current_server->last_seen.tv_sec);
1314
waited_time.tv_nsec = (now.tv_nsec
1315
- mc.current_server->last_seen.tv_nsec);
1316
/* total time is 10s/10,000ms.
1317
Converting to s from ms by dividing by 1,000,
1318
and ns to ms by dividing by 1,000,000. */
1319
block_time = ((retry_interval
1320
- ((intmax_t)waited_time.tv_sec * 1000))
1321
- ((intmax_t)waited_time.tv_nsec / 1000000));
1324
fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
1327
if(block_time <= 0){
1328
ret = start_mandos_communication(mc.current_server->ip,
1329
mc.current_server->port,
1330
mc.current_server->if_index,
1331
mc.current_server->af);
1333
avahi_simple_poll_quit(mc.simple_poll);
1336
ret = clock_gettime(CLOCK_MONOTONIC,
1337
&mc.current_server->last_seen);
1339
perror_plus("clock_gettime");
1342
mc.current_server = mc.current_server->next;
1343
block_time = 0; /* Call avahi to find new Mandos
1344
servers, but don't block */
1347
ret = avahi_simple_poll_iterate(s, (int)block_time);
1350
if (ret > 0 or errno != EINTR){
1351
return (ret != 1) ? ret : 0;
764
1357
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);
857
return ARGP_ERR_UNKNOWN;
862
struct argp argp = { .options = options, .parser = parse_opt,
864
.doc = "Mandos client -- Get and decrypt"
865
" passwords from mandos server" };
866
ret = argp_parse (&argp, argc, argv, 0, 0, NULL);
867
if (ret == ARGP_ERR_UNKNOWN){
868
fprintf(stderr, "Unknown error while parsing arguments\n");
869
exitcode = EXIT_FAILURE;
874
pubkeyfile = combinepath(keydir, pubkeyfile);
875
if (pubkeyfile == NULL){
876
perror("combinepath");
877
exitcode = EXIT_FAILURE;
881
seckeyfile = combinepath(keydir, seckeyfile);
882
if (seckeyfile == NULL){
883
perror("combinepath");
884
exitcode = EXIT_FAILURE;
888
ret = init_gnutls_global(&mc, pubkeyfile, seckeyfile);
890
fprintf(stderr, "init_gnutls_global failed\n");
891
exitcode = EXIT_FAILURE;
1358
AvahiSServiceBrowser *sb = NULL;
1363
int exitcode = EXIT_SUCCESS;
1364
const char *interface = "";
1365
struct ifreq network;
1367
bool take_down_interface = false;
1370
char tempdir[] = "/tmp/mandosXXXXXX";
1371
bool tempdir_created = false;
1372
AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1373
const char *seckey = PATHDIR "/" SECKEY;
1374
const char *pubkey = PATHDIR "/" PUBKEY;
1376
bool gnutls_initialized = false;
1377
bool gpgme_initialized = false;
1379
double retry_interval = 10; /* 10s between trying a server and
1380
retrying the same server again */
1382
struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1383
struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1388
/* Lower any group privileges we might have, just to be safe */
1392
perror_plus("setgid");
1395
/* Lower user privileges (temporarily) */
1399
perror_plus("seteuid");
1407
struct argp_option options[] = {
1408
{ .name = "debug", .key = 128,
1409
.doc = "Debug mode", .group = 3 },
1410
{ .name = "connect", .key = 'c',
1411
.arg = "ADDRESS:PORT",
1412
.doc = "Connect directly to a specific Mandos server",
1414
{ .name = "interface", .key = 'i',
1416
.doc = "Network interface that will be used to search for"
1419
{ .name = "seckey", .key = 's',
1421
.doc = "OpenPGP secret key file base name",
1423
{ .name = "pubkey", .key = 'p',
1425
.doc = "OpenPGP public key file base name",
1427
{ .name = "dh-bits", .key = 129,
1429
.doc = "Bit length of the prime number used in the"
1430
" Diffie-Hellman key exchange",
1432
{ .name = "priority", .key = 130,
1434
.doc = "GnuTLS priority string for the TLS handshake",
1436
{ .name = "delay", .key = 131,
1438
.doc = "Maximum delay to wait for interface startup",
1440
{ .name = "retry", .key = 132,
1442
.doc = "Retry interval used when denied by the mandos server",
1444
{ .name = "network-hook-dir", .key = 133,
1446
.doc = "Directory where network hooks are located",
1449
* These reproduce what we would get without ARGP_NO_HELP
1451
{ .name = "help", .key = '?',
1452
.doc = "Give this help list", .group = -1 },
1453
{ .name = "usage", .key = -3,
1454
.doc = "Give a short usage message", .group = -1 },
1455
{ .name = "version", .key = 'V',
1456
.doc = "Print program version", .group = -1 },
1460
error_t parse_opt(int key, char *arg,
1461
struct argp_state *state){
1464
case 128: /* --debug */
1467
case 'c': /* --connect */
1470
case 'i': /* --interface */
1473
case 's': /* --seckey */
1476
case 'p': /* --pubkey */
1479
case 129: /* --dh-bits */
1481
tmpmax = strtoimax(arg, &tmp, 10);
1482
if(errno != 0 or tmp == arg or *tmp != '\0'
1483
or tmpmax != (typeof(mc.dh_bits))tmpmax){
1484
argp_error(state, "Bad number of DH bits");
1486
mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1488
case 130: /* --priority */
1491
case 131: /* --delay */
1493
delay = strtof(arg, &tmp);
1494
if(errno != 0 or tmp == arg or *tmp != '\0'){
1495
argp_error(state, "Bad delay");
1497
case 132: /* --retry */
1499
retry_interval = strtod(arg, &tmp);
1500
if(errno != 0 or tmp == arg or *tmp != '\0'
1501
or (retry_interval * 1000) > INT_MAX
1502
or retry_interval < 0){
1503
argp_error(state, "Bad retry interval");
1506
case 133: /* --network-hook-dir */
1510
* These reproduce what we would get without ARGP_NO_HELP
1512
case '?': /* --help */
1513
argp_state_help(state, state->out_stream,
1514
(ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
1515
& ~(unsigned int)ARGP_HELP_EXIT_OK);
1516
case -3: /* --usage */
1517
argp_state_help(state, state->out_stream,
1518
ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1519
case 'V': /* --version */
1520
fprintf_plus(state->out_stream, "Mandos plugin mandos-client: ");
1521
fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1522
exit(argp_err_exit_status);
1525
return ARGP_ERR_UNKNOWN;
1530
struct argp argp = { .options = options, .parser = parse_opt,
1532
.doc = "Mandos client -- Get and decrypt"
1533
" passwords from a Mandos server" };
1534
ret = argp_parse(&argp, argc, argv,
1535
ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
1542
perror_plus("argp_parse");
1543
exitcode = EX_OSERR;
1546
exitcode = EX_USAGE;
1552
/* Work around Debian bug #633582:
1553
<http://bugs.debian.org/633582> */
1556
/* Re-raise priviliges */
1560
perror_plus("seteuid");
1563
if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1564
int seckey_fd = open(seckey, O_RDONLY);
1565
if(seckey_fd == -1){
1566
perror_plus("open");
1568
ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1570
perror_plus("fstat");
1572
if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1573
ret = fchown(seckey_fd, uid, gid);
1575
perror_plus("fchown");
1579
TEMP_FAILURE_RETRY(close(seckey_fd));
1583
if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1584
int pubkey_fd = open(pubkey, O_RDONLY);
1585
if(pubkey_fd == -1){
1586
perror_plus("open");
1588
ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1590
perror_plus("fstat");
1592
if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1593
ret = fchown(pubkey_fd, uid, gid);
1595
perror_plus("fchown");
1599
TEMP_FAILURE_RETRY(close(pubkey_fd));
1603
/* Lower privileges */
1607
perror_plus("seteuid");
1611
/* Find network hooks and run them */
1613
struct dirent **direntries;
1614
struct dirent *direntry;
1615
int numhooks = scandir(hookdir, &direntries, runnable_hook,
1618
perror_plus("scandir");
894
gnutls_initalized = true;
897
/* If the interface is down, bring it up */
899
sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
902
exitcode = EXIT_FAILURE;
905
strcpy(network.ifr_name, interface); /* Spurious warning */
906
ret = ioctl(sd, SIOCGIFFLAGS, &network);
908
perror("ioctl SIOCGIFFLAGS");
909
exitcode = EXIT_FAILURE;
912
if((network.ifr_flags & IFF_UP) == 0){
913
network.ifr_flags |= IFF_UP;
914
ret = ioctl(sd, SIOCSIFFLAGS, &network);
916
perror("ioctl SIOCSIFFLAGS");
917
exitcode = EXIT_FAILURE;
1620
int devnull = open("/dev/null", O_RDONLY);
1621
for(int i = 0; i < numhooks; i++){
1622
direntry = direntries[0];
1623
char *fullname = NULL;
1624
ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1626
perror_plus("asprintf");
1629
pid_t hook_pid = fork();
1632
dup2(devnull, STDIN_FILENO);
1634
dup2(STDERR_FILENO, STDOUT_FILENO);
1635
ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1637
perror_plus("setenv");
1640
ret = setenv("DEVICE", interface, 1);
1642
perror_plus("setenv");
1645
ret = setenv("VERBOSE", debug ? "1" : "0", 1);
1647
perror_plus("setenv");
1650
ret = setenv("MODE", "start", 1);
1652
perror_plus("setenv");
1656
ret = asprintf(&delaystring, "%f", delay);
1658
perror_plus("asprintf");
1661
ret = setenv("DELAY", delaystring, 1);
1664
perror_plus("setenv");
1668
ret = execl(fullname, direntry->d_name, "start", NULL);
1669
perror_plus("execl");
1672
if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1673
perror_plus("waitpid");
1677
if(WIFEXITED(status)){
1678
if(WEXITSTATUS(status) != 0){
1679
fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1680
" with status %d\n", direntry->d_name,
1681
WEXITSTATUS(status));
1685
} else if(WIFSIGNALED(status)){
1686
fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1687
" signal %d\n", direntry->d_name,
1692
fprintf_plus(stderr, "Warning: network hook \"%s\" crashed\n",
1708
avahi_set_log_function(empty_log);
1711
if(interface[0] == '\0'){
1712
struct dirent **direntries;
1713
/* First look for interfaces that are up */
1714
ret = scandir(sys_class_net, &direntries, up_interface,
1717
/* No up interfaces, look for any good interfaces */
1719
ret = scandir(sys_class_net, &direntries, good_interface,
1723
/* Pick the first interface returned */
1724
interface = strdup(direntries[0]->d_name);
1726
fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1728
if(interface == NULL){
1729
perror_plus("malloc");
1731
exitcode = EXIT_FAILURE;
1737
fprintf_plus(stderr, "Could not find a network interface\n");
1738
exitcode = EXIT_FAILURE;
1743
/* Initialize Avahi early so avahi_simple_poll_quit() can be called
1744
from the signal handler */
1745
/* Initialize the pseudo-RNG for Avahi */
1746
srand((unsigned int) time(NULL));
1747
mc.simple_poll = avahi_simple_poll_new();
1748
if(mc.simple_poll == NULL){
1749
fprintf_plus(stderr, "Avahi: Failed to create simple poll object.\n");
1750
exitcode = EX_UNAVAILABLE;
1754
sigemptyset(&sigterm_action.sa_mask);
1755
ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1757
perror_plus("sigaddset");
1758
exitcode = EX_OSERR;
1761
ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1763
perror_plus("sigaddset");
1764
exitcode = EX_OSERR;
1767
ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1769
perror_plus("sigaddset");
1770
exitcode = EX_OSERR;
1773
/* Need to check if the handler is SIG_IGN before handling:
1774
| [[info:libc:Initial Signal Actions]] |
1775
| [[info:libc:Basic Signal Handling]] |
1777
ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1779
perror_plus("sigaction");
1782
if(old_sigterm_action.sa_handler != SIG_IGN){
1783
ret = sigaction(SIGINT, &sigterm_action, NULL);
1785
perror_plus("sigaction");
1786
exitcode = EX_OSERR;
1790
ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1792
perror_plus("sigaction");
1795
if(old_sigterm_action.sa_handler != SIG_IGN){
1796
ret = sigaction(SIGHUP, &sigterm_action, NULL);
1798
perror_plus("sigaction");
1799
exitcode = EX_OSERR;
1803
ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1805
perror_plus("sigaction");
1808
if(old_sigterm_action.sa_handler != SIG_IGN){
1809
ret = sigaction(SIGTERM, &sigterm_action, NULL);
1811
perror_plus("sigaction");
1812
exitcode = EX_OSERR;
1817
/* If the interface is down, bring it up */
1818
if(strcmp(interface, "none") != 0){
937
1819
if_index = (AvahiIfIndex) if_nametoindex(interface);
938
1820
if(if_index == 0){
939
fprintf(stderr, "No such interface: \"%s\"\n", interface);
943
if(connect_to != NULL){
944
/* Connect directly, do not use Zeroconf */
945
/* (Mainly meant for debugging) */
946
char *address = strrchr(connect_to, ':');
948
fprintf(stderr, "No colon in address\n");
949
exitcode = EXIT_FAILURE;
953
uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
955
perror("Bad port number");
956
exitcode = EXIT_FAILURE;
960
address = connect_to;
961
ret = start_mandos_communication(address, port, if_index, &mc);
963
exitcode = EXIT_FAILURE;
965
exitcode = EXIT_SUCCESS;
971
avahi_set_log_function(empty_log);
974
/* Initialize the pseudo-RNG for Avahi */
975
srand((unsigned int) time(NULL));
977
/* Allocate main Avahi loop object */
978
mc.simple_poll = avahi_simple_poll_new();
979
if (mc.simple_poll == NULL) {
980
fprintf(stderr, "Avahi: Failed to create simple poll"
982
exitcode = EXIT_FAILURE;
987
AvahiServerConfig config;
988
/* Do not publish any local Zeroconf records */
989
avahi_server_config_init(&config);
990
config.publish_hinfo = 0;
991
config.publish_addresses = 0;
992
config.publish_workstation = 0;
993
config.publish_domain = 0;
995
/* Allocate a new server */
996
mc.server = avahi_server_new(avahi_simple_poll_get
997
(mc.simple_poll), &config, NULL,
1000
/* Free the Avahi configuration data */
1001
avahi_server_config_free(&config);
1004
/* Check if creating the Avahi server object succeeded */
1005
if (mc.server == NULL) {
1006
fprintf(stderr, "Failed to create Avahi server: %s\n",
1007
avahi_strerror(error));
1008
exitcode = EXIT_FAILURE;
1012
/* Create the Avahi service browser */
1013
sb = avahi_s_service_browser_new(mc.server, if_index,
1015
"_mandos._tcp", NULL, 0,
1016
browse_callback, &mc);
1018
fprintf(stderr, "Failed to create service browser: %s\n",
1019
avahi_strerror(avahi_server_errno(mc.server)));
1020
exitcode = EXIT_FAILURE;
1024
/* Run the main loop */
1027
fprintf(stderr, "Starting Avahi loop search\n");
1030
avahi_simple_poll_loop(mc.simple_poll);
1821
fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1822
exitcode = EX_UNAVAILABLE;
1830
/* Re-raise priviliges */
1834
perror_plus("seteuid");
1838
/* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1839
messages about the network interface to mess up the prompt */
1840
ret = klogctl(8, NULL, 5);
1841
bool restore_loglevel = true;
1843
restore_loglevel = false;
1844
perror_plus("klogctl");
1846
#endif /* __linux__ */
1848
sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1850
perror_plus("socket");
1851
exitcode = EX_OSERR;
1853
if(restore_loglevel){
1854
ret = klogctl(7, NULL, 0);
1856
perror_plus("klogctl");
1859
#endif /* __linux__ */
1860
/* Lower privileges */
1864
perror_plus("seteuid");
1868
strcpy(network.ifr_name, interface);
1869
ret = ioctl(sd, SIOCGIFFLAGS, &network);
1871
perror_plus("ioctl SIOCGIFFLAGS");
1873
if(restore_loglevel){
1874
ret = klogctl(7, NULL, 0);
1876
perror_plus("klogctl");
1879
#endif /* __linux__ */
1880
exitcode = EX_OSERR;
1881
/* Lower privileges */
1885
perror_plus("seteuid");
1889
if((network.ifr_flags & IFF_UP) == 0){
1890
network.ifr_flags |= IFF_UP;
1891
take_down_interface = true;
1892
ret = ioctl(sd, SIOCSIFFLAGS, &network);
1894
take_down_interface = false;
1895
perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1896
exitcode = EX_OSERR;
1898
if(restore_loglevel){
1899
ret = klogctl(7, NULL, 0);
1901
perror_plus("klogctl");
1904
#endif /* __linux__ */
1905
/* Lower privileges */
1909
perror_plus("seteuid");
1914
/* Sleep checking until interface is running.
1915
Check every 0.25s, up to total time of delay */
1916
for(int i=0; i < delay * 4; i++){
1917
ret = ioctl(sd, SIOCGIFFLAGS, &network);
1919
perror_plus("ioctl SIOCGIFFLAGS");
1920
} else if(network.ifr_flags & IFF_RUNNING){
1923
struct timespec sleeptime = { .tv_nsec = 250000000 };
1924
ret = nanosleep(&sleeptime, NULL);
1925
if(ret == -1 and errno != EINTR){
1926
perror_plus("nanosleep");
1929
if(not take_down_interface){
1930
/* We won't need the socket anymore */
1931
ret = (int)TEMP_FAILURE_RETRY(close(sd));
1933
perror_plus("close");
1937
if(restore_loglevel){
1938
/* Restores kernel loglevel to default */
1939
ret = klogctl(7, NULL, 0);
1941
perror_plus("klogctl");
1944
#endif /* __linux__ */
1945
/* Lower privileges */
1947
if(take_down_interface){
1948
/* Lower privileges */
1951
perror_plus("seteuid");
1954
/* Lower privileges permanently */
1957
perror_plus("setuid");
1966
ret = init_gnutls_global(pubkey, seckey);
1968
fprintf_plus(stderr, "init_gnutls_global failed\n");
1969
exitcode = EX_UNAVAILABLE;
1972
gnutls_initialized = true;
1979
if(mkdtemp(tempdir) == NULL){
1980
perror_plus("mkdtemp");
1983
tempdir_created = true;
1989
if(not init_gpgme(pubkey, seckey, tempdir)){
1990
fprintf_plus(stderr, "init_gpgme failed\n");
1991
exitcode = EX_UNAVAILABLE;
1994
gpgme_initialized = true;
2001
if(connect_to != NULL){
2002
/* Connect directly, do not use Zeroconf */
2003
/* (Mainly meant for debugging) */
2004
char *address = strrchr(connect_to, ':');
2005
if(address == NULL){
2006
fprintf_plus(stderr, "No colon in address\n");
2007
exitcode = EX_USAGE;
2017
tmpmax = strtoimax(address+1, &tmp, 10);
2018
if(errno != 0 or tmp == address+1 or *tmp != '\0'
2019
or tmpmax != (uint16_t)tmpmax){
2020
fprintf_plus(stderr, "Bad port number\n");
2021
exitcode = EX_USAGE;
2029
port = (uint16_t)tmpmax;
2031
/* Colon in address indicates IPv6 */
2033
if(strchr(connect_to, ':') != NULL){
2035
/* Accept [] around IPv6 address - see RFC 5952 */
2036
if(connect_to[0] == '[' and address[-1] == ']')
2044
address = connect_to;
2050
while(not quit_now){
2051
ret = start_mandos_communication(address, port, if_index, af);
2052
if(quit_now or ret == 0){
2056
fprintf_plus(stderr, "Retrying in %d seconds\n", (int)retry_interval);
2058
sleep((int)retry_interval);
2062
exitcode = EXIT_SUCCESS;
2073
AvahiServerConfig config;
2074
/* Do not publish any local Zeroconf records */
2075
avahi_server_config_init(&config);
2076
config.publish_hinfo = 0;
2077
config.publish_addresses = 0;
2078
config.publish_workstation = 0;
2079
config.publish_domain = 0;
2081
/* Allocate a new server */
2082
mc.server = avahi_server_new(avahi_simple_poll_get
2083
(mc.simple_poll), &config, NULL,
2086
/* Free the Avahi configuration data */
2087
avahi_server_config_free(&config);
2090
/* Check if creating the Avahi server object succeeded */
2091
if(mc.server == NULL){
2092
fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2093
avahi_strerror(error));
2094
exitcode = EX_UNAVAILABLE;
2102
/* Create the Avahi service browser */
2103
sb = avahi_s_service_browser_new(mc.server, if_index,
2104
AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2105
NULL, 0, browse_callback, NULL);
2107
fprintf_plus(stderr, "Failed to create service browser: %s\n",
2108
avahi_strerror(avahi_server_errno(mc.server)));
2109
exitcode = EX_UNAVAILABLE;
2117
/* Run the main loop */
2120
fprintf_plus(stderr, "Starting Avahi loop search\n");
2123
ret = avahi_loop_with_timeout(mc.simple_poll,
2124
(int)(retry_interval * 1000));
2126
fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2127
(ret == 0) ? "successfully" : "with error");
1035
fprintf(stderr, "%s exiting\n", argv[0]);
1038
/* Cleanup things */
1040
avahi_s_service_browser_free(sb);
1042
if (mc.server != NULL)
1043
avahi_server_free(mc.server);
1045
if (mc.simple_poll != NULL)
1046
avahi_simple_poll_free(mc.simple_poll);
1050
if (gnutls_initalized){
1051
gnutls_certificate_free_credentials(mc.cred);
1052
gnutls_global_deinit ();
2133
fprintf_plus(stderr, "%s exiting\n", argv[0]);
2136
/* Cleanup things */
2138
avahi_s_service_browser_free(sb);
2140
if(mc.server != NULL)
2141
avahi_server_free(mc.server);
2143
if(mc.simple_poll != NULL)
2144
avahi_simple_poll_free(mc.simple_poll);
2146
if(gnutls_initialized){
2147
gnutls_certificate_free_credentials(mc.cred);
2148
gnutls_global_deinit();
2149
gnutls_dh_params_deinit(mc.dh_params);
2152
if(gpgme_initialized){
2153
gpgme_release(mc.ctx);
2156
/* Cleans up the circular linked list of Mandos servers the client
2158
if(mc.current_server != NULL){
2159
mc.current_server->prev->next = NULL;
2160
while(mc.current_server != NULL){
2161
server *next = mc.current_server->next;
2162
free(mc.current_server);
2163
mc.current_server = next;
2167
/* XXX run network hooks "stop" here */
2169
/* Take down the network interface */
2170
if(take_down_interface){
2171
/* Re-raise priviliges */
2175
perror_plus("seteuid");
2178
ret = ioctl(sd, SIOCGIFFLAGS, &network);
2180
perror_plus("ioctl SIOCGIFFLAGS");
2181
} else if(network.ifr_flags & IFF_UP){
2182
network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2183
ret = ioctl(sd, SIOCSIFFLAGS, &network);
2185
perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
2188
ret = (int)TEMP_FAILURE_RETRY(close(sd));
2190
perror_plus("close");
2192
/* Lower privileges permanently */
2196
perror_plus("setuid");
2201
/* Removes the GPGME temp directory and all files inside */
2202
if(tempdir_created){
2203
struct dirent **direntries = NULL;
2204
struct dirent *direntry = NULL;
2205
int numentries = scandir(tempdir, &direntries, notdotentries,
2207
if (numentries > 0){
2208
for(int i = 0; i < numentries; i++){
2209
direntry = direntries[i];
2210
char *fullname = NULL;
2211
ret = asprintf(&fullname, "%s/%s", tempdir,
2214
perror_plus("asprintf");
2217
ret = remove(fullname);
2219
fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname, strerror(errno));
2225
/* need to clean even if 0 because man page doesn't specify */
2227
if (numentries == -1){
2228
perror_plus("scandir");
2230
ret = rmdir(tempdir);
2231
if(ret == -1 and errno != ENOENT){
2232
perror_plus("rmdir");
2237
sigemptyset(&old_sigterm_action.sa_mask);
2238
old_sigterm_action.sa_handler = SIG_DFL;
2239
ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
2240
&old_sigterm_action,
2243
perror_plus("sigaction");
2246
ret = raise(signal_received);
2247
} while(ret != 0 and errno == EINTR);
2249
perror_plus("raise");
2252
TEMP_FAILURE_RETRY(pause());