101
47
#include <avahi-common/malloc.h>
102
48
#include <avahi-common/error.h>
105
#include <gnutls/gnutls.h> /* All GnuTLS types, constants and
108
init_gnutls_session(),
110
#include <gnutls/openpgp.h>
111
/* gnutls_certificate_set_openpgp_key_file(),
112
GNUTLS_OPENPGP_FMT_BASE64 */
115
#include <gpgme.h> /* All GPGME types, constants and
118
GPGME_PROTOCOL_OpenPGP,
51
#include <sys/types.h> /* socket(), inet_pton() */
52
#include <sys/socket.h> /* socket(), struct sockaddr_in6,
53
struct in6_addr, inet_pton() */
54
#include <gnutls/gnutls.h> /* All GnuTLS stuff */
55
#include <gnutls/openpgp.h> /* GnuTLS with openpgp stuff */
57
#include <unistd.h> /* close() */
58
#include <netinet/in.h>
59
#include <stdbool.h> /* true */
60
#include <string.h> /* memset */
61
#include <arpa/inet.h> /* inet_pton() */
62
#include <iso646.h> /* not */
65
#include <errno.h> /* perror() */
72
#define CERT_ROOT "/conf/conf.d/cryptkeyreq/"
74
#define CERTFILE CERT_ROOT "openpgp-client.txt"
75
#define KEYFILE CERT_ROOT "openpgp-client-key.txt"
121
76
#define BUFFER_SIZE 256
123
#define PATHDIR "/conf/conf.d/mandos"
124
#define SECKEY "seckey.txt"
125
#define PUBKEY "pubkey.txt"
126
#define HOOKDIR "/lib/mandos/network-hooks.d"
128
79
bool debug = false;
129
static const char mandos_protocol_version[] = "1";
130
const char *argp_program_version = "mandos-client " VERSION;
131
const char *argp_program_bug_address = "<mandos@recompile.se>";
132
static const char sys_class_net[] = "/sys/class/net";
133
char *connect_to = NULL;
135
/* Doubly linked list that need to be circularly linked when used */
136
typedef struct server{
139
AvahiIfIndex if_index;
141
struct timespec last_seen;
146
/* Used for passing in values through the Avahi callback functions */
148
AvahiSimplePoll *simple_poll;
82
gnutls_session_t session;
150
83
gnutls_certificate_credentials_t cred;
151
unsigned int dh_bits;
152
84
gnutls_dh_params_t dh_params;
153
const char *priority;
88
ssize_t pgp_packet_decrypt (char *packet, size_t packet_size,
89
char **new_packet, const char *homedir){
90
gpgme_data_t dh_crypto, dh_plain;
155
server *current_server;
158
/* global context so signal handler can reach it*/
159
mandos_context mc = { .simple_poll = NULL, .server = NULL,
160
.dh_bits = 1024, .priority = "SECURE256"
161
":!CTYPE-X.509:+CTYPE-OPENPGP",
162
.current_server = NULL };
164
sig_atomic_t quit_now = 0;
165
int signal_received = 0;
167
/* Function to use when printing errors */
168
void perror_plus(const char *print_text){
169
fprintf(stderr, "Mandos plugin %s: ",
170
program_invocation_short_name);
175
* Make additional room in "buffer" for at least BUFFER_SIZE more
176
* bytes. "buffer_capacity" is how much is currently allocated,
177
* "buffer_length" is how much is already used.
179
size_t incbuffer(char **buffer, size_t buffer_length,
180
size_t buffer_capacity){
181
if(buffer_length + BUFFER_SIZE > buffer_capacity){
182
*buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
186
buffer_capacity += BUFFER_SIZE;
188
return buffer_capacity;
191
/* Add server to set of servers to retry periodically */
192
int add_server(const char *ip, uint16_t port,
193
AvahiIfIndex if_index,
196
server *new_server = malloc(sizeof(server));
197
if(new_server == NULL){
198
perror_plus("malloc");
201
*new_server = (server){ .ip = strdup(ip),
203
.if_index = if_index,
205
if(new_server->ip == NULL){
206
perror_plus("strdup");
209
/* Special case of first server */
210
if (mc.current_server == NULL){
211
new_server->next = new_server;
212
new_server->prev = new_server;
213
mc.current_server = new_server;
214
/* Place the new server last in the list */
216
new_server->next = mc.current_server;
217
new_server->prev = mc.current_server->prev;
218
new_server->prev->next = new_server;
219
mc.current_server->prev = new_server;
221
ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
223
perror_plus("clock_gettime");
232
static bool init_gpgme(const char *seckey,
233
const char *pubkey, const char *tempdir){
94
ssize_t new_packet_capacity = 0;
95
ssize_t new_packet_length = 0;
235
96
gpgme_engine_info_t engine_info;
239
* Helper function to insert pub and seckey to the engine keyring.
241
bool import_key(const char *filename){
244
gpgme_data_t pgp_data;
246
fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
252
rc = gpgme_data_new_from_fd(&pgp_data, fd);
253
if(rc != GPG_ERR_NO_ERROR){
254
fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
255
gpgme_strsource(rc), gpgme_strerror(rc));
259
rc = gpgme_op_import(mc.ctx, pgp_data);
260
if(rc != GPG_ERR_NO_ERROR){
261
fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
262
gpgme_strsource(rc), gpgme_strerror(rc));
266
ret = (int)TEMP_FAILURE_RETRY(close(fd));
268
perror_plus("close");
270
gpgme_data_release(pgp_data);
275
fprintf(stderr, "Initializing GPGME\n");
99
fprintf(stderr, "Trying to decrypt OpenPGP packet\n");
279
103
gpgme_check_version(NULL);
280
rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
281
if(rc != GPG_ERR_NO_ERROR){
282
fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
283
gpgme_strsource(rc), gpgme_strerror(rc));
104
gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
287
/* Set GPGME home directory for the OpenPGP engine only */
288
rc = gpgme_get_engine_info(&engine_info);
289
if(rc != GPG_ERR_NO_ERROR){
106
/* Set GPGME home directory */
107
rc = gpgme_get_engine_info (&engine_info);
108
if (rc != GPG_ERR_NO_ERROR){
290
109
fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
291
110
gpgme_strsource(rc), gpgme_strerror(rc));
294
113
while(engine_info != NULL){
295
114
if(engine_info->protocol == GPGME_PROTOCOL_OpenPGP){
296
115
gpgme_set_engine_info(GPGME_PROTOCOL_OpenPGP,
297
engine_info->file_name, tempdir);
116
engine_info->file_name, homedir);
300
119
engine_info = engine_info->next;
302
121
if(engine_info == NULL){
303
fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
307
/* Create new GPGME "context" */
308
rc = gpgme_new(&(mc.ctx));
309
if(rc != GPG_ERR_NO_ERROR){
310
fprintf(stderr, "bad gpgme_new: %s: %s\n",
311
gpgme_strsource(rc), gpgme_strerror(rc));
315
if(not import_key(pubkey) or not import_key(seckey)){
323
* Decrypt OpenPGP data.
324
* Returns -1 on error
326
static ssize_t pgp_packet_decrypt(const char *cryptotext,
329
gpgme_data_t dh_crypto, dh_plain;
332
size_t plaintext_capacity = 0;
333
ssize_t plaintext_length = 0;
336
fprintf(stderr, "Trying to decrypt OpenPGP data\n");
339
/* Create new GPGME data buffer from memory cryptotext */
340
rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
342
if(rc != GPG_ERR_NO_ERROR){
122
fprintf(stderr, "Could not set home dir to %s\n", homedir);
126
/* Create new GPGME data buffer from packet buffer */
127
rc = gpgme_data_new_from_mem(&dh_crypto, packet, packet_size, 0);
128
if (rc != GPG_ERR_NO_ERROR){
343
129
fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
344
130
gpgme_strsource(rc), gpgme_strerror(rc));
394
fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
192
/* Delete the GPGME FILE pointer cryptotext data buffer */
193
gpgme_data_release(dh_crypto);
397
195
/* Seek back to the beginning of the GPGME plaintext data buffer */
398
if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
399
perror_plus("gpgme_data_seek");
400
plaintext_length = -1;
196
gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET);
406
plaintext_capacity = incbuffer(plaintext,
407
(size_t)plaintext_length,
409
if(plaintext_capacity == 0){
410
perror_plus("incbuffer");
411
plaintext_length = -1;
200
if (new_packet_length + BUFFER_SIZE > new_packet_capacity){
201
*new_packet = realloc(*new_packet,
202
(unsigned int)new_packet_capacity
204
if (*new_packet == NULL){
208
new_packet_capacity += BUFFER_SIZE;
415
ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
211
ret = gpgme_data_read(dh_plain, *new_packet + new_packet_length,
417
213
/* Print the data, if any */
423
perror_plus("gpgme_data_read");
424
plaintext_length = -1;
427
plaintext_length += ret;
431
fprintf(stderr, "Decrypted password is: ");
432
for(ssize_t i = 0; i < plaintext_length; i++){
433
fprintf(stderr, "%02hhX ", (*plaintext)[i]);
435
fprintf(stderr, "\n");
440
/* Delete the GPGME cryptotext data buffer */
441
gpgme_data_release(dh_crypto);
218
perror("gpgme_data_read");
221
new_packet_length += ret;
224
/* FIXME: check characters before printing to screen so to not print
225
terminal control characters */
227
/* fprintf(stderr, "decrypted password is: "); */
228
/* fwrite(*new_packet, 1, new_packet_length, stderr); */
229
/* fprintf(stderr, "\n"); */
443
232
/* Delete the GPGME plaintext data buffer */
444
233
gpgme_data_release(dh_plain);
445
return plaintext_length;
234
return new_packet_length;
448
static const char * safer_gnutls_strerror(int value){
449
const char *ret = gnutls_strerror(value); /* Spurious warning from
450
-Wunreachable-code */
237
static const char * safer_gnutls_strerror (int value) {
238
const char *ret = gnutls_strerror (value);
452
240
ret = "(unknown)";
456
/* GnuTLS log function callback */
457
static void debuggnutls(__attribute__((unused)) int level,
459
fprintf(stderr, "GnuTLS: %s", string);
244
void debuggnutls(__attribute__((unused)) int level,
246
fprintf(stderr, "%s", string);
462
static int init_gnutls_global(const char *pubkeyfilename,
463
const char *seckeyfilename){
249
int initgnutls(encrypted_session *es){
467
254
fprintf(stderr, "Initializing GnuTLS\n");
470
ret = gnutls_global_init();
471
if(ret != GNUTLS_E_SUCCESS){
472
fprintf(stderr, "GnuTLS global_init: %s\n",
473
safer_gnutls_strerror(ret));
257
if ((ret = gnutls_global_init ())
258
!= GNUTLS_E_SUCCESS) {
259
fprintf (stderr, "global_init: %s\n", safer_gnutls_strerror(ret));
478
/* "Use a log level over 10 to enable all debugging options."
481
264
gnutls_global_set_log_level(11);
482
265
gnutls_global_set_log_function(debuggnutls);
485
/* OpenPGP credentials */
486
ret = gnutls_certificate_allocate_credentials(&mc.cred);
487
if(ret != GNUTLS_E_SUCCESS){
488
fprintf(stderr, "GnuTLS memory error: %s\n",
489
safer_gnutls_strerror(ret));
490
gnutls_global_deinit();
268
/* openpgp credentials */
269
if ((ret = gnutls_certificate_allocate_credentials (&es->cred))
270
!= GNUTLS_E_SUCCESS) {
271
fprintf (stderr, "memory error: %s\n",
272
safer_gnutls_strerror(ret));
495
fprintf(stderr, "Attempting to use OpenPGP public key %s and"
496
" secret key %s as GnuTLS credentials\n", pubkeyfilename,
277
fprintf(stderr, "Attempting to use OpenPGP certificate %s"
278
" and keyfile %s as GnuTLS credentials\n", CERTFILE,
500
282
ret = gnutls_certificate_set_openpgp_key_file
501
(mc.cred, pubkeyfilename, seckeyfilename,
502
GNUTLS_OPENPGP_FMT_BASE64);
503
if(ret != GNUTLS_E_SUCCESS){
505
"Error[%d] while reading the OpenPGP key pair ('%s',"
506
" '%s')\n", ret, pubkeyfilename, seckeyfilename);
507
fprintf(stderr, "The GnuTLS error is: %s\n",
508
safer_gnutls_strerror(ret));
512
/* GnuTLS server initialization */
513
ret = gnutls_dh_params_init(&mc.dh_params);
514
if(ret != GNUTLS_E_SUCCESS){
515
fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
516
" %s\n", safer_gnutls_strerror(ret));
519
ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
520
if(ret != GNUTLS_E_SUCCESS){
521
fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
522
safer_gnutls_strerror(ret));
526
gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
532
gnutls_certificate_free_credentials(mc.cred);
533
gnutls_global_deinit();
534
gnutls_dh_params_deinit(mc.dh_params);
538
static int init_gnutls_session(gnutls_session_t *session){
540
/* GnuTLS session creation */
542
ret = gnutls_init(session, GNUTLS_SERVER);
546
} while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
547
if(ret != GNUTLS_E_SUCCESS){
283
(es->cred, CERTFILE, KEYFILE, GNUTLS_OPENPGP_FMT_BASE64);
284
if (ret != GNUTLS_E_SUCCESS) {
286
(stderr, "Error[%d] while reading the OpenPGP key pair ('%s',"
288
ret, CERTFILE, KEYFILE);
289
fprintf(stdout, "The Error is: %s\n",
290
safer_gnutls_strerror(ret));
294
//GnuTLS server initialization
295
if ((ret = gnutls_dh_params_init (&es->dh_params))
296
!= GNUTLS_E_SUCCESS) {
297
fprintf (stderr, "Error in dh parameter initialization: %s\n",
298
safer_gnutls_strerror(ret));
302
if ((ret = gnutls_dh_params_generate2 (es->dh_params, DH_BITS))
303
!= GNUTLS_E_SUCCESS) {
304
fprintf (stderr, "Error in prime generation: %s\n",
305
safer_gnutls_strerror(ret));
309
gnutls_certificate_set_dh_params (es->cred, es->dh_params);
311
// GnuTLS session creation
312
if ((ret = gnutls_init (&es->session, GNUTLS_SERVER))
313
!= GNUTLS_E_SUCCESS){
548
314
fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
549
315
safer_gnutls_strerror(ret));
555
ret = gnutls_priority_set_direct(*session, mc.priority, &err);
557
gnutls_deinit(*session);
560
} while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
561
if(ret != GNUTLS_E_SUCCESS){
562
fprintf(stderr, "Syntax error at: %s\n", err);
563
fprintf(stderr, "GnuTLS error: %s\n",
564
safer_gnutls_strerror(ret));
565
gnutls_deinit(*session);
318
if ((ret = gnutls_priority_set_direct (es->session, "NORMAL", &err))
319
!= GNUTLS_E_SUCCESS) {
320
fprintf(stderr, "Syntax error at: %s\n", err);
321
fprintf(stderr, "GnuTLS error: %s\n",
322
safer_gnutls_strerror(ret));
571
ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
574
gnutls_deinit(*session);
577
} while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
578
if(ret != GNUTLS_E_SUCCESS){
579
fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
326
if ((ret = gnutls_credentials_set
327
(es->session, GNUTLS_CRD_CERTIFICATE, es->cred))
328
!= GNUTLS_E_SUCCESS) {
329
fprintf(stderr, "Error setting a credentials set: %s\n",
580
330
safer_gnutls_strerror(ret));
581
gnutls_deinit(*session);
585
334
/* ignore client certificate if any. */
586
gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
335
gnutls_certificate_server_set_request (es->session,
588
gnutls_dh_set_prime_bits(*session, mc.dh_bits);
338
gnutls_dh_set_prime_bits (es->session, DH_BITS);
593
/* Avahi log function callback */
594
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
595
__attribute__((unused)) const char *txt){}
343
void empty_log(__attribute__((unused)) AvahiLogLevel level,
344
__attribute__((unused)) const char *txt){}
597
/* Called when a Mandos server is found */
598
static int start_mandos_communication(const char *ip, uint16_t port,
599
AvahiIfIndex if_index,
601
int ret, tcp_sd = -1;
604
struct sockaddr_in in;
605
struct sockaddr_in6 in6;
346
int start_mandos_communication(const char *ip, uint16_t port,
347
unsigned int if_index){
349
struct sockaddr_in6 to;
350
encrypted_session es;
607
351
char *buffer = NULL;
608
char *decrypted_buffer = NULL;
352
char *decrypted_buffer;
609
353
size_t buffer_length = 0;
610
354
size_t buffer_capacity = 0;
613
gnutls_session_t session;
614
int pf; /* Protocol family */
631
fprintf(stderr, "Bad address family: %d\n", af);
636
ret = init_gnutls_session(&session);
642
fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
646
tcp_sd = socket(pf, SOCK_STREAM, 0);
649
perror_plus("socket");
659
memset(&to, 0, sizeof(to));
661
to.in6.sin6_family = (sa_family_t)af;
662
ret = inet_pton(af, ip, &to.in6.sin6_addr);
664
to.in.sin_family = (sa_family_t)af;
665
ret = inet_pton(af, ip, &to.in.sin_addr);
669
perror_plus("inet_pton");
355
ssize_t decrypted_buffer_size;
358
char interface[IF_NAMESIZE];
361
fprintf(stderr, "Setting up a tcp connection to %s\n", ip);
364
tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
370
if(if_indextoname(if_index, interface) == NULL){
372
perror("if_indextoname");
378
fprintf(stderr, "Binding to interface %s\n", interface);
381
memset(&to,0,sizeof(to)); /* Spurious warning */
382
to.sin6_family = AF_INET6;
383
ret = inet_pton(AF_INET6, ip, &to.sin6_addr);
675
389
fprintf(stderr, "Bad address: %s\n", ip);
680
to.in6.sin6_port = htons(port); /* Spurious warnings from
682
-Wunreachable-code */
684
if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
685
(&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
687
if(if_index == AVAHI_IF_UNSPEC){
688
fprintf(stderr, "An IPv6 link-local address is incomplete"
689
" without a network interface\n");
693
/* Set the network interface number as scope */
694
to.in6.sin6_scope_id = (uint32_t)if_index;
697
to.in.sin_port = htons(port); /* Spurious warnings from
699
-Wunreachable-code */
392
to.sin6_port = htons(port); /* Spurious warning */
394
to.sin6_scope_id = (uint32_t)if_index;
708
if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
709
char interface[IF_NAMESIZE];
710
if(if_indextoname((unsigned int)if_index, interface) == NULL){
711
perror_plus("if_indextoname");
713
fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
714
ip, interface, port);
717
fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
720
char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
721
INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
724
pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
727
pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
731
perror_plus("inet_ntop");
733
if(strcmp(addrstr, ip) != 0){
734
fprintf(stderr, "Canonical address form: %s\n", addrstr);
745
ret = connect(tcp_sd, &to.in6, sizeof(to));
747
ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
750
if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
752
perror_plus("connect");
763
const char *out = mandos_protocol_version;
766
size_t out_size = strlen(out);
767
ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
768
out_size - written));
771
perror_plus("write");
775
written += (size_t)ret;
776
if(written < out_size){
779
if(out == mandos_protocol_version){
397
fprintf(stderr, "Connection to: %s\n", ip);
400
ret = connect(tcp_sd, (struct sockaddr *) &to, sizeof(to));
406
ret = initgnutls (&es);
412
gnutls_transport_set_ptr (es.session,
413
(gnutls_transport_ptr_t) tcp_sd);
794
416
fprintf(stderr, "Establishing TLS session with %s\n", ip);
802
/* Spurious warning from -Wint-to-pointer-cast */
803
gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
811
ret = gnutls_handshake(session);
816
} while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
818
if(ret != GNUTLS_E_SUCCESS){
419
ret = gnutls_handshake (es.session);
421
if (ret != GNUTLS_E_SUCCESS){
820
fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
423
fprintf(stderr, "\n*** Handshake failed ***\n");
827
/* Read OpenPGP packet that contains the wanted password */
430
//Retrieve OpenPGP packet that contains the wanted password
830
fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
433
fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
841
buffer_capacity = incbuffer(&buffer, buffer_length,
843
if(buffer_capacity == 0){
845
perror_plus("incbuffer");
855
sret = gnutls_record_recv(session, buffer+buffer_length,
438
if (buffer_length + BUFFER_SIZE > buffer_capacity){
439
buffer = realloc(buffer, buffer_capacity + BUFFER_SIZE);
444
buffer_capacity += BUFFER_SIZE;
447
ret = gnutls_record_recv
448
(es.session, buffer+buffer_length, BUFFER_SIZE);
862
454
case GNUTLS_E_INTERRUPTED:
863
455
case GNUTLS_E_AGAIN:
865
457
case GNUTLS_E_REHANDSHAKE:
867
ret = gnutls_handshake(session);
873
} while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
875
fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
458
ret = gnutls_handshake (es.session);
460
fprintf(stderr, "\n*** Handshake failed ***\n");
882
467
fprintf(stderr, "Unknown error while reading data from"
883
" encrypted session with Mandos server\n");
884
gnutls_bye(session, GNUTLS_SHUT_RDWR);
468
" encrypted session with mandos server\n");
470
gnutls_bye (es.session, GNUTLS_SHUT_RDWR);
889
buffer_length += (size_t) sret;
894
fprintf(stderr, "Closing TLS session\n");
903
ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
908
} while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
910
if(buffer_length > 0){
911
ssize_t decrypted_buffer_size;
474
buffer_length += (size_t) ret;
478
if (buffer_length > 0){
912
479
decrypted_buffer_size = pgp_packet_decrypt(buffer,
915
if(decrypted_buffer_size >= 0){
918
while(written < (size_t) decrypted_buffer_size){
924
ret = (int)fwrite(decrypted_buffer + written, 1,
925
(size_t)decrypted_buffer_size - written,
483
if (decrypted_buffer_size >= 0){
484
while(written < decrypted_buffer_size){
485
ret = (int)fwrite (decrypted_buffer + written, 1,
486
(size_t)decrypted_buffer_size - written,
927
488
if(ret == 0 and ferror(stdout)){
930
490
fprintf(stderr, "Error writing encrypted data: %s\n",
931
491
strerror(errno));
936
496
written += (size_t)ret;
942
/* Shutdown procedure */
947
free(decrypted_buffer);
950
ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
956
perror_plus("close");
958
gnutls_deinit(session);
498
free(decrypted_buffer);
507
fprintf(stderr, "Closing TLS session\n");
511
gnutls_bye (es.session, GNUTLS_SHUT_RDWR);
514
gnutls_deinit (es.session);
515
gnutls_certificate_free_credentials (es.cred);
516
gnutls_global_deinit ();
968
static void resolve_callback(AvahiSServiceResolver *r,
969
AvahiIfIndex interface,
971
AvahiResolverEvent event,
975
const char *host_name,
976
const AvahiAddress *address,
978
AVAHI_GCC_UNUSED AvahiStringList *txt,
979
AVAHI_GCC_UNUSED AvahiLookupResultFlags
981
AVAHI_GCC_UNUSED void* userdata){
520
static AvahiSimplePoll *simple_poll = NULL;
521
static AvahiServer *server = NULL;
523
static void resolve_callback(
524
AvahiSServiceResolver *r,
525
AvahiIfIndex interface,
526
AVAHI_GCC_UNUSED AvahiProtocol protocol,
527
AvahiResolverEvent event,
531
const char *host_name,
532
const AvahiAddress *address,
534
AVAHI_GCC_UNUSED AvahiStringList *txt,
535
AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
536
AVAHI_GCC_UNUSED void* userdata) {
538
assert(r); /* Spurious warning */
984
540
/* Called whenever a service has been resolved successfully or
993
545
case AVAHI_RESOLVER_FAILURE:
994
fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
995
" of type '%s' in domain '%s': %s\n", name, type, domain,
996
avahi_strerror(avahi_server_errno(mc.server)));
546
fprintf(stderr, "(Resolver) Failed to resolve service '%s' of"
547
" type '%s' in domain '%s': %s\n", name, type, domain,
548
avahi_strerror(avahi_server_errno(server)));
999
551
case AVAHI_RESOLVER_FOUND:
1001
553
char ip[AVAHI_ADDRESS_STR_MAX];
1002
554
avahi_address_snprint(ip, sizeof(ip), address);
1004
fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
1005
PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1006
ip, (intmax_t)interface, port);
556
fprintf(stderr, "Mandos server \"%s\" found on %s (%s) on"
557
" port %d\n", name, host_name, ip, port);
1008
int ret = start_mandos_communication(ip, port, interface,
1009
avahi_proto_to_af(proto));
1011
avahi_simple_poll_quit(mc.simple_poll);
1013
ret = add_server(ip, port, interface,
1014
avahi_proto_to_af(proto));
559
int ret = start_mandos_communication(ip, port,
560
(unsigned int) interface);
1018
566
avahi_s_service_resolver_free(r);
1021
static void browse_callback(AvahiSServiceBrowser *b,
1022
AvahiIfIndex interface,
1023
AvahiProtocol protocol,
1024
AvahiBrowserEvent event,
1028
AVAHI_GCC_UNUSED AvahiLookupResultFlags
1030
AVAHI_GCC_UNUSED void* userdata){
1033
/* Called whenever a new services becomes available on the LAN or
1034
is removed from the LAN */
1042
case AVAHI_BROWSER_FAILURE:
1044
fprintf(stderr, "(Avahi browser) %s\n",
1045
avahi_strerror(avahi_server_errno(mc.server)));
1046
avahi_simple_poll_quit(mc.simple_poll);
1049
case AVAHI_BROWSER_NEW:
1050
/* We ignore the returned Avahi resolver object. In the callback
1051
function we free it. If the Avahi server is terminated before
1052
the callback function is called the Avahi server will free the
1055
if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1056
name, type, domain, protocol, 0,
1057
resolve_callback, NULL) == NULL)
1058
fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
1059
name, avahi_strerror(avahi_server_errno(mc.server)));
1062
case AVAHI_BROWSER_REMOVE:
1065
case AVAHI_BROWSER_ALL_FOR_NOW:
1066
case AVAHI_BROWSER_CACHE_EXHAUSTED:
1068
fprintf(stderr, "No Mandos server found, still searching...\n");
1074
/* Signal handler that stops main loop after SIGTERM */
1075
static void handle_sigterm(int sig){
1080
signal_received = sig;
1081
int old_errno = errno;
1082
/* set main loop to exit */
1083
if(mc.simple_poll != NULL){
1084
avahi_simple_poll_quit(mc.simple_poll);
1089
bool get_flags(const char *ifname, struct ifreq *ifr){
1092
int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1094
perror_plus("socket");
1097
strcpy(ifr->ifr_name, ifname);
1098
ret = ioctl(s, SIOCGIFFLAGS, ifr);
1101
perror_plus("ioctl SIOCGIFFLAGS");
1108
bool good_flags(const char *ifname, const struct ifreq *ifr){
1110
/* Reject the loopback device */
1111
if(ifr->ifr_flags & IFF_LOOPBACK){
1113
fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1118
/* Accept point-to-point devices only if connect_to is specified */
1119
if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1121
fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1126
/* Otherwise, reject non-broadcast-capable devices */
1127
if(not (ifr->ifr_flags & IFF_BROADCAST)){
1129
fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1134
/* Reject non-ARP interfaces (including dummy interfaces) */
1135
if(ifr->ifr_flags & IFF_NOARP){
1137
fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
1142
/* Accept this device */
1144
fprintf(stderr, "Interface \"%s\" is good\n", ifname);
1150
* This function determines if a directory entry in /sys/class/net
1151
* corresponds to an acceptable network device.
1152
* (This function is passed to scandir(3) as a filter function.)
1154
int good_interface(const struct dirent *if_entry){
1155
if(if_entry->d_name[0] == '.'){
1160
if(not get_flags(if_entry->d_name, &ifr)){
1162
fprintf(stderr, "Failed to get flags for interface \"%s\"\n",
1168
if(not good_flags(if_entry->d_name, &ifr)){
1175
* This function determines if a directory entry in /sys/class/net
1176
* corresponds to an acceptable network device which is up.
1177
* (This function is passed to scandir(3) as a filter function.)
1179
int up_interface(const struct dirent *if_entry){
1180
if(if_entry->d_name[0] == '.'){
1185
if(not get_flags(if_entry->d_name, &ifr)){
1187
fprintf(stderr, "Failed to get flags for interface \"%s\"\n",
1193
/* Reject down interfaces */
1194
if(not (ifr.ifr_flags & IFF_UP)){
1196
fprintf(stderr, "Rejecting down interface \"%s\"\n",
1202
/* Reject non-running interfaces */
1203
if(not (ifr.ifr_flags & IFF_RUNNING)){
1205
fprintf(stderr, "Rejecting non-running interface \"%s\"\n",
1211
if(not good_flags(if_entry->d_name, &ifr)){
1217
int notdotentries(const struct dirent *direntry){
1218
/* Skip "." and ".." */
1219
if(direntry->d_name[0] == '.'
1220
and (direntry->d_name[1] == '\0'
1221
or (direntry->d_name[1] == '.'
1222
and direntry->d_name[2] == '\0'))){
1228
/* Is this directory entry a runnable program? */
1229
int runnable_hook(const struct dirent *direntry){
1233
if((direntry->d_name)[0] == '\0'){
1238
/* Save pointer to last character */
1239
char *end = strchr(direntry->d_name, '\0')-1;
1246
if(((direntry->d_name)[0] == '#')
1248
/* Temporary #name# */
1252
/* XXX more rules here */
1254
ret = stat(direntry->d_name, &st);
1257
perror_plus("Could not stat plugin");
1261
if(not (S_ISREG(st.st_mode))){
1262
/* Not a regular file */
1265
if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1266
/* Not executable */
1272
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1274
struct timespec now;
1275
struct timespec waited_time;
1276
intmax_t block_time;
1279
if(mc.current_server == NULL){
1282
"Wait until first server is found. No timeout!\n");
1284
ret = avahi_simple_poll_iterate(s, -1);
1287
fprintf(stderr, "Check current_server if we should run it,"
1290
/* the current time */
1291
ret = clock_gettime(CLOCK_MONOTONIC, &now);
1293
perror_plus("clock_gettime");
1296
/* Calculating in ms how long time between now and server
1297
who we visted longest time ago. Now - last seen. */
1298
waited_time.tv_sec = (now.tv_sec
1299
- mc.current_server->last_seen.tv_sec);
1300
waited_time.tv_nsec = (now.tv_nsec
1301
- mc.current_server->last_seen.tv_nsec);
1302
/* total time is 10s/10,000ms.
1303
Converting to s from ms by dividing by 1,000,
1304
and ns to ms by dividing by 1,000,000. */
1305
block_time = ((retry_interval
1306
- ((intmax_t)waited_time.tv_sec * 1000))
1307
- ((intmax_t)waited_time.tv_nsec / 1000000));
1310
fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
1313
if(block_time <= 0){
1314
ret = start_mandos_communication(mc.current_server->ip,
1315
mc.current_server->port,
1316
mc.current_server->if_index,
1317
mc.current_server->af);
1319
avahi_simple_poll_quit(mc.simple_poll);
1322
ret = clock_gettime(CLOCK_MONOTONIC,
1323
&mc.current_server->last_seen);
1325
perror_plus("clock_gettime");
1328
mc.current_server = mc.current_server->next;
1329
block_time = 0; /* Call avahi to find new Mandos
1330
servers, but don't block */
1333
ret = avahi_simple_poll_iterate(s, (int)block_time);
1336
if (ret > 0 or errno != EINTR) {
1337
return (ret != 1) ? ret : 0;
1343
int main(int argc, char *argv[]){
1344
AvahiSServiceBrowser *sb = NULL;
1349
int exitcode = EXIT_SUCCESS;
1350
const char *interface = "";
1351
struct ifreq network;
1353
bool take_down_interface = false;
1356
char tempdir[] = "/tmp/mandosXXXXXX";
1357
bool tempdir_created = false;
1358
AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1359
const char *seckey = PATHDIR "/" SECKEY;
1360
const char *pubkey = PATHDIR "/" PUBKEY;
1362
bool gnutls_initialized = false;
1363
bool gpgme_initialized = false;
1365
double retry_interval = 10; /* 10s between trying a server and
1366
retrying the same server again */
1368
struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1369
struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1374
/* Lower any group privileges we might have, just to be safe */
1378
perror_plus("setgid");
1381
/* Lower user privileges (temporarily) */
1385
perror_plus("seteuid");
1393
struct argp_option options[] = {
1394
{ .name = "debug", .key = 128,
1395
.doc = "Debug mode", .group = 3 },
1396
{ .name = "connect", .key = 'c',
1397
.arg = "ADDRESS:PORT",
1398
.doc = "Connect directly to a specific Mandos server",
1400
{ .name = "interface", .key = 'i',
1402
.doc = "Network interface that will be used to search for"
1405
{ .name = "seckey", .key = 's',
1407
.doc = "OpenPGP secret key file base name",
1409
{ .name = "pubkey", .key = 'p',
1411
.doc = "OpenPGP public key file base name",
1413
{ .name = "dh-bits", .key = 129,
1415
.doc = "Bit length of the prime number used in the"
1416
" Diffie-Hellman key exchange",
1418
{ .name = "priority", .key = 130,
1420
.doc = "GnuTLS priority string for the TLS handshake",
1422
{ .name = "delay", .key = 131,
1424
.doc = "Maximum delay to wait for interface startup",
1426
{ .name = "retry", .key = 132,
1428
.doc = "Retry interval used when denied by the mandos server",
1431
* These reproduce what we would get without ARGP_NO_HELP
1433
{ .name = "help", .key = '?',
1434
.doc = "Give this help list", .group = -1 },
1435
{ .name = "usage", .key = -3,
1436
.doc = "Give a short usage message", .group = -1 },
1437
{ .name = "version", .key = 'V',
1438
.doc = "Print program version", .group = -1 },
1442
error_t parse_opt(int key, char *arg,
1443
struct argp_state *state){
1446
case 128: /* --debug */
1449
case 'c': /* --connect */
1452
case 'i': /* --interface */
1455
case 's': /* --seckey */
1458
case 'p': /* --pubkey */
1461
case 129: /* --dh-bits */
1463
tmpmax = strtoimax(arg, &tmp, 10);
1464
if(errno != 0 or tmp == arg or *tmp != '\0'
1465
or tmpmax != (typeof(mc.dh_bits))tmpmax){
1466
argp_error(state, "Bad number of DH bits");
1468
mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1470
case 130: /* --priority */
1473
case 131: /* --delay */
1475
delay = strtof(arg, &tmp);
1476
if(errno != 0 or tmp == arg or *tmp != '\0'){
1477
argp_error(state, "Bad delay");
1479
case 132: /* --retry */
1481
retry_interval = strtod(arg, &tmp);
1482
if(errno != 0 or tmp == arg or *tmp != '\0'
1483
or (retry_interval * 1000) > INT_MAX
1484
or retry_interval < 0){
1485
argp_error(state, "Bad retry interval");
1489
* These reproduce what we would get without ARGP_NO_HELP
1491
case '?': /* --help */
1492
argp_state_help(state, state->out_stream,
1493
(ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
1494
& ~(unsigned int)ARGP_HELP_EXIT_OK);
1495
case -3: /* --usage */
1496
argp_state_help(state, state->out_stream,
1497
ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1498
case 'V': /* --version */
1499
fprintf(state->out_stream, "%s\n", argp_program_version);
1500
exit(argp_err_exit_status);
1503
return ARGP_ERR_UNKNOWN;
1508
struct argp argp = { .options = options, .parser = parse_opt,
1510
.doc = "Mandos client -- Get and decrypt"
1511
" passwords from a Mandos server" };
1512
ret = argp_parse(&argp, argc, argv,
1513
ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
569
static void browse_callback(
570
AvahiSServiceBrowser *b,
571
AvahiIfIndex interface,
572
AvahiProtocol protocol,
573
AvahiBrowserEvent event,
577
AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
580
AvahiServer *s = userdata;
581
assert(b); /* Spurious warning */
583
/* Called whenever a new services becomes available on the LAN or
584
is removed from the LAN */
1520
perror_plus("argp_parse");
1521
exitcode = EX_OSERR;
1524
exitcode = EX_USAGE;
1530
/* Work around Debian bug #633582:
1531
<http://bugs.debian.org/633582> */
1534
/* Re-raise priviliges */
1538
perror_plus("seteuid");
1541
if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1542
int seckey_fd = open(seckey, O_RDONLY);
1543
if(seckey_fd == -1){
1544
perror_plus("open");
1546
ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1548
perror_plus("fstat");
1550
if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1551
ret = fchown(seckey_fd, uid, gid);
1553
perror_plus("fchown");
1557
TEMP_FAILURE_RETRY(close(seckey_fd));
1561
if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1562
int pubkey_fd = open(pubkey, O_RDONLY);
1563
if(pubkey_fd == -1){
1564
perror_plus("open");
1566
ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1568
perror_plus("fstat");
1570
if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1571
ret = fchown(pubkey_fd, uid, gid);
1573
perror_plus("fchown");
1577
TEMP_FAILURE_RETRY(close(pubkey_fd));
1581
/* Lower privileges */
1585
perror_plus("seteuid");
1589
/* Find network hooks and run them */
1591
struct dirent **direntries;
1592
struct dirent *direntry;
1593
int numhooks = scandir(HOOKDIR, &direntries, runnable_hook,
1595
int devnull = open("/dev/null", O_RDONLY);
1596
for(int i = 0; i < numhooks; i++){
1597
direntry = direntries[0];
1598
char *fullname = NULL;
1599
ret = asprintf(&fullname, "%s/%s", tempdir,
1602
perror_plus("asprintf");
1605
pid_t hook_pid = fork();
1608
dup2(devnull, STDIN_FILENO);
1610
dup2(STDERR_FILENO, STDOUT_FILENO);
1611
ret = setenv("DEVICE", interface, 1);
1613
perror_plus("setenv");
1616
ret = setenv("VERBOSE", debug ? "1" : "0", 1);
1618
perror_plus("setenv");
1621
ret = setenv("MODE", "start", 1);
1623
perror_plus("setenv");
1627
ret = asprintf(&delaystring, "%f", delay);
1629
perror_plus("asprintf");
1632
ret = setenv("DELAY", delaystring, 1);
1635
perror_plus("setenv");
1639
ret = execl(fullname, direntry->d_name, "start", NULL);
1640
perror_plus("execl");
1651
avahi_set_log_function(empty_log);
1654
if(interface[0] == '\0'){
1655
struct dirent **direntries;
1656
/* First look for interfaces that are up */
1657
ret = scandir(sys_class_net, &direntries, up_interface,
1660
/* No up interfaces, look for any good interfaces */
1662
ret = scandir(sys_class_net, &direntries, good_interface,
1666
/* Pick the first interface returned */
1667
interface = strdup(direntries[0]->d_name);
1669
fprintf(stderr, "Using interface \"%s\"\n", interface);
1671
if(interface == NULL){
1672
perror_plus("malloc");
1674
exitcode = EXIT_FAILURE;
1680
fprintf(stderr, "Could not find a network interface\n");
1681
exitcode = EXIT_FAILURE;
1686
/* Initialize Avahi early so avahi_simple_poll_quit() can be called
1687
from the signal handler */
1688
/* Initialize the pseudo-RNG for Avahi */
1689
srand((unsigned int) time(NULL));
1690
mc.simple_poll = avahi_simple_poll_new();
1691
if(mc.simple_poll == NULL){
1692
fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1693
exitcode = EX_UNAVAILABLE;
1697
sigemptyset(&sigterm_action.sa_mask);
1698
ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1700
perror_plus("sigaddset");
1701
exitcode = EX_OSERR;
1704
ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1706
perror_plus("sigaddset");
1707
exitcode = EX_OSERR;
1710
ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1712
perror_plus("sigaddset");
1713
exitcode = EX_OSERR;
1716
/* Need to check if the handler is SIG_IGN before handling:
1717
| [[info:libc:Initial Signal Actions]] |
1718
| [[info:libc:Basic Signal Handling]] |
1720
ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1722
perror_plus("sigaction");
1725
if(old_sigterm_action.sa_handler != SIG_IGN){
1726
ret = sigaction(SIGINT, &sigterm_action, NULL);
1728
perror_plus("sigaction");
1729
exitcode = EX_OSERR;
1733
ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1735
perror_plus("sigaction");
1738
if(old_sigterm_action.sa_handler != SIG_IGN){
1739
ret = sigaction(SIGHUP, &sigterm_action, NULL);
1741
perror_plus("sigaction");
1742
exitcode = EX_OSERR;
1746
ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1748
perror_plus("sigaction");
1751
if(old_sigterm_action.sa_handler != SIG_IGN){
1752
ret = sigaction(SIGTERM, &sigterm_action, NULL);
1754
perror_plus("sigaction");
1755
exitcode = EX_OSERR;
1760
/* If the interface is down, bring it up */
1761
if(strcmp(interface, "none") != 0){
1762
if_index = (AvahiIfIndex) if_nametoindex(interface);
1764
fprintf(stderr, "No such interface: \"%s\"\n", interface);
1765
exitcode = EX_UNAVAILABLE;
1773
/* Re-raise priviliges */
1777
perror_plus("seteuid");
1781
/* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1782
messages about the network interface to mess up the prompt */
1783
ret = klogctl(8, NULL, 5);
1784
bool restore_loglevel = true;
1786
restore_loglevel = false;
1787
perror_plus("klogctl");
1789
#endif /* __linux__ */
1791
sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1793
perror_plus("socket");
1794
exitcode = EX_OSERR;
1796
if(restore_loglevel){
1797
ret = klogctl(7, NULL, 0);
1799
perror_plus("klogctl");
1802
#endif /* __linux__ */
1803
/* Lower privileges */
1807
perror_plus("seteuid");
1811
strcpy(network.ifr_name, interface);
1812
ret = ioctl(sd, SIOCGIFFLAGS, &network);
1814
perror_plus("ioctl SIOCGIFFLAGS");
1816
if(restore_loglevel){
1817
ret = klogctl(7, NULL, 0);
1819
perror_plus("klogctl");
1822
#endif /* __linux__ */
1823
exitcode = EX_OSERR;
1824
/* Lower privileges */
1828
perror_plus("seteuid");
1832
if((network.ifr_flags & IFF_UP) == 0){
1833
network.ifr_flags |= IFF_UP;
1834
take_down_interface = true;
1835
ret = ioctl(sd, SIOCSIFFLAGS, &network);
1837
take_down_interface = false;
1838
perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1839
exitcode = EX_OSERR;
1841
if(restore_loglevel){
1842
ret = klogctl(7, NULL, 0);
1844
perror_plus("klogctl");
1847
#endif /* __linux__ */
1848
/* Lower privileges */
1852
perror_plus("seteuid");
1857
/* Sleep checking until interface is running.
1858
Check every 0.25s, up to total time of delay */
1859
for(int i=0; i < delay * 4; i++){
1860
ret = ioctl(sd, SIOCGIFFLAGS, &network);
1862
perror_plus("ioctl SIOCGIFFLAGS");
1863
} else if(network.ifr_flags & IFF_RUNNING){
1866
struct timespec sleeptime = { .tv_nsec = 250000000 };
1867
ret = nanosleep(&sleeptime, NULL);
1868
if(ret == -1 and errno != EINTR){
1869
perror_plus("nanosleep");
1872
if(not take_down_interface){
1873
/* We won't need the socket anymore */
1874
ret = (int)TEMP_FAILURE_RETRY(close(sd));
1876
perror_plus("close");
1880
if(restore_loglevel){
1881
/* Restores kernel loglevel to default */
1882
ret = klogctl(7, NULL, 0);
1884
perror_plus("klogctl");
1887
#endif /* __linux__ */
1888
/* Lower privileges */
1890
if(take_down_interface){
1891
/* Lower privileges */
1894
perror_plus("seteuid");
1897
/* Lower privileges permanently */
1900
perror_plus("setuid");
1909
ret = init_gnutls_global(pubkey, seckey);
1911
fprintf(stderr, "init_gnutls_global failed\n");
1912
exitcode = EX_UNAVAILABLE;
1915
gnutls_initialized = true;
1922
if(mkdtemp(tempdir) == NULL){
1923
perror_plus("mkdtemp");
1926
tempdir_created = true;
1932
if(not init_gpgme(pubkey, seckey, tempdir)){
1933
fprintf(stderr, "init_gpgme failed\n");
1934
exitcode = EX_UNAVAILABLE;
1937
gpgme_initialized = true;
1944
if(connect_to != NULL){
1945
/* Connect directly, do not use Zeroconf */
1946
/* (Mainly meant for debugging) */
1947
char *address = strrchr(connect_to, ':');
1948
if(address == NULL){
1949
fprintf(stderr, "No colon in address\n");
1950
exitcode = EX_USAGE;
1960
tmpmax = strtoimax(address+1, &tmp, 10);
1961
if(errno != 0 or tmp == address+1 or *tmp != '\0'
1962
or tmpmax != (uint16_t)tmpmax){
1963
fprintf(stderr, "Bad port number\n");
1964
exitcode = EX_USAGE;
1972
port = (uint16_t)tmpmax;
1974
/* Colon in address indicates IPv6 */
1976
if(strchr(connect_to, ':') != NULL){
1978
/* Accept [] around IPv6 address - see RFC 5952 */
1979
if(connect_to[0] == '[' and address[-1] == ']')
1987
address = connect_to;
1993
while(not quit_now){
1994
ret = start_mandos_communication(address, port, if_index, af);
1995
if(quit_now or ret == 0){
1999
fprintf(stderr, "Retrying in %d seconds\n",
2000
(int)retry_interval);
2002
sleep((int)retry_interval);
2006
exitcode = EXIT_SUCCESS;
588
case AVAHI_BROWSER_FAILURE:
590
fprintf(stderr, "(Browser) %s\n",
591
avahi_strerror(avahi_server_errno(server)));
592
avahi_simple_poll_quit(simple_poll);
595
case AVAHI_BROWSER_NEW:
596
/* We ignore the returned resolver object. In the callback
597
function we free it. If the server is terminated before
598
the callback function is called the server will free
599
the resolver for us. */
601
if (!(avahi_s_service_resolver_new(s, interface, protocol, name,
603
AVAHI_PROTO_INET6, 0,
604
resolve_callback, s)))
605
fprintf(stderr, "Failed to resolve service '%s': %s\n", name,
606
avahi_strerror(avahi_server_errno(s)));
609
case AVAHI_BROWSER_REMOVE:
612
case AVAHI_BROWSER_ALL_FOR_NOW:
613
case AVAHI_BROWSER_CACHE_EXHAUSTED:
618
int main(AVAHI_GCC_UNUSED int argc, AVAHI_GCC_UNUSED char*argv[]) {
2017
619
AvahiServerConfig config;
2018
/* Do not publish any local Zeroconf records */
620
AvahiSServiceBrowser *sb = NULL;
623
int returncode = EXIT_SUCCESS;
624
const char *interface = "eth0";
627
static struct option long_options[] = {
628
{"debug", no_argument, (int *)&debug, 1},
629
{"interface", required_argument, 0, 'i'},
632
int option_index = 0;
633
ret = getopt_long (argc, argv, "i:", long_options,
652
avahi_set_log_function(empty_log);
655
/* Initialize the psuedo-RNG */
656
srand((unsigned int) time(NULL));
658
/* Allocate main loop object */
659
if (!(simple_poll = avahi_simple_poll_new())) {
660
fprintf(stderr, "Failed to create simple poll object.\n");
665
/* Do not publish any local records */
2019
666
avahi_server_config_init(&config);
2020
667
config.publish_hinfo = 0;
2021
668
config.publish_addresses = 0;
2022
669
config.publish_workstation = 0;
2023
670
config.publish_domain = 0;
2025
672
/* Allocate a new server */
2026
mc.server = avahi_server_new(avahi_simple_poll_get
2027
(mc.simple_poll), &config, NULL,
2030
/* Free the Avahi configuration data */
673
server = avahi_server_new(avahi_simple_poll_get(simple_poll),
674
&config, NULL, NULL, &error);
676
/* Free the configuration data */
2031
677
avahi_server_config_free(&config);
2034
/* Check if creating the Avahi server object succeeded */
2035
if(mc.server == NULL){
2036
fprintf(stderr, "Failed to create Avahi server: %s\n",
2037
avahi_strerror(error));
2038
exitcode = EX_UNAVAILABLE;
2046
/* Create the Avahi service browser */
2047
sb = avahi_s_service_browser_new(mc.server, if_index,
2048
AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2049
NULL, 0, browse_callback, NULL);
2051
fprintf(stderr, "Failed to create service browser: %s\n",
2052
avahi_strerror(avahi_server_errno(mc.server)));
2053
exitcode = EX_UNAVAILABLE;
2061
/* Run the main loop */
2064
fprintf(stderr, "Starting Avahi loop search\n");
2067
ret = avahi_loop_with_timeout(mc.simple_poll,
2068
(int)(retry_interval * 1000));
2070
fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
2071
(ret == 0) ? "successfully" : "with error");
2077
fprintf(stderr, "%s exiting\n", argv[0]);
2080
/* Cleanup things */
2082
avahi_s_service_browser_free(sb);
2084
if(mc.server != NULL)
2085
avahi_server_free(mc.server);
2087
if(mc.simple_poll != NULL)
2088
avahi_simple_poll_free(mc.simple_poll);
2090
if(gnutls_initialized){
2091
gnutls_certificate_free_credentials(mc.cred);
2092
gnutls_global_deinit();
2093
gnutls_dh_params_deinit(mc.dh_params);
2096
if(gpgme_initialized){
2097
gpgme_release(mc.ctx);
2100
/* Cleans up the circular linked list of Mandos servers the client
2102
if(mc.current_server != NULL){
2103
mc.current_server->prev->next = NULL;
2104
while(mc.current_server != NULL){
2105
server *next = mc.current_server->next;
2106
free(mc.current_server);
2107
mc.current_server = next;
2111
/* XXX run network hooks "stop" here */
2113
/* Take down the network interface */
2114
if(take_down_interface){
2115
/* Re-raise priviliges */
2119
perror_plus("seteuid");
2122
ret = ioctl(sd, SIOCGIFFLAGS, &network);
2124
perror_plus("ioctl SIOCGIFFLAGS");
2125
} else if(network.ifr_flags & IFF_UP) {
2126
network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2127
ret = ioctl(sd, SIOCSIFFLAGS, &network);
2129
perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
2132
ret = (int)TEMP_FAILURE_RETRY(close(sd));
2134
perror_plus("close");
2136
/* Lower privileges permanently */
2140
perror_plus("setuid");
2145
/* Removes the GPGME temp directory and all files inside */
2146
if(tempdir_created){
2147
struct dirent **direntries = NULL;
2148
struct dirent *direntry = NULL;
2149
int numentries = scandir(tempdir, &direntries, notdotentries,
2151
if (numentries > 0){
2152
for(int i = 0; i < numentries; i++){
2153
direntry = direntries[i];
2154
char *fullname = NULL;
2155
ret = asprintf(&fullname, "%s/%s", tempdir,
2158
perror_plus("asprintf");
2161
ret = remove(fullname);
2163
fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
2170
/* need to clean even if 0 because man page doesn't specify */
2172
if (numentries == -1){
2173
perror_plus("scandir");
2175
ret = rmdir(tempdir);
2176
if(ret == -1 and errno != ENOENT){
2177
perror_plus("rmdir");
2182
sigemptyset(&old_sigterm_action.sa_mask);
2183
old_sigterm_action.sa_handler = SIG_DFL;
2184
ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
2185
&old_sigterm_action,
2188
perror_plus("sigaction");
2191
ret = raise(signal_received);
2192
} while(ret != 0 and errno == EINTR);
2194
perror_plus("raise");
2197
TEMP_FAILURE_RETRY(pause());
679
/* Check if creating the server object succeeded */
681
fprintf(stderr, "Failed to create server: %s\n",
682
avahi_strerror(error));
683
returncode = EXIT_FAILURE;
687
/* Create the service browser */
688
sb = avahi_s_service_browser_new(server,
690
if_nametoindex(interface),
692
"_mandos._tcp", NULL, 0,
693
browse_callback, server);
695
fprintf(stderr, "Failed to create service browser: %s\n",
696
avahi_strerror(avahi_server_errno(server)));
697
returncode = EXIT_FAILURE;
701
/* Run the main loop */
704
fprintf(stderr, "Starting avahi loop search\n");
707
avahi_simple_poll_loop(simple_poll);
712
fprintf(stderr, "%s exiting\n", argv[0]);
717
avahi_s_service_browser_free(sb);
720
avahi_server_free(server);
723
avahi_simple_poll_free(simple_poll);