129
201
return buffer_capacity;
204
/* Add server to set of servers to retry periodically */
205
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
208
server *new_server = malloc(sizeof(server));
209
if(new_server == NULL){
210
perror_plus("malloc");
213
*new_server = (server){ .ip = strdup(ip),
215
.if_index = if_index,
217
if(new_server->ip == NULL){
218
perror_plus("strdup");
221
/* Special case of first server */
222
if (mc.current_server == NULL){
223
new_server->next = new_server;
224
new_server->prev = new_server;
225
mc.current_server = new_server;
226
/* Place the new server last in the list */
228
new_server->next = mc.current_server;
229
new_server->prev = mc.current_server->prev;
230
new_server->prev->next = new_server;
231
mc.current_server->prev = new_server;
233
ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
235
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;
244
static bool init_gpgme(const char *seckey, const char *pubkey,
245
const char *tempdir){
142
246
gpgme_error_t rc;
144
size_t plaintext_capacity = 0;
145
ssize_t plaintext_length = 0;
146
247
gpgme_engine_info_t engine_info;
149
fprintf(stderr, "Trying to decrypt OpenPGP data\n");
251
* Helper function to insert pub and seckey to the engine keyring.
253
bool import_key(const char *filename){
256
gpgme_data_t pgp_data;
258
fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
264
rc = gpgme_data_new_from_fd(&pgp_data, fd);
265
if(rc != GPG_ERR_NO_ERROR){
266
fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
267
gpgme_strsource(rc), gpgme_strerror(rc));
271
rc = gpgme_op_import(mc.ctx, pgp_data);
272
if(rc != GPG_ERR_NO_ERROR){
273
fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
274
gpgme_strsource(rc), gpgme_strerror(rc));
278
ret = (int)TEMP_FAILURE_RETRY(close(fd));
280
perror_plus("close");
282
gpgme_data_release(pgp_data);
287
fprintf_plus(stderr, "Initializing GPGME\n");
153
291
gpgme_check_version(NULL);
154
292
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));
293
if(rc != GPG_ERR_NO_ERROR){
294
fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
295
gpgme_strsource(rc), gpgme_strerror(rc));
161
299
/* 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));
300
rc = gpgme_get_engine_info(&engine_info);
301
if(rc != GPG_ERR_NO_ERROR){
302
fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
303
gpgme_strsource(rc), gpgme_strerror(rc));
168
306
while(engine_info != NULL){
169
307
if(engine_info->protocol == GPGME_PROTOCOL_OpenPGP){
170
308
gpgme_set_engine_info(GPGME_PROTOCOL_OpenPGP,
171
engine_info->file_name, homedir);
309
engine_info->file_name, tempdir);
174
312
engine_info = engine_info->next;
176
314
if(engine_info == NULL){
177
fprintf(stderr, "Could not set GPGME home dir to %s\n", homedir);
315
fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
320
/* Create new GPGME "context" */
321
rc = gpgme_new(&(mc.ctx));
322
if(rc != GPG_ERR_NO_ERROR){
323
fprintf_plus(stderr, "Mandos plugin mandos-client: "
324
"bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
329
if(not import_key(pubkey) or not import_key(seckey)){
337
* Decrypt OpenPGP data.
338
* Returns -1 on error
340
static ssize_t pgp_packet_decrypt(const char *cryptotext,
343
gpgme_data_t dh_crypto, dh_plain;
346
size_t plaintext_capacity = 0;
347
ssize_t plaintext_length = 0;
350
fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
181
353
/* Create new GPGME data buffer from memory cryptotext */
182
354
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));
356
if(rc != GPG_ERR_NO_ERROR){
357
fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
358
gpgme_strsource(rc), gpgme_strerror(rc));
190
362
/* Create new empty GPGME data buffer for the plaintext */
191
363
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));
364
if(rc != GPG_ERR_NO_ERROR){
365
fprintf_plus(stderr, "Mandos plugin mandos-client: "
366
"bad gpgme_data_new: %s: %s\n",
367
gpgme_strsource(rc), gpgme_strerror(rc));
195
368
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
372
/* 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));
374
rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
375
if(rc != GPG_ERR_NO_ERROR){
376
fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
377
gpgme_strsource(rc), gpgme_strerror(rc));
214
378
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;
380
gpgme_decrypt_result_t result;
381
result = gpgme_op_decrypt_result(mc.ctx);
383
fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
385
fprintf_plus(stderr, "Unsupported algorithm: %s\n",
386
result->unsupported_algorithm);
387
fprintf_plus(stderr, "Wrong key usage: %u\n",
388
result->wrong_key_usage);
389
if(result->file_name != NULL){
390
fprintf_plus(stderr, "File name: %s\n", result->file_name);
392
gpgme_recipient_t recipient;
393
recipient = result->recipients;
238
394
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
395
fprintf_plus(stderr, "Public key algorithm: %s\n",
396
gpgme_pubkey_algo_name
397
(recipient->pubkey_algo));
398
fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
399
fprintf_plus(stderr, "Secret key available: %s\n",
400
recipient->status == GPG_ERR_NO_SECKEY
245
402
recipient = recipient->next;
410
fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
251
413
/* 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");
414
if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
415
perror_plus("gpgme_data_seek");
254
416
plaintext_length = -1;
255
417
goto decrypt_end;
258
420
*plaintext = NULL;
260
plaintext_capacity = adjustbuffer(plaintext,
261
(size_t)plaintext_length,
263
if (plaintext_capacity == 0){
264
perror("adjustbuffer");
265
plaintext_length = -1;
422
plaintext_capacity = incbuffer(plaintext,
423
(size_t)plaintext_length,
425
if(plaintext_capacity == 0){
426
perror_plus("incbuffer");
427
plaintext_length = -1;
269
431
ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
271
433
/* Print the data, if any */
277
perror("gpgme_data_read");
439
perror_plus("gpgme_data_read");
278
440
plaintext_length = -1;
279
441
goto decrypt_end;
281
443
plaintext_length += ret;
285
fprintf(stderr, "Decrypted password is: ");
447
fprintf_plus(stderr, "Decrypted password is: ");
286
448
for(ssize_t i = 0; i < plaintext_length; i++){
287
449
fprintf(stderr, "%02hhX ", (*plaintext)[i]);
435
616
/* Called when a Mandos server is found */
436
617
static int start_mandos_communication(const char *ip, uint16_t port,
437
618
AvahiIfIndex if_index,
440
union { struct sockaddr in; struct sockaddr_in6 in6; } to;
620
int ret, tcp_sd = -1;
623
struct sockaddr_in in;
624
struct sockaddr_in6 in6;
441
626
char *buffer = NULL;
442
char *decrypted_buffer;
627
char *decrypted_buffer = NULL;
443
628
size_t buffer_length = 0;
444
629
size_t buffer_capacity = 0;
445
ssize_t decrypted_buffer_size;
448
char interface[IF_NAMESIZE];
449
632
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);
633
int pf; /* Protocol family */
650
fprintf_plus(stderr, "Bad address family: %d\n", af);
655
ret = init_gnutls_session(&session);
661
fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
662
PRIu16 "\n", ip, port);
665
tcp_sd = socket(pf, SOCK_STREAM, 0);
668
perror_plus("socket");
678
memset(&to, 0, sizeof(to));
680
to.in6.sin6_family = (sa_family_t)af;
681
ret = inet_pton(af, ip, &to.in6.sin6_addr);
683
to.in.sin_family = (sa_family_t)af;
684
ret = inet_pton(af, ip, &to.in.sin_addr);
688
perror_plus("inet_pton");
485
fprintf(stderr, "Bad address: %s\n", ip);
488
to.in6.sin6_port = htons(port); /* Spurious warning */
694
fprintf_plus(stderr, "Bad address: %s\n", ip);
699
to.in6.sin6_port = htons(port); /* Spurious warnings from
701
-Wunreachable-code */
703
if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
704
(&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
706
if(if_index == AVAHI_IF_UNSPEC){
707
fprintf_plus(stderr, "An IPv6 link-local address is"
708
" incomplete without a network interface\n");
712
/* Set the network interface number as scope */
713
to.in6.sin6_scope_id = (uint32_t)if_index;
716
to.in.sin_port = htons(port); /* Spurious warnings from
718
-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){
727
if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
728
char interface[IF_NAMESIZE];
729
if(if_indextoname((unsigned int)if_index, interface) == NULL){
730
perror_plus("if_indextoname");
732
fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
733
"\n", ip, interface, port);
736
fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
739
char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
740
INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
743
pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
746
pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
750
perror_plus("inet_ntop");
500
752
if(strcmp(addrstr, ip) != 0){
501
fprintf(stderr, "Canonical address form: %s\n", addrstr);
753
fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
506
ret = connect(tcp_sd, &to.in, sizeof(to));
764
ret = connect(tcp_sd, &to.in6, sizeof(to));
766
ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
769
if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
771
perror_plus("connect");
512
782
const char *out = mandos_protocol_version;
515
785
size_t out_size = strlen(out);
516
ret = TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
517
out_size - written));
786
ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
787
out_size - written));
790
perror_plus("write");
523
794
written += (size_t)ret;
524
795
if(written < out_size){
527
if (out == mandos_protocol_version){
798
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);
813
fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
821
/* Spurious warning from -Wint-to-pointer-cast */
822
gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
830
ret = gnutls_handshake(session);
544
835
} while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
546
if (ret != GNUTLS_E_SUCCESS){
837
if(ret != GNUTLS_E_SUCCESS){
548
fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
839
fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
555
846
/* Read OpenPGP packet that contains the wanted password */
558
fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
849
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,
860
buffer_capacity = incbuffer(&buffer, buffer_length,
862
if(buffer_capacity == 0){
864
perror_plus("incbuffer");
874
sret = gnutls_record_recv(session, buffer+buffer_length,
578
881
case GNUTLS_E_INTERRUPTED:
579
882
case GNUTLS_E_AGAIN:
581
884
case GNUTLS_E_REHANDSHAKE:
583
ret = gnutls_handshake (session);
886
ret = gnutls_handshake(session);
584
892
} while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
586
fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
894
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);
902
fprintf_plus(stderr, "Unknown error while reading data from"
903
" encrypted session with Mandos server\n");
904
gnutls_bye(session, GNUTLS_SHUT_RDWR);
600
buffer_length += (size_t) ret;
909
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){
914
fprintf_plus(stderr, "Closing TLS session\n");
923
ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
928
} while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
930
if(buffer_length > 0){
931
ssize_t decrypted_buffer_size;
932
decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
934
if(decrypted_buffer_size >= 0){
617
937
while(written < (size_t) decrypted_buffer_size){
618
ret = (int)fwrite (decrypted_buffer + written, 1,
619
(size_t)decrypted_buffer_size - written,
943
ret = (int)fwrite(decrypted_buffer + written, 1,
944
(size_t)decrypted_buffer_size - written,
621
946
if(ret == 0 and ferror(stdout)){
623
fprintf(stderr, "Error writing encrypted data: %s\n",
949
fprintf_plus(stderr, "Error writing encrypted data: %s\n",
629
955
written += (size_t)ret;
631
free(decrypted_buffer);
637
961
/* Shutdown procedure */
642
gnutls_deinit (session);
966
free(decrypted_buffer);
969
ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
975
perror_plus("close");
977
gnutls_deinit(session);
646
987
static void resolve_callback(AvahiSServiceResolver *r,
647
988
AvahiIfIndex interface,
648
AVAHI_GCC_UNUSED AvahiProtocol protocol,
649
990
AvahiResolverEvent event,
650
991
const char *name,
651
992
const char *type,
734
1086
case AVAHI_BROWSER_ALL_FOR_NOW:
735
1087
case AVAHI_BROWSER_CACHE_EXHAUSTED:
737
fprintf(stderr, "No Mandos server found, still searching...\n");
1089
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';
1096
/* Signal handler that stops main loop after SIGTERM */
1097
static void handle_sigterm(int sig){
1102
signal_received = sig;
1103
int old_errno = errno;
1104
/* set main loop to exit */
1105
if(mc.simple_poll != NULL){
1106
avahi_simple_poll_quit(mc.simple_poll);
1111
bool get_flags(const char *ifname, struct ifreq *ifr){
1114
int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1116
perror_plus("socket");
1119
strcpy(ifr->ifr_name, ifname);
1120
ret = ioctl(s, SIOCGIFFLAGS, ifr);
1123
perror_plus("ioctl SIOCGIFFLAGS");
1130
bool good_flags(const char *ifname, const struct ifreq *ifr){
1132
/* Reject the loopback device */
1133
if(ifr->ifr_flags & IFF_LOOPBACK){
1135
fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1140
/* Accept point-to-point devices only if connect_to is specified */
1141
if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1143
fprintf_plus(stderr, "Accepting point-to-point interface"
1144
" \"%s\"\n", ifname);
1148
/* Otherwise, reject non-broadcast-capable devices */
1149
if(not (ifr->ifr_flags & IFF_BROADCAST)){
1151
fprintf_plus(stderr, "Rejecting non-broadcast interface"
1152
" \"%s\"\n", ifname);
1156
/* Reject non-ARP interfaces (including dummy interfaces) */
1157
if(ifr->ifr_flags & IFF_NOARP){
1159
fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1165
/* Accept this device */
1167
fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1173
* This function determines if a directory entry in /sys/class/net
1174
* corresponds to an acceptable network device.
1175
* (This function is passed to scandir(3) as a filter function.)
1177
int good_interface(const struct dirent *if_entry){
1178
if(if_entry->d_name[0] == '.'){
1183
if(not get_flags(if_entry->d_name, &ifr)){
1185
fprintf_plus(stderr, "Failed to get flags for interface "
1186
"\"%s\"\n", if_entry->d_name);
1191
if(not good_flags(if_entry->d_name, &ifr)){
1198
* This function determines if a directory entry in /sys/class/net
1199
* corresponds to an acceptable network device which is up.
1200
* (This function is passed to scandir(3) as a filter function.)
1202
int up_interface(const struct dirent *if_entry){
1203
if(if_entry->d_name[0] == '.'){
1208
if(not get_flags(if_entry->d_name, &ifr)){
1210
fprintf_plus(stderr, "Failed to get flags for interface "
1211
"\"%s\"\n", if_entry->d_name);
1216
/* Reject down interfaces */
1217
if(not (ifr.ifr_flags & IFF_UP)){
1219
fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
1225
/* Reject non-running interfaces */
1226
if(not (ifr.ifr_flags & IFF_RUNNING)){
1228
fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
1234
if(not good_flags(if_entry->d_name, &ifr)){
1240
int notdotentries(const struct dirent *direntry){
1241
/* Skip "." and ".." */
1242
if(direntry->d_name[0] == '.'
1243
and (direntry->d_name[1] == '\0'
1244
or (direntry->d_name[1] == '.'
1245
and direntry->d_name[2] == '\0'))){
1251
/* Is this directory entry a runnable program? */
1252
int runnable_hook(const struct dirent *direntry){
1257
if((direntry->d_name)[0] == '\0'){
1262
sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1263
"abcdefghijklmnopqrstuvwxyz"
1266
if((direntry->d_name)[sret] != '\0'){
1267
/* Contains non-allowed characters */
1269
fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
1275
char *fullname = NULL;
1276
ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1278
perror_plus("asprintf");
1282
ret = stat(fullname, &st);
1285
perror_plus("Could not stat hook");
1289
if(not (S_ISREG(st.st_mode))){
1290
/* Not a regular file */
1292
fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
1297
if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1298
/* Not executable */
1300
fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
1306
fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
1312
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1314
struct timespec now;
1315
struct timespec waited_time;
1316
intmax_t block_time;
1319
if(mc.current_server == NULL){
1321
fprintf_plus(stderr, "Wait until first server is found."
1324
ret = avahi_simple_poll_iterate(s, -1);
1327
fprintf_plus(stderr, "Check current_server if we should run"
1330
/* the current time */
1331
ret = clock_gettime(CLOCK_MONOTONIC, &now);
1333
perror_plus("clock_gettime");
1336
/* Calculating in ms how long time between now and server
1337
who we visted longest time ago. Now - last seen. */
1338
waited_time.tv_sec = (now.tv_sec
1339
- mc.current_server->last_seen.tv_sec);
1340
waited_time.tv_nsec = (now.tv_nsec
1341
- mc.current_server->last_seen.tv_nsec);
1342
/* total time is 10s/10,000ms.
1343
Converting to s from ms by dividing by 1,000,
1344
and ns to ms by dividing by 1,000,000. */
1345
block_time = ((retry_interval
1346
- ((intmax_t)waited_time.tv_sec * 1000))
1347
- ((intmax_t)waited_time.tv_nsec / 1000000));
1350
fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1354
if(block_time <= 0){
1355
ret = start_mandos_communication(mc.current_server->ip,
1356
mc.current_server->port,
1357
mc.current_server->if_index,
1358
mc.current_server->af);
1360
avahi_simple_poll_quit(mc.simple_poll);
1363
ret = clock_gettime(CLOCK_MONOTONIC,
1364
&mc.current_server->last_seen);
1366
perror_plus("clock_gettime");
1369
mc.current_server = mc.current_server->next;
1370
block_time = 0; /* Call avahi to find new Mandos
1371
servers, but don't block */
1374
ret = avahi_simple_poll_iterate(s, (int)block_time);
1377
if (ret > 0 or errno != EINTR){
1378
return (ret != 1) ? ret : 0;
1384
bool run_network_hooks(const char *mode, const char *interface,
1386
struct dirent **direntries;
1387
struct dirent *direntry;
1389
int numhooks = scandir(hookdir, &direntries, runnable_hook,
1392
perror_plus("scandir");
1394
int devnull = open("/dev/null", O_RDONLY);
1395
for(int i = 0; i < numhooks; i++){
1396
direntry = direntries[i];
1397
char *fullname = NULL;
1398
ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1400
perror_plus("asprintf");
1404
fprintf_plus(stderr, "Running network hook \"%s\"\n",
1407
pid_t hook_pid = fork();
1410
/* Raise privileges */
1414
perror_plus("seteuid");
1416
/* Raise privileges even more */
1420
perror_plus("setuid");
1426
perror_plus("setgid");
1428
/* Reset supplementary groups */
1430
ret = setgroups(0, NULL);
1432
perror_plus("setgroups");
1434
fprintf_plus(stderr, "Child: getuid() = %d\n", getuid());
1435
fprintf_plus(stderr, "Child: geteuid() = %d\n", geteuid());
1436
dup2(devnull, STDIN_FILENO);
1438
dup2(STDERR_FILENO, STDOUT_FILENO);
1439
ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1441
perror_plus("setenv");
1444
ret = setenv("DEVICE", interface, 1);
1446
perror_plus("setenv");
1449
ret = setenv("VERBOSE", debug ? "1" : "0", 1);
1451
perror_plus("setenv");
1454
ret = setenv("MODE", mode, 1);
1456
perror_plus("setenv");
1460
ret = asprintf(&delaystring, "%f", delay);
1462
perror_plus("asprintf");
1465
ret = setenv("DELAY", delaystring, 1);
1468
perror_plus("setenv");
1472
ret = execl(fullname, direntry->d_name, mode, NULL);
1473
perror_plus("execl");
1476
if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1477
perror_plus("waitpid");
1481
if(WIFEXITED(status)){
1482
if(WEXITSTATUS(status) != 0){
1483
fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1484
" with status %d\n", direntry->d_name,
1485
WEXITSTATUS(status));
1489
} else if(WIFSIGNALED(status)){
1490
fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1491
" signal %d\n", direntry->d_name,
1496
fprintf_plus(stderr, "Warning: network hook \"%s\""
1497
" crashed\n", direntry->d_name);
1504
fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
764
1513
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 },
1514
AvahiSServiceBrowser *sb = NULL;
1519
int exitcode = EXIT_SUCCESS;
1520
const char *interface = "";
1521
struct ifreq network;
1523
bool take_down_interface = false;
1526
char tempdir[] = "/tmp/mandosXXXXXX";
1527
bool tempdir_created = false;
1528
AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1529
const char *seckey = PATHDIR "/" SECKEY;
1530
const char *pubkey = PATHDIR "/" PUBKEY;
1532
bool gnutls_initialized = false;
1533
bool gpgme_initialized = false;
1535
double retry_interval = 10; /* 10s between trying a server and
1536
retrying the same server again */
1538
struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1539
struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1544
/* Lower any group privileges we might have, just to be safe */
1548
perror_plus("setgid");
1551
/* Lower user privileges (temporarily) */
1555
perror_plus("seteuid");
1563
struct argp_option options[] = {
1564
{ .name = "debug", .key = 128,
1565
.doc = "Debug mode", .group = 3 },
1566
{ .name = "connect", .key = 'c',
1567
.arg = "ADDRESS:PORT",
1568
.doc = "Connect directly to a specific Mandos server",
1570
{ .name = "interface", .key = 'i',
1572
.doc = "Network interface that will be used to search for"
1575
{ .name = "seckey", .key = 's',
1577
.doc = "OpenPGP secret key file base name",
1579
{ .name = "pubkey", .key = 'p',
1581
.doc = "OpenPGP public key file base name",
1583
{ .name = "dh-bits", .key = 129,
1585
.doc = "Bit length of the prime number used in the"
1586
" Diffie-Hellman key exchange",
1588
{ .name = "priority", .key = 130,
1590
.doc = "GnuTLS priority string for the TLS handshake",
1592
{ .name = "delay", .key = 131,
1594
.doc = "Maximum delay to wait for interface startup",
1596
{ .name = "retry", .key = 132,
1598
.doc = "Retry interval used when denied by the mandos server",
1600
{ .name = "network-hook-dir", .key = 133,
1602
.doc = "Directory where network hooks are located",
1605
* These reproduce what we would get without ARGP_NO_HELP
1607
{ .name = "help", .key = '?',
1608
.doc = "Give this help list", .group = -1 },
1609
{ .name = "usage", .key = -3,
1610
.doc = "Give a short usage message", .group = -1 },
1611
{ .name = "version", .key = 'V',
1612
.doc = "Print program version", .group = -1 },
1616
error_t parse_opt(int key, char *arg,
1617
struct argp_state *state){
1620
case 128: /* --debug */
1623
case 'c': /* --connect */
1626
case 'i': /* --interface */
1629
case 's': /* --seckey */
1632
case 'p': /* --pubkey */
1635
case 129: /* --dh-bits */
1637
tmpmax = strtoimax(arg, &tmp, 10);
1638
if(errno != 0 or tmp == arg or *tmp != '\0'
1639
or tmpmax != (typeof(mc.dh_bits))tmpmax){
1640
argp_error(state, "Bad number of DH bits");
1642
mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1644
case 130: /* --priority */
1647
case 131: /* --delay */
1649
delay = strtof(arg, &tmp);
1650
if(errno != 0 or tmp == arg or *tmp != '\0'){
1651
argp_error(state, "Bad delay");
1653
case 132: /* --retry */
1655
retry_interval = strtod(arg, &tmp);
1656
if(errno != 0 or tmp == arg or *tmp != '\0'
1657
or (retry_interval * 1000) > INT_MAX
1658
or retry_interval < 0){
1659
argp_error(state, "Bad retry interval");
1662
case 133: /* --network-hook-dir */
1666
* These reproduce what we would get without ARGP_NO_HELP
1668
case '?': /* --help */
1669
argp_state_help(state, state->out_stream,
1670
(ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
1671
& ~(unsigned int)ARGP_HELP_EXIT_OK);
1672
case -3: /* --usage */
1673
argp_state_help(state, state->out_stream,
1674
ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1675
case 'V': /* --version */
1676
fprintf_plus(state->out_stream,
1677
"Mandos plugin mandos-client: ");
1678
fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1679
exit(argp_err_exit_status);
1682
return ARGP_ERR_UNKNOWN;
1687
struct argp argp = { .options = options, .parser = parse_opt,
1689
.doc = "Mandos client -- Get and decrypt"
1690
" passwords from a Mandos server" };
1691
ret = argp_parse(&argp, argc, argv,
1692
ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
1699
perror_plus("argp_parse");
1700
exitcode = EX_OSERR;
1703
exitcode = EX_USAGE;
1709
/* Work around Debian bug #633582:
1710
<http://bugs.debian.org/633582> */
1712
/* Re-raise priviliges */
1716
perror_plus("seteuid");
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");
1720
if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1721
int seckey_fd = open(seckey, O_RDONLY);
1722
if(seckey_fd == -1){
1723
perror_plus("open");
1725
ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1727
perror_plus("fstat");
1729
if(S_ISREG(st.st_mode)
1730
and st.st_uid == 0 and st.st_gid == 0){
1731
ret = fchown(seckey_fd, uid, gid);
1733
perror_plus("fchown");
1737
TEMP_FAILURE_RETRY(close(seckey_fd));
1741
if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1742
int pubkey_fd = open(pubkey, O_RDONLY);
1743
if(pubkey_fd == -1){
1744
perror_plus("open");
1746
ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1748
perror_plus("fstat");
1750
if(S_ISREG(st.st_mode)
1751
and st.st_uid == 0 and st.st_gid == 0){
1752
ret = fchown(pubkey_fd, uid, gid);
1754
perror_plus("fchown");
1758
TEMP_FAILURE_RETRY(close(pubkey_fd));
1762
/* Lower privileges */
1766
perror_plus("seteuid");
1771
/* Run network hooks */
1772
if(not run_network_hooks("start", interface, delay)){
1777
avahi_set_log_function(empty_log);
1780
if(interface[0] == '\0'){
1781
struct dirent **direntries;
1782
/* First look for interfaces that are up */
1783
ret = scandir(sys_class_net, &direntries, up_interface,
1786
/* No up interfaces, look for any good interfaces */
1788
ret = scandir(sys_class_net, &direntries, good_interface,
1792
/* Pick the first interface returned */
1793
interface = strdup(direntries[0]->d_name);
1795
fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1797
if(interface == NULL){
1798
perror_plus("malloc");
869
1800
exitcode = EXIT_FAILURE;
874
pubkeyfile = combinepath(keydir, pubkeyfile);
875
if (pubkeyfile == NULL){
876
perror("combinepath");
1806
fprintf_plus(stderr, "Could not find a network interface\n");
877
1807
exitcode = EXIT_FAILURE;
881
seckeyfile = combinepath(keydir, seckeyfile);
882
if (seckeyfile == NULL){
883
perror("combinepath");
887
ret = init_gnutls_global(&mc, pubkeyfile, seckeyfile);
889
fprintf(stderr, "init_gnutls_global\n");
892
gnutls_initalized = true;
895
/* If the interface is down, bring it up */
897
sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
900
exitcode = EXIT_FAILURE;
903
strcpy(network.ifr_name, interface); /* Spurious warning */
904
ret = ioctl(sd, SIOCGIFFLAGS, &network);
906
perror("ioctl SIOCGIFFLAGS");
907
exitcode = EXIT_FAILURE;
910
if((network.ifr_flags & IFF_UP) == 0){
911
network.ifr_flags |= IFF_UP;
912
ret = ioctl(sd, SIOCSIFFLAGS, &network);
914
perror("ioctl SIOCSIFFLAGS");
915
exitcode = EXIT_FAILURE;
1812
/* Initialize Avahi early so avahi_simple_poll_quit() can be called
1813
from the signal handler */
1814
/* Initialize the pseudo-RNG for Avahi */
1815
srand((unsigned int) time(NULL));
1816
mc.simple_poll = avahi_simple_poll_new();
1817
if(mc.simple_poll == NULL){
1818
fprintf_plus(stderr,
1819
"Avahi: Failed to create simple poll object.\n");
1820
exitcode = EX_UNAVAILABLE;
1824
sigemptyset(&sigterm_action.sa_mask);
1825
ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1827
perror_plus("sigaddset");
1828
exitcode = EX_OSERR;
1831
ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1833
perror_plus("sigaddset");
1834
exitcode = EX_OSERR;
1837
ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1839
perror_plus("sigaddset");
1840
exitcode = EX_OSERR;
1843
/* Need to check if the handler is SIG_IGN before handling:
1844
| [[info:libc:Initial Signal Actions]] |
1845
| [[info:libc:Basic Signal Handling]] |
1847
ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1849
perror_plus("sigaction");
1852
if(old_sigterm_action.sa_handler != SIG_IGN){
1853
ret = sigaction(SIGINT, &sigterm_action, NULL);
1855
perror_plus("sigaction");
1856
exitcode = EX_OSERR;
1860
ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1862
perror_plus("sigaction");
1865
if(old_sigterm_action.sa_handler != SIG_IGN){
1866
ret = sigaction(SIGHUP, &sigterm_action, NULL);
1868
perror_plus("sigaction");
1869
exitcode = EX_OSERR;
1873
ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1875
perror_plus("sigaction");
1878
if(old_sigterm_action.sa_handler != SIG_IGN){
1879
ret = sigaction(SIGTERM, &sigterm_action, NULL);
1881
perror_plus("sigaction");
1882
exitcode = EX_OSERR;
1887
/* If the interface is down, bring it up */
1888
if(strcmp(interface, "none") != 0){
935
1889
if_index = (AvahiIfIndex) if_nametoindex(interface);
936
1890
if(if_index == 0){
937
fprintf(stderr, "No such interface: \"%s\"\n", interface);
941
if(connect_to != NULL){
942
/* Connect directly, do not use Zeroconf */
943
/* (Mainly meant for debugging) */
944
char *address = strrchr(connect_to, ':');
946
fprintf(stderr, "No colon in address\n");
947
exitcode = EXIT_FAILURE;
951
uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
953
perror("Bad port number");
954
exitcode = EXIT_FAILURE;
958
address = connect_to;
959
ret = start_mandos_communication(address, port, if_index, &mc);
961
exitcode = EXIT_FAILURE;
963
exitcode = EXIT_SUCCESS;
969
avahi_set_log_function(empty_log);
972
/* Initialize the pseudo-RNG for Avahi */
973
srand((unsigned int) time(NULL));
975
/* Allocate main Avahi loop object */
976
mc.simple_poll = avahi_simple_poll_new();
977
if (mc.simple_poll == NULL) {
978
fprintf(stderr, "Avahi: Failed to create simple poll"
980
exitcode = EXIT_FAILURE;
985
AvahiServerConfig config;
986
/* Do not publish any local Zeroconf records */
987
avahi_server_config_init(&config);
988
config.publish_hinfo = 0;
989
config.publish_addresses = 0;
990
config.publish_workstation = 0;
991
config.publish_domain = 0;
993
/* Allocate a new server */
994
mc.server = avahi_server_new(avahi_simple_poll_get
995
(mc.simple_poll), &config, NULL,
998
/* Free the Avahi configuration data */
999
avahi_server_config_free(&config);
1002
/* Check if creating the Avahi server object succeeded */
1003
if (mc.server == NULL) {
1004
fprintf(stderr, "Failed to create Avahi server: %s\n",
1005
avahi_strerror(error));
1006
exitcode = EXIT_FAILURE;
1010
/* Create the Avahi service browser */
1011
sb = avahi_s_service_browser_new(mc.server, if_index,
1013
"_mandos._tcp", NULL, 0,
1014
browse_callback, &mc);
1016
fprintf(stderr, "Failed to create service browser: %s\n",
1017
avahi_strerror(avahi_server_errno(mc.server)));
1018
exitcode = EXIT_FAILURE;
1022
/* Run the main loop */
1025
fprintf(stderr, "Starting Avahi loop search\n");
1028
avahi_simple_poll_loop(mc.simple_poll);
1891
fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1892
exitcode = EX_UNAVAILABLE;
1900
/* Re-raise priviliges */
1904
perror_plus("seteuid");
1908
/* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1909
messages about the network interface to mess up the prompt */
1910
ret = klogctl(8, NULL, 5);
1911
bool restore_loglevel = true;
1913
restore_loglevel = false;
1914
perror_plus("klogctl");
1916
#endif /* __linux__ */
1918
sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1920
perror_plus("socket");
1921
exitcode = EX_OSERR;
1923
if(restore_loglevel){
1924
ret = klogctl(7, NULL, 0);
1926
perror_plus("klogctl");
1929
#endif /* __linux__ */
1930
/* Lower privileges */
1934
perror_plus("seteuid");
1938
strcpy(network.ifr_name, interface);
1939
ret = ioctl(sd, SIOCGIFFLAGS, &network);
1941
perror_plus("ioctl SIOCGIFFLAGS");
1943
if(restore_loglevel){
1944
ret = klogctl(7, NULL, 0);
1946
perror_plus("klogctl");
1949
#endif /* __linux__ */
1950
exitcode = EX_OSERR;
1951
/* Lower privileges */
1955
perror_plus("seteuid");
1959
if((network.ifr_flags & IFF_UP) == 0){
1960
network.ifr_flags |= IFF_UP;
1961
take_down_interface = true;
1962
ret = ioctl(sd, SIOCSIFFLAGS, &network);
1964
take_down_interface = false;
1965
perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1966
exitcode = EX_OSERR;
1968
if(restore_loglevel){
1969
ret = klogctl(7, NULL, 0);
1971
perror_plus("klogctl");
1974
#endif /* __linux__ */
1975
/* Lower privileges */
1979
perror_plus("seteuid");
1984
/* Sleep checking until interface is running.
1985
Check every 0.25s, up to total time of delay */
1986
for(int i=0; i < delay * 4; i++){
1987
ret = ioctl(sd, SIOCGIFFLAGS, &network);
1989
perror_plus("ioctl SIOCGIFFLAGS");
1990
} else if(network.ifr_flags & IFF_RUNNING){
1993
struct timespec sleeptime = { .tv_nsec = 250000000 };
1994
ret = nanosleep(&sleeptime, NULL);
1995
if(ret == -1 and errno != EINTR){
1996
perror_plus("nanosleep");
1999
if(not take_down_interface){
2000
/* We won't need the socket anymore */
2001
ret = (int)TEMP_FAILURE_RETRY(close(sd));
2003
perror_plus("close");
2007
if(restore_loglevel){
2008
/* Restores kernel loglevel to default */
2009
ret = klogctl(7, NULL, 0);
2011
perror_plus("klogctl");
2014
#endif /* __linux__ */
2015
/* Lower privileges */
2017
/* Lower privileges */
2020
perror_plus("seteuid");
2028
ret = init_gnutls_global(pubkey, seckey);
2030
fprintf_plus(stderr, "init_gnutls_global failed\n");
2031
exitcode = EX_UNAVAILABLE;
2034
gnutls_initialized = true;
2041
if(mkdtemp(tempdir) == NULL){
2042
perror_plus("mkdtemp");
2045
tempdir_created = true;
2051
if(not init_gpgme(pubkey, seckey, tempdir)){
2052
fprintf_plus(stderr, "init_gpgme failed\n");
2053
exitcode = EX_UNAVAILABLE;
2056
gpgme_initialized = true;
2063
if(connect_to != NULL){
2064
/* Connect directly, do not use Zeroconf */
2065
/* (Mainly meant for debugging) */
2066
char *address = strrchr(connect_to, ':');
2067
if(address == NULL){
2068
fprintf_plus(stderr, "No colon in address\n");
2069
exitcode = EX_USAGE;
2079
tmpmax = strtoimax(address+1, &tmp, 10);
2080
if(errno != 0 or tmp == address+1 or *tmp != '\0'
2081
or tmpmax != (uint16_t)tmpmax){
2082
fprintf_plus(stderr, "Bad port number\n");
2083
exitcode = EX_USAGE;
2091
port = (uint16_t)tmpmax;
2093
/* Colon in address indicates IPv6 */
2095
if(strchr(connect_to, ':') != NULL){
2097
/* Accept [] around IPv6 address - see RFC 5952 */
2098
if(connect_to[0] == '[' and address[-1] == ']')
2106
address = connect_to;
2112
while(not quit_now){
2113
ret = start_mandos_communication(address, port, if_index, af);
2114
if(quit_now or ret == 0){
2118
fprintf_plus(stderr, "Retrying in %d seconds\n",
2119
(int)retry_interval);
2121
sleep((int)retry_interval);
2125
exitcode = EXIT_SUCCESS;
2136
AvahiServerConfig config;
2137
/* Do not publish any local Zeroconf records */
2138
avahi_server_config_init(&config);
2139
config.publish_hinfo = 0;
2140
config.publish_addresses = 0;
2141
config.publish_workstation = 0;
2142
config.publish_domain = 0;
2144
/* Allocate a new server */
2145
mc.server = avahi_server_new(avahi_simple_poll_get
2146
(mc.simple_poll), &config, NULL,
2149
/* Free the Avahi configuration data */
2150
avahi_server_config_free(&config);
2153
/* Check if creating the Avahi server object succeeded */
2154
if(mc.server == NULL){
2155
fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2156
avahi_strerror(error));
2157
exitcode = EX_UNAVAILABLE;
2165
/* Create the Avahi service browser */
2166
sb = avahi_s_service_browser_new(mc.server, if_index,
2167
AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2168
NULL, 0, browse_callback, NULL);
2170
fprintf_plus(stderr, "Failed to create service browser: %s\n",
2171
avahi_strerror(avahi_server_errno(mc.server)));
2172
exitcode = EX_UNAVAILABLE;
2180
/* Run the main loop */
2183
fprintf_plus(stderr, "Starting Avahi loop search\n");
2186
ret = avahi_loop_with_timeout(mc.simple_poll,
2187
(int)(retry_interval * 1000));
2189
fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2190
(ret == 0) ? "successfully" : "with error");
1033
fprintf(stderr, "%s exiting\n", argv[0]);
1036
/* Cleanup things */
1038
avahi_s_service_browser_free(sb);
1040
if (mc.server != NULL)
1041
avahi_server_free(mc.server);
1043
if (mc.simple_poll != NULL)
1044
avahi_simple_poll_free(mc.simple_poll);
1048
if (gnutls_initalized){
1049
gnutls_certificate_free_credentials(mc.cred);
1050
gnutls_global_deinit ();
2196
fprintf_plus(stderr, "%s exiting\n", argv[0]);
2199
/* Cleanup things */
2201
avahi_s_service_browser_free(sb);
2203
if(mc.server != NULL)
2204
avahi_server_free(mc.server);
2206
if(mc.simple_poll != NULL)
2207
avahi_simple_poll_free(mc.simple_poll);
2209
if(gnutls_initialized){
2210
gnutls_certificate_free_credentials(mc.cred);
2211
gnutls_global_deinit();
2212
gnutls_dh_params_deinit(mc.dh_params);
2215
if(gpgme_initialized){
2216
gpgme_release(mc.ctx);
2219
/* Cleans up the circular linked list of Mandos servers the client
2221
if(mc.current_server != NULL){
2222
mc.current_server->prev->next = NULL;
2223
while(mc.current_server != NULL){
2224
server *next = mc.current_server->next;
2225
free(mc.current_server);
2226
mc.current_server = next;
2230
/* Run network hooks */
2231
run_network_hooks("stop", interface, delay);
2233
/* Re-raise priviliges */
2238
perror_plus("seteuid");
2241
/* Take down the network interface */
2242
if(take_down_interface and geteuid() == 0){
2243
ret = ioctl(sd, SIOCGIFFLAGS, &network);
2245
perror_plus("ioctl SIOCGIFFLAGS");
2246
} else if(network.ifr_flags & IFF_UP){
2247
network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2248
ret = ioctl(sd, SIOCSIFFLAGS, &network);
2250
perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
2253
ret = (int)TEMP_FAILURE_RETRY(close(sd));
2255
perror_plus("close");
2259
/* Lower privileges permanently */
2263
perror_plus("setuid");
2266
/* Removes the GPGME temp directory and all files inside */
2267
if(tempdir_created){
2268
struct dirent **direntries = NULL;
2269
struct dirent *direntry = NULL;
2270
int numentries = scandir(tempdir, &direntries, notdotentries,
2272
if (numentries > 0){
2273
for(int i = 0; i < numentries; i++){
2274
direntry = direntries[i];
2275
char *fullname = NULL;
2276
ret = asprintf(&fullname, "%s/%s", tempdir,
2279
perror_plus("asprintf");
2282
ret = remove(fullname);
2284
fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2291
/* need to clean even if 0 because man page doesn't specify */
2293
if (numentries == -1){
2294
perror_plus("scandir");
2296
ret = rmdir(tempdir);
2297
if(ret == -1 and errno != ENOENT){
2298
perror_plus("rmdir");
2303
sigemptyset(&old_sigterm_action.sa_mask);
2304
old_sigterm_action.sa_handler = SIG_DFL;
2305
ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
2306
&old_sigterm_action,
2309
perror_plus("sigaction");
2312
ret = raise(signal_received);
2313
} while(ret != 0 and errno == EINTR);
2315
perror_plus("raise");
2318
TEMP_FAILURE_RETRY(pause());