105
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");
109
* Decrypt OpenPGP data using keyrings in HOMEDIR.
110
* Returns -1 on error
112
static ssize_t pgp_packet_decrypt (const char *cryptotext,
115
const char *homedir){
116
gpgme_data_t dh_crypto, dh_plain;
242
static bool init_gpgme(const char *seckey, const char *pubkey,
243
const char *tempdir){
118
244
gpgme_error_t rc;
120
size_t plaintext_capacity = 0;
121
ssize_t plaintext_length = 0;
122
245
gpgme_engine_info_t engine_info;
125
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");
129
289
gpgme_check_version(NULL);
130
290
rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
131
if (rc != GPG_ERR_NO_ERROR){
132
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",
133
293
gpgme_strsource(rc), gpgme_strerror(rc));
137
297
/* Set GPGME home directory for the OpenPGP engine only */
138
rc = gpgme_get_engine_info (&engine_info);
139
if (rc != GPG_ERR_NO_ERROR){
140
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",
141
301
gpgme_strsource(rc), gpgme_strerror(rc));
144
304
while(engine_info != NULL){
145
305
if(engine_info->protocol == GPGME_PROTOCOL_OpenPGP){
146
306
gpgme_set_engine_info(GPGME_PROTOCOL_OpenPGP,
147
engine_info->file_name, homedir);
307
engine_info->file_name, tempdir);
150
310
engine_info = engine_info->next;
152
312
if(engine_info == NULL){
153
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");
157
350
/* Create new GPGME data buffer from memory cryptotext */
158
351
rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
160
if (rc != GPG_ERR_NO_ERROR){
161
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",
162
355
gpgme_strsource(rc), gpgme_strerror(rc));
166
359
/* Create new empty GPGME data buffer for the plaintext */
167
360
rc = gpgme_data_new(&dh_plain);
168
if (rc != GPG_ERR_NO_ERROR){
169
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",
170
364
gpgme_strsource(rc), gpgme_strerror(rc));
171
365
gpgme_data_release(dh_crypto);
175
/* Create new GPGME "context" */
176
rc = gpgme_new(&ctx);
177
if (rc != GPG_ERR_NO_ERROR){
178
fprintf(stderr, "bad gpgme_new: %s: %s\n",
179
gpgme_strsource(rc), gpgme_strerror(rc));
180
plaintext_length = -1;
184
369
/* Decrypt data from the cryptotext data buffer to the plaintext
186
rc = gpgme_op_decrypt(ctx, dh_crypto, dh_plain);
187
if (rc != GPG_ERR_NO_ERROR){
188
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",
189
374
gpgme_strsource(rc), gpgme_strerror(rc));
190
375
plaintext_length = -1;
195
fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
199
gpgme_decrypt_result_t result;
200
result = gpgme_op_decrypt_result(ctx);
202
fprintf(stderr, "gpgme_op_decrypt_result failed\n");
204
fprintf(stderr, "Unsupported algorithm: %s\n",
205
result->unsupported_algorithm);
206
fprintf(stderr, "Wrong key usage: %d\n",
207
result->wrong_key_usage);
208
if(result->file_name != NULL){
209
fprintf(stderr, "File name: %s\n", result->file_name);
211
gpgme_recipient_t recipient;
212
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;
214
391
while(recipient != NULL){
215
fprintf(stderr, "Public key algorithm: %s\n",
392
fprintf_plus(stderr, "Public key algorithm: %s\n",
216
393
gpgme_pubkey_algo_name(recipient->pubkey_algo));
217
fprintf(stderr, "Key ID: %s\n", recipient->keyid);
218
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",
219
396
recipient->status == GPG_ERR_NO_SECKEY
221
398
recipient = recipient->next;
406
fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
227
409
/* Seek back to the beginning of the GPGME plaintext data buffer */
228
if (gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET) == -1){
229
perror("pgpme_data_seek");
410
if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
411
perror_plus("gpgme_data_seek");
230
412
plaintext_length = -1;
231
413
goto decrypt_end;
234
416
*plaintext = NULL;
236
plaintext_capacity = adjustbuffer(plaintext, (size_t)plaintext_length,
238
if (plaintext_capacity == 0){
239
perror("adjustbuffer");
240
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;
244
427
ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
246
429
/* Print the data, if any */
252
perror("gpgme_data_read");
435
perror_plus("gpgme_data_read");
253
436
plaintext_length = -1;
254
437
goto decrypt_end;
256
439
plaintext_length += ret;
260
fprintf(stderr, "Decrypted password is: ");
443
fprintf_plus(stderr, "Decrypted password is: ");
261
444
for(ssize_t i = 0; i < plaintext_length; i++){
262
445
fprintf(stderr, "%02hhX ", (*plaintext)[i]);
397
605
/* Called when a Mandos server is found */
398
606
static int start_mandos_communication(const char *ip, uint16_t port,
399
607
AvahiIfIndex if_index,
402
struct sockaddr_in6 to;
609
int ret, tcp_sd = -1;
612
struct sockaddr_in in;
613
struct sockaddr_in6 in6;
403
615
char *buffer = NULL;
404
char *decrypted_buffer;
616
char *decrypted_buffer = NULL;
405
617
size_t buffer_length = 0;
406
618
size_t buffer_capacity = 0;
407
ssize_t decrypted_buffer_size;
410
char interface[IF_NAMESIZE];
411
621
gnutls_session_t session;
412
gnutls_dh_params_t dh_params;
414
ret = init_gnutls_session (mc, &session);
420
fprintf(stderr, "Setting up a tcp connection to %s, port %d\n",
424
tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
431
if(if_indextoname((unsigned int)if_index, interface) == NULL){
432
perror("if_indextoname");
435
fprintf(stderr, "Binding to interface %s\n", interface);
438
memset(&to,0,sizeof(to)); /* Spurious warning */
439
to.sin6_family = AF_INET6;
440
/* It would be nice to have a way to detect if we were passed an
441
IPv4 address here. Now we assume an IPv6 address. */
442
ret = inet_pton(AF_INET6, ip, &to.sin6_addr);
622
int pf; /* Protocol family */
639
fprintf_plus(stderr, "Bad address family: %d\n", af);
644
ret = init_gnutls_session(&session);
650
fprintf_plus(stderr, "Setting up a TCP connection to %s, port %" PRIu16
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");
448
fprintf(stderr, "Bad address: %s\n", ip);
451
to.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 */
453
to.sin6_scope_id = (uint32_t)if_index;
456
fprintf(stderr, "Connection to: %s, port %d\n", ip, port);
457
char addrstr[INET6_ADDRSTRLEN] = "";
458
if(inet_ntop(to.sin6_family, &(to.sin6_addr), addrstr,
459
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");
462
740
if(strcmp(addrstr, ip) != 0){
463
fprintf(stderr, "Canonical address form: %s\n", addrstr);
741
fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
468
ret = connect(tcp_sd, (struct sockaddr *) &to, 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");
474
770
const char *out = mandos_protocol_version;
477
773
size_t out_size = strlen(out);
478
ret = TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
479
out_size - written));
774
ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
775
out_size - written));
778
perror_plus("write");
485
782
written += (size_t)ret;
486
783
if(written < out_size){
489
if (out == mandos_protocol_version){
786
if(out == mandos_protocol_version){
499
fprintf(stderr, "Establishing TLS session with %s\n", ip);
502
gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) tcp_sd);
504
ret = gnutls_handshake (session);
506
if (ret != GNUTLS_E_SUCCESS){
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);
823
} while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
825
if(ret != GNUTLS_E_SUCCESS){
508
fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
827
fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
515
834
/* Read OpenPGP packet that contains the wanted password */
518
fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
837
fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from %s\n", ip);
523
buffer_capacity = adjustbuffer(&buffer, buffer_length, buffer_capacity);
524
if (buffer_capacity == 0){
525
perror("adjustbuffer");
530
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,
537
868
case GNUTLS_E_INTERRUPTED:
538
869
case GNUTLS_E_AGAIN:
540
871
case GNUTLS_E_REHANDSHAKE:
541
ret = gnutls_handshake (session);
543
fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
873
ret = gnutls_handshake(session);
879
} while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
881
fprintf_plus(stderr, "*** GnuTLS Re-handshake failed ***\n");
550
fprintf(stderr, "Unknown error while reading data from"
888
fprintf_plus(stderr, "Unknown error while reading data from"
551
889
" encrypted session with Mandos server\n");
553
gnutls_bye (session, GNUTLS_SHUT_RDWR);
890
gnutls_bye(session, GNUTLS_SHUT_RDWR);
557
buffer_length += (size_t) ret;
895
buffer_length += (size_t) sret;
562
fprintf(stderr, "Closing TLS session\n");
565
gnutls_bye (session, GNUTLS_SHUT_RDWR);
567
if (buffer_length > 0){
568
decrypted_buffer_size = pgp_packet_decrypt(buffer,
572
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){
574
923
while(written < (size_t) decrypted_buffer_size){
575
ret = (int)fwrite (decrypted_buffer + written, 1,
576
(size_t)decrypted_buffer_size - written,
929
ret = (int)fwrite(decrypted_buffer + written, 1,
930
(size_t)decrypted_buffer_size - written,
578
932
if(ret == 0 and ferror(stdout)){
580
fprintf(stderr, "Error writing encrypted data: %s\n",
935
fprintf_plus(stderr, "Error writing encrypted data: %s\n",
581
936
strerror(errno));
586
941
written += (size_t)ret;
588
free(decrypted_buffer);
594
947
/* Shutdown procedure */
599
gnutls_deinit (session);
600
gnutls_certificate_free_credentials (mc->cred);
601
gnutls_global_deinit ();
952
free(decrypted_buffer);
955
ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
961
perror_plus("close");
963
gnutls_deinit(session);
605
973
static void resolve_callback(AvahiSServiceResolver *r,
606
974
AvahiIfIndex interface,
607
AVAHI_GCC_UNUSED AvahiProtocol protocol,
608
976
AvahiResolverEvent event,
609
977
const char *name,
610
978
const char *type,
692
1070
case AVAHI_BROWSER_ALL_FOR_NOW:
693
1071
case AVAHI_BROWSER_CACHE_EXHAUSTED:
695
fprintf(stderr, "No Mandos server found, still searching...\n");
1073
fprintf_plus(stderr, "No Mandos server found, still searching...\n");
701
/* Combines file name and path and returns the malloced new
702
string. some sane checks could/should be added */
703
static const char *combinepath(const char *first, const char *second){
704
size_t f_len = strlen(first);
705
size_t s_len = strlen(second);
706
char *tmp = malloc(f_len + s_len + 2);
711
memcpy(tmp, first, f_len); /* Spurious warning */
715
memcpy(tmp + f_len + 1, second, s_len); /* Spurious warning */
717
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;
722
1357
int main(int argc, char *argv[]){
723
AvahiSServiceBrowser *sb = NULL;
726
int exitcode = EXIT_SUCCESS;
727
const char *interface = "eth0";
728
struct ifreq network;
732
char *connect_to = NULL;
733
AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
734
mandos_context mc = { .simple_poll = NULL, .server = NULL,
735
.dh_bits = 1024, .priority = "SECURE256"};
738
/* Temporary int to get the address of for getopt_long */
739
int debug_int = debug ? 1 : 0;
741
struct option long_options[] = {
742
{"debug", no_argument, &debug_int, 1},
743
{"connect", required_argument, NULL, 'c'},
744
{"interface", required_argument, NULL, 'i'},
745
{"keydir", required_argument, NULL, 'd'},
746
{"seckey", required_argument, NULL, 's'},
747
{"pubkey", required_argument, NULL, 'p'},
748
{"dh-bits", required_argument, NULL, 'D'},
749
{"priority", required_argument, NULL, 'P'},
752
int option_index = 0;
753
ret = getopt_long (argc, argv, "i:", long_options,
780
mc.dh_bits = (unsigned int) strtol(optarg, NULL, 10);
787
mc.priority = optarg;
791
/* getopt_long() has already printed a message about the
792
unrcognized option, so just exit. */
796
/* Set the global debug flag from the temporary int */
797
debug = debug_int ? true : false;
800
pubkeyfile = combinepath(keydir, pubkeyfile);
801
if (pubkeyfile == NULL){
802
perror("combinepath");
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");
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");
803
1738
exitcode = EXIT_FAILURE;
807
seckeyfile = combinepath(keydir, seckeyfile);
808
if (seckeyfile == NULL){
809
perror("combinepath");
813
ret = init_gnutls_global(&mc);
815
fprintf(stderr, "init_gnutls_global\n");
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){
832
1819
if_index = (AvahiIfIndex) if_nametoindex(interface);
833
1820
if(if_index == 0){
834
fprintf(stderr, "No such interface: \"%s\"\n", interface);
838
if(connect_to != NULL){
839
/* Connect directly, do not use Zeroconf */
840
/* (Mainly meant for debugging) */
841
char *address = strrchr(connect_to, ':');
843
fprintf(stderr, "No colon in address\n");
844
exitcode = EXIT_FAILURE;
848
uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
850
perror("Bad port number");
851
exitcode = EXIT_FAILURE;
855
address = connect_to;
856
ret = start_mandos_communication(address, port, if_index, &mc);
858
exitcode = EXIT_FAILURE;
860
exitcode = EXIT_SUCCESS;
865
/* If the interface is down, bring it up */
867
sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
870
exitcode = EXIT_FAILURE;
873
strcpy(network.ifr_name, interface); /* Spurious warning */
874
ret = ioctl(sd, SIOCGIFFLAGS, &network);
876
perror("ioctl SIOCGIFFLAGS");
877
exitcode = EXIT_FAILURE;
880
if((network.ifr_flags & IFF_UP) == 0){
881
network.ifr_flags |= IFF_UP;
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");
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 */
882
2183
ret = ioctl(sd, SIOCSIFFLAGS, &network);
884
perror("ioctl SIOCSIFFLAGS");
885
exitcode = EXIT_FAILURE;
893
avahi_set_log_function(empty_log);
896
/* Initialize the pseudo-RNG for Avahi */
897
srand((unsigned int) time(NULL));
899
/* Allocate main Avahi loop object */
900
mc.simple_poll = avahi_simple_poll_new();
901
if (mc.simple_poll == NULL) {
902
fprintf(stderr, "Avahi: Failed to create simple poll"
904
exitcode = EXIT_FAILURE;
909
AvahiServerConfig config;
910
/* Do not publish any local Zeroconf records */
911
avahi_server_config_init(&config);
912
config.publish_hinfo = 0;
913
config.publish_addresses = 0;
914
config.publish_workstation = 0;
915
config.publish_domain = 0;
917
/* Allocate a new server */
918
mc.server = avahi_server_new(avahi_simple_poll_get
919
(mc.simple_poll), &config, NULL,
922
/* Free the Avahi configuration data */
923
avahi_server_config_free(&config);
926
/* Check if creating the Avahi server object succeeded */
927
if (mc.server == NULL) {
928
fprintf(stderr, "Failed to create Avahi server: %s\n",
929
avahi_strerror(error));
930
exitcode = EXIT_FAILURE;
934
/* Create the Avahi service browser */
935
sb = avahi_s_service_browser_new(mc.server, if_index,
937
"_mandos._tcp", NULL, 0,
938
browse_callback, &mc);
940
fprintf(stderr, "Failed to create service browser: %s\n",
941
avahi_strerror(avahi_server_errno(mc.server)));
942
exitcode = EXIT_FAILURE;
946
/* Run the main loop */
949
fprintf(stderr, "Starting Avahi loop search\n");
952
avahi_simple_poll_loop(mc.simple_poll);
957
fprintf(stderr, "%s exiting\n", argv[0]);
962
avahi_s_service_browser_free(sb);
964
if (mc.server != NULL)
965
avahi_server_free(mc.server);
967
if (mc.simple_poll != NULL)
968
avahi_simple_poll_free(mc.simple_poll);
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());