/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk

« back to all changes in this revision

Viewing changes to plugins.d/mandos-client.c

  • Committer: Teddy Hogeborn
  • Date: 2009-04-17 08:26:17 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090417082617-eltetak5lzjyz55o
* initramfs-tools-hook: Bug fix: Add "--userid" and "--groupid" to
                        start of "plugin-runner.conf" file instead of
                        appending, to allow any preexisting options to
                        override.
* plugin-runner.conf: Improved wording.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2012 Teddy Hogeborn
13
 
 * Copyright © 2008-2012 Björn Påhlsson
 
12
 * Copyright © 2008,2009 Teddy Hogeborn
 
13
 * Copyright © 2008,2009 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@recompile.se>.
 
29
 * Contact the authors at <mandos@fukt.bsnet.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
43
                                   stdout, ferror(), remove() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
 
44
#include <stdint.h>             /* uint16_t, uint32_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
 
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
 
                                   strtof(), abort() */
 
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
 
47
                                   srand(), strtof() */
48
48
#include <stdbool.h>            /* bool, false, true */
49
49
#include <string.h>             /* memset(), strcmp(), strlen(),
50
50
                                   strerror(), asprintf(), strcpy() */
53
53
                                   sockaddr_in6, PF_INET6,
54
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
55
                                   opendir(), DIR */
56
 
#include <sys/stat.h>           /* open(), S_ISREG */
 
56
#include <sys/stat.h>           /* open() */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect() */
59
59
#include <fcntl.h>              /* open() */
62
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
63
                                   strtoimax() */
64
64
#include <assert.h>             /* assert() */
65
 
#include <errno.h>              /* perror(), errno,
66
 
                                   program_invocation_short_name */
67
 
#include <time.h>               /* nanosleep(), time(), sleep() */
 
65
#include <errno.h>              /* perror(), errno */
 
66
#include <time.h>               /* nanosleep(), time() */
68
67
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
69
68
                                   SIOCSIFFLAGS, if_indextoname(),
70
69
                                   if_nametoindex(), IF_NAMESIZE */
72
71
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
73
72
                                */
74
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
 
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause(), _exit() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
74
                                   getuid(), getgid(), setuid(),
 
75
                                   setgid() */
 
76
#include <arpa/inet.h>          /* inet_pton(), htons */
78
77
#include <iso646.h>             /* not, or, and */
79
78
#include <argp.h>               /* struct argp_option, error_t, struct
80
79
                                   argp_state, struct argp,
81
80
                                   argp_parse(), ARGP_KEY_ARG,
82
81
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
83
82
#include <signal.h>             /* sigemptyset(), sigaddset(),
84
 
                                   sigaction(), SIGTERM, sig_atomic_t,
85
 
                                   raise() */
86
 
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
 
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
 
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
 
                                   WEXITSTATUS(), WTERMSIG() */
90
 
#include <grp.h>                /* setgroups() */
 
83
                                   sigaction(), SIGTERM, sigaction,
 
84
                                   sig_atomic_t */
91
85
 
92
86
#ifdef __linux__
93
87
#include <sys/klog.h>           /* klogctl() */
111
105
                                   init_gnutls_session(),
112
106
                                   GNUTLS_* */
113
107
#include <gnutls/openpgp.h>
114
 
                         /* gnutls_certificate_set_openpgp_key_file(),
115
 
                            GNUTLS_OPENPGP_FMT_BASE64 */
 
108
                          /* gnutls_certificate_set_openpgp_key_file(),
 
109
                                   GNUTLS_OPENPGP_FMT_BASE64 */
116
110
 
117
111
/* GPGME */
118
112
#include <gpgme.h>              /* All GPGME types, constants and
126
120
#define PATHDIR "/conf/conf.d/mandos"
127
121
#define SECKEY "seckey.txt"
128
122
#define PUBKEY "pubkey.txt"
129
 
#define HOOKDIR "/lib/mandos/network-hooks.d"
130
123
 
131
124
bool debug = false;
132
125
static const char mandos_protocol_version[] = "1";
133
126
const char *argp_program_version = "mandos-client " VERSION;
134
 
const char *argp_program_bug_address = "<mandos@recompile.se>";
135
 
static const char sys_class_net[] = "/sys/class/net";
136
 
char *connect_to = NULL;
137
 
const char *hookdir = HOOKDIR;
138
 
uid_t uid = 65534;
139
 
gid_t gid = 65534;
140
 
 
141
 
/* Doubly linked list that need to be circularly linked when used */
142
 
typedef struct server{
143
 
  const char *ip;
144
 
  uint16_t port;
145
 
  AvahiIfIndex if_index;
146
 
  int af;
147
 
  struct timespec last_seen;
148
 
  struct server *next;
149
 
  struct server *prev;
150
 
} server;
 
127
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
151
128
 
152
129
/* Used for passing in values through the Avahi callback functions */
153
130
typedef struct {
158
135
  gnutls_dh_params_t dh_params;
159
136
  const char *priority;
160
137
  gpgme_ctx_t ctx;
161
 
  server *current_server;
162
138
} mandos_context;
163
139
 
164
140
/* global context so signal handler can reach it*/
165
141
mandos_context mc = { .simple_poll = NULL, .server = NULL,
166
142
                      .dh_bits = 1024, .priority = "SECURE256"
167
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
168
 
                      .current_server = NULL };
169
 
 
170
 
sig_atomic_t quit_now = 0;
171
 
int signal_received = 0;
172
 
 
173
 
/* Function to use when printing errors */
174
 
void perror_plus(const char *print_text){
175
 
  int e = errno;
176
 
  fprintf(stderr, "Mandos plugin %s: ",
177
 
          program_invocation_short_name);
178
 
  errno = e;
179
 
  perror(print_text);
180
 
}
181
 
 
182
 
__attribute__((format (gnu_printf, 2, 3)))
183
 
int fprintf_plus(FILE *stream, const char *format, ...){
184
 
  va_list ap;
185
 
  va_start (ap, format);
186
 
  
187
 
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
188
 
                             program_invocation_short_name));
189
 
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
190
 
}
 
143
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
191
144
 
192
145
/*
193
146
 * Make additional room in "buffer" for at least BUFFER_SIZE more
195
148
 * "buffer_length" is how much is already used.
196
149
 */
197
150
size_t incbuffer(char **buffer, size_t buffer_length,
198
 
                 size_t buffer_capacity){
 
151
                  size_t buffer_capacity){
199
152
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
200
153
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
201
154
    if(buffer == NULL){
206
159
  return buffer_capacity;
207
160
}
208
161
 
209
 
/* Add server to set of servers to retry periodically */
210
 
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
211
 
                int af){
212
 
  int ret;
213
 
  server *new_server = malloc(sizeof(server));
214
 
  if(new_server == NULL){
215
 
    perror_plus("malloc");
216
 
    return false;
217
 
  }
218
 
  *new_server = (server){ .ip = strdup(ip),
219
 
                          .port = port,
220
 
                          .if_index = if_index,
221
 
                          .af = af };
222
 
  if(new_server->ip == NULL){
223
 
    perror_plus("strdup");
224
 
    return false;
225
 
  }
226
 
  /* Special case of first server */
227
 
  if (mc.current_server == NULL){
228
 
    new_server->next = new_server;
229
 
    new_server->prev = new_server;
230
 
    mc.current_server = new_server;
231
 
  /* Place the new server last in the list */
232
 
  } else {
233
 
    new_server->next = mc.current_server;
234
 
    new_server->prev = mc.current_server->prev;
235
 
    new_server->prev->next = new_server;
236
 
    mc.current_server->prev = new_server;
237
 
  }
238
 
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
239
 
  if(ret == -1){
240
 
    perror_plus("clock_gettime");
241
 
    return false;
242
 
  }
243
 
  return true;
244
 
}
245
 
 
246
162
/* 
247
163
 * Initialize GPGME.
248
164
 */
249
 
static bool init_gpgme(const char *seckey, const char *pubkey,
250
 
                       const char *tempdir){
 
165
static bool init_gpgme(const char *seckey,
 
166
                       const char *pubkey, const char *tempdir){
 
167
  int ret;
251
168
  gpgme_error_t rc;
252
169
  gpgme_engine_info_t engine_info;
253
170
  
256
173
   * Helper function to insert pub and seckey to the engine keyring.
257
174
   */
258
175
  bool import_key(const char *filename){
259
 
    int ret;
260
176
    int fd;
261
177
    gpgme_data_t pgp_data;
262
178
    
263
179
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
264
180
    if(fd == -1){
265
 
      perror_plus("open");
 
181
      perror("open");
266
182
      return false;
267
183
    }
268
184
    
269
185
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
270
186
    if(rc != GPG_ERR_NO_ERROR){
271
 
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
272
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
187
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
188
              gpgme_strsource(rc), gpgme_strerror(rc));
273
189
      return false;
274
190
    }
275
191
    
276
192
    rc = gpgme_op_import(mc.ctx, pgp_data);
277
193
    if(rc != GPG_ERR_NO_ERROR){
278
 
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
279
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
194
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
195
              gpgme_strsource(rc), gpgme_strerror(rc));
280
196
      return false;
281
197
    }
282
198
    
283
199
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
284
200
    if(ret == -1){
285
 
      perror_plus("close");
 
201
      perror("close");
286
202
    }
287
203
    gpgme_data_release(pgp_data);
288
204
    return true;
289
205
  }
290
206
  
291
207
  if(debug){
292
 
    fprintf_plus(stderr, "Initializing GPGME\n");
 
208
    fprintf(stderr, "Initializing GPGME\n");
293
209
  }
294
210
  
295
211
  /* Init GPGME */
296
212
  gpgme_check_version(NULL);
297
213
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
298
214
  if(rc != GPG_ERR_NO_ERROR){
299
 
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
300
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
215
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
216
            gpgme_strsource(rc), gpgme_strerror(rc));
301
217
    return false;
302
218
  }
303
219
  
304
 
  /* Set GPGME home directory for the OpenPGP engine only */
 
220
    /* Set GPGME home directory for the OpenPGP engine only */
305
221
  rc = gpgme_get_engine_info(&engine_info);
306
222
  if(rc != GPG_ERR_NO_ERROR){
307
 
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
308
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
223
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
224
            gpgme_strsource(rc), gpgme_strerror(rc));
309
225
    return false;
310
226
  }
311
227
  while(engine_info != NULL){
317
233
    engine_info = engine_info->next;
318
234
  }
319
235
  if(engine_info == NULL){
320
 
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
321
 
                 tempdir);
 
236
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
322
237
    return false;
323
238
  }
324
239
  
325
240
  /* Create new GPGME "context" */
326
241
  rc = gpgme_new(&(mc.ctx));
327
242
  if(rc != GPG_ERR_NO_ERROR){
328
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
329
 
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
330
 
                 gpgme_strerror(rc));
 
243
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
244
            gpgme_strsource(rc), gpgme_strerror(rc));
331
245
    return false;
332
246
  }
333
247
  
335
249
    return false;
336
250
  }
337
251
  
338
 
  return true;
 
252
  return true; 
339
253
}
340
254
 
341
255
/* 
352
266
  ssize_t plaintext_length = 0;
353
267
  
354
268
  if(debug){
355
 
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
 
269
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
356
270
  }
357
271
  
358
272
  /* Create new GPGME data buffer from memory cryptotext */
359
273
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
360
274
                               0);
361
275
  if(rc != GPG_ERR_NO_ERROR){
362
 
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
363
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
276
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
277
            gpgme_strsource(rc), gpgme_strerror(rc));
364
278
    return -1;
365
279
  }
366
280
  
367
281
  /* Create new empty GPGME data buffer for the plaintext */
368
282
  rc = gpgme_data_new(&dh_plain);
369
283
  if(rc != GPG_ERR_NO_ERROR){
370
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
371
 
                 "bad gpgme_data_new: %s: %s\n",
372
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
284
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
285
            gpgme_strsource(rc), gpgme_strerror(rc));
373
286
    gpgme_data_release(dh_crypto);
374
287
    return -1;
375
288
  }
378
291
     data buffer */
379
292
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
380
293
  if(rc != GPG_ERR_NO_ERROR){
381
 
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
382
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
294
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
295
            gpgme_strsource(rc), gpgme_strerror(rc));
383
296
    plaintext_length = -1;
384
297
    if(debug){
385
298
      gpgme_decrypt_result_t result;
386
299
      result = gpgme_op_decrypt_result(mc.ctx);
387
300
      if(result == NULL){
388
 
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
 
301
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
389
302
      } else {
390
 
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
391
 
                     result->unsupported_algorithm);
392
 
        fprintf_plus(stderr, "Wrong key usage: %u\n",
393
 
                     result->wrong_key_usage);
 
303
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
304
                result->unsupported_algorithm);
 
305
        fprintf(stderr, "Wrong key usage: %u\n",
 
306
                result->wrong_key_usage);
394
307
        if(result->file_name != NULL){
395
 
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
 
308
          fprintf(stderr, "File name: %s\n", result->file_name);
396
309
        }
397
310
        gpgme_recipient_t recipient;
398
311
        recipient = result->recipients;
399
 
        while(recipient != NULL){
400
 
          fprintf_plus(stderr, "Public key algorithm: %s\n",
401
 
                       gpgme_pubkey_algo_name
402
 
                       (recipient->pubkey_algo));
403
 
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
404
 
          fprintf_plus(stderr, "Secret key available: %s\n",
405
 
                       recipient->status == GPG_ERR_NO_SECKEY
406
 
                       ? "No" : "Yes");
407
 
          recipient = recipient->next;
 
312
        if(recipient){
 
313
          while(recipient != NULL){
 
314
            fprintf(stderr, "Public key algorithm: %s\n",
 
315
                    gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
316
            fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
317
            fprintf(stderr, "Secret key available: %s\n",
 
318
                    recipient->status == GPG_ERR_NO_SECKEY
 
319
                    ? "No" : "Yes");
 
320
            recipient = recipient->next;
 
321
          }
408
322
        }
409
323
      }
410
324
    }
412
326
  }
413
327
  
414
328
  if(debug){
415
 
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
 
329
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
416
330
  }
417
331
  
418
332
  /* Seek back to the beginning of the GPGME plaintext data buffer */
419
333
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
420
 
    perror_plus("gpgme_data_seek");
 
334
    perror("gpgme_data_seek");
421
335
    plaintext_length = -1;
422
336
    goto decrypt_end;
423
337
  }
425
339
  *plaintext = NULL;
426
340
  while(true){
427
341
    plaintext_capacity = incbuffer(plaintext,
428
 
                                   (size_t)plaintext_length,
429
 
                                   plaintext_capacity);
 
342
                                      (size_t)plaintext_length,
 
343
                                      plaintext_capacity);
430
344
    if(plaintext_capacity == 0){
431
 
      perror_plus("incbuffer");
432
 
      plaintext_length = -1;
433
 
      goto decrypt_end;
 
345
        perror("incbuffer");
 
346
        plaintext_length = -1;
 
347
        goto decrypt_end;
434
348
    }
435
349
    
436
350
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
441
355
      break;
442
356
    }
443
357
    if(ret < 0){
444
 
      perror_plus("gpgme_data_read");
 
358
      perror("gpgme_data_read");
445
359
      plaintext_length = -1;
446
360
      goto decrypt_end;
447
361
    }
449
363
  }
450
364
  
451
365
  if(debug){
452
 
    fprintf_plus(stderr, "Decrypted password is: ");
 
366
    fprintf(stderr, "Decrypted password is: ");
453
367
    for(ssize_t i = 0; i < plaintext_length; i++){
454
368
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
455
369
    }
477
391
/* GnuTLS log function callback */
478
392
static void debuggnutls(__attribute__((unused)) int level,
479
393
                        const char* string){
480
 
  fprintf_plus(stderr, "GnuTLS: %s", string);
 
394
  fprintf(stderr, "GnuTLS: %s", string);
481
395
}
482
396
 
483
397
static int init_gnutls_global(const char *pubkeyfilename,
485
399
  int ret;
486
400
  
487
401
  if(debug){
488
 
    fprintf_plus(stderr, "Initializing GnuTLS\n");
 
402
    fprintf(stderr, "Initializing GnuTLS\n");
489
403
  }
490
404
  
491
405
  ret = gnutls_global_init();
492
406
  if(ret != GNUTLS_E_SUCCESS){
493
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
494
 
                 safer_gnutls_strerror(ret));
 
407
    fprintf(stderr, "GnuTLS global_init: %s\n",
 
408
            safer_gnutls_strerror(ret));
495
409
    return -1;
496
410
  }
497
411
  
504
418
  }
505
419
  
506
420
  /* OpenPGP credentials */
507
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
421
  gnutls_certificate_allocate_credentials(&mc.cred);
508
422
  if(ret != GNUTLS_E_SUCCESS){
509
 
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
510
 
                 safer_gnutls_strerror(ret));
 
423
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
 
424
                                                    from
 
425
                                                    -Wunreachable-code
 
426
                                                 */
 
427
            safer_gnutls_strerror(ret));
511
428
    gnutls_global_deinit();
512
429
    return -1;
513
430
  }
514
431
  
515
432
  if(debug){
516
 
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
517
 
                 " secret key %s as GnuTLS credentials\n",
518
 
                 pubkeyfilename,
519
 
                 seckeyfilename);
 
433
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
434
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
 
435
            seckeyfilename);
520
436
  }
521
437
  
522
438
  ret = gnutls_certificate_set_openpgp_key_file
523
439
    (mc.cred, pubkeyfilename, seckeyfilename,
524
440
     GNUTLS_OPENPGP_FMT_BASE64);
525
441
  if(ret != GNUTLS_E_SUCCESS){
526
 
    fprintf_plus(stderr,
527
 
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
528
 
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
529
 
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
530
 
                 safer_gnutls_strerror(ret));
 
442
    fprintf(stderr,
 
443
            "Error[%d] while reading the OpenPGP key pair ('%s',"
 
444
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
445
    fprintf(stderr, "The GnuTLS error is: %s\n",
 
446
            safer_gnutls_strerror(ret));
531
447
    goto globalfail;
532
448
  }
533
449
  
534
450
  /* GnuTLS server initialization */
535
451
  ret = gnutls_dh_params_init(&mc.dh_params);
536
452
  if(ret != GNUTLS_E_SUCCESS){
537
 
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
538
 
                 " initialization: %s\n",
539
 
                 safer_gnutls_strerror(ret));
 
453
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
454
            " %s\n", safer_gnutls_strerror(ret));
540
455
    goto globalfail;
541
456
  }
542
457
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
543
458
  if(ret != GNUTLS_E_SUCCESS){
544
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
545
 
                 safer_gnutls_strerror(ret));
 
459
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
460
            safer_gnutls_strerror(ret));
546
461
    goto globalfail;
547
462
  }
548
463
  
561
476
static int init_gnutls_session(gnutls_session_t *session){
562
477
  int ret;
563
478
  /* GnuTLS session creation */
564
 
  do {
565
 
    ret = gnutls_init(session, GNUTLS_SERVER);
566
 
    if(quit_now){
567
 
      return -1;
568
 
    }
569
 
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
 
479
  ret = gnutls_init(session, GNUTLS_SERVER);
570
480
  if(ret != GNUTLS_E_SUCCESS){
571
 
    fprintf_plus(stderr,
572
 
                 "Error in GnuTLS session initialization: %s\n",
573
 
                 safer_gnutls_strerror(ret));
 
481
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
482
            safer_gnutls_strerror(ret));
574
483
  }
575
484
  
576
485
  {
577
486
    const char *err;
578
 
    do {
579
 
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
580
 
      if(quit_now){
581
 
        gnutls_deinit(*session);
582
 
        return -1;
583
 
      }
584
 
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
 
487
    ret = gnutls_priority_set_direct(*session, mc.priority, &err);
585
488
    if(ret != GNUTLS_E_SUCCESS){
586
 
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
587
 
      fprintf_plus(stderr, "GnuTLS error: %s\n",
588
 
                   safer_gnutls_strerror(ret));
 
489
      fprintf(stderr, "Syntax error at: %s\n", err);
 
490
      fprintf(stderr, "GnuTLS error: %s\n",
 
491
              safer_gnutls_strerror(ret));
589
492
      gnutls_deinit(*session);
590
493
      return -1;
591
494
    }
592
495
  }
593
496
  
594
 
  do {
595
 
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
596
 
                                 mc.cred);
597
 
    if(quit_now){
598
 
      gnutls_deinit(*session);
599
 
      return -1;
600
 
    }
601
 
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
 
497
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
 
498
                               mc.cred);
602
499
  if(ret != GNUTLS_E_SUCCESS){
603
 
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
604
 
                 safer_gnutls_strerror(ret));
 
500
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
501
            safer_gnutls_strerror(ret));
605
502
    gnutls_deinit(*session);
606
503
    return -1;
607
504
  }
608
505
  
609
506
  /* ignore client certificate if any. */
610
 
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
 
507
  gnutls_certificate_server_set_request(*session,
 
508
                                        GNUTLS_CERT_IGNORE);
611
509
  
612
510
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
613
511
  
622
520
static int start_mandos_communication(const char *ip, uint16_t port,
623
521
                                      AvahiIfIndex if_index,
624
522
                                      int af){
625
 
  int ret, tcp_sd = -1;
 
523
  int ret, tcp_sd;
626
524
  ssize_t sret;
627
525
  union {
628
526
    struct sockaddr_in in;
629
527
    struct sockaddr_in6 in6;
630
528
  } to;
631
529
  char *buffer = NULL;
632
 
  char *decrypted_buffer = NULL;
 
530
  char *decrypted_buffer;
633
531
  size_t buffer_length = 0;
634
532
  size_t buffer_capacity = 0;
 
533
  ssize_t decrypted_buffer_size;
635
534
  size_t written;
636
 
  int retval = -1;
 
535
  int retval = 0;
637
536
  gnutls_session_t session;
638
537
  int pf;                       /* Protocol family */
639
538
  
640
 
  errno = 0;
641
 
  
642
 
  if(quit_now){
643
 
    errno = EINTR;
644
 
    return -1;
645
 
  }
646
 
  
647
539
  switch(af){
648
540
  case AF_INET6:
649
541
    pf = PF_INET6;
652
544
    pf = PF_INET;
653
545
    break;
654
546
  default:
655
 
    fprintf_plus(stderr, "Bad address family: %d\n", af);
656
 
    errno = EINVAL;
 
547
    fprintf(stderr, "Bad address family: %d\n", af);
657
548
    return -1;
658
549
  }
659
550
  
663
554
  }
664
555
  
665
556
  if(debug){
666
 
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
667
 
                 PRIu16 "\n", ip, port);
 
557
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
558
            "\n", ip, port);
668
559
  }
669
560
  
670
561
  tcp_sd = socket(pf, SOCK_STREAM, 0);
671
562
  if(tcp_sd < 0){
672
 
    int e = errno;
673
 
    perror_plus("socket");
674
 
    errno = e;
675
 
    goto mandos_end;
676
 
  }
677
 
  
678
 
  if(quit_now){
679
 
    errno = EINTR;
680
 
    goto mandos_end;
 
563
    perror("socket");
 
564
    return -1;
681
565
  }
682
566
  
683
567
  memset(&to, 0, sizeof(to));
689
573
    ret = inet_pton(af, ip, &to.in.sin_addr);
690
574
  }
691
575
  if(ret < 0 ){
692
 
    int e = errno;
693
 
    perror_plus("inet_pton");
694
 
    errno = e;
695
 
    goto mandos_end;
 
576
    perror("inet_pton");
 
577
    return -1;
696
578
  }
697
579
  if(ret == 0){
698
 
    int e = errno;
699
 
    fprintf_plus(stderr, "Bad address: %s\n", ip);
700
 
    errno = e;
701
 
    goto mandos_end;
 
580
    fprintf(stderr, "Bad address: %s\n", ip);
 
581
    return -1;
702
582
  }
703
583
  if(af == AF_INET6){
704
584
    to.in6.sin6_port = htons(port); /* Spurious warnings from
707
587
    
708
588
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
709
589
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
710
 
                                -Wunreachable-code*/
 
590
                              -Wunreachable-code*/
711
591
      if(if_index == AVAHI_IF_UNSPEC){
712
 
        fprintf_plus(stderr, "An IPv6 link-local address is"
713
 
                     " incomplete without a network interface\n");
714
 
        errno = EINVAL;
715
 
        goto mandos_end;
 
592
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
593
                " without a network interface\n");
 
594
        return -1;
716
595
      }
717
596
      /* Set the network interface number as scope */
718
597
      to.in6.sin6_scope_id = (uint32_t)if_index;
723
602
                                     -Wunreachable-code */
724
603
  }
725
604
  
726
 
  if(quit_now){
727
 
    errno = EINTR;
728
 
    goto mandos_end;
729
 
  }
730
 
  
731
605
  if(debug){
732
606
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
733
607
      char interface[IF_NAMESIZE];
734
608
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
735
 
        perror_plus("if_indextoname");
 
609
        perror("if_indextoname");
736
610
      } else {
737
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
738
 
                     "\n", ip, interface, port);
 
611
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
612
                ip, interface, port);
739
613
      }
740
614
    } else {
741
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
742
 
                   ip, port);
 
615
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
616
              port);
743
617
    }
744
618
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
745
619
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
752
626
                        sizeof(addrstr));
753
627
    }
754
628
    if(pcret == NULL){
755
 
      perror_plus("inet_ntop");
 
629
      perror("inet_ntop");
756
630
    } else {
757
631
      if(strcmp(addrstr, ip) != 0){
758
 
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
632
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
759
633
      }
760
634
    }
761
635
  }
762
636
  
763
 
  if(quit_now){
764
 
    errno = EINTR;
765
 
    goto mandos_end;
766
 
  }
767
 
  
768
637
  if(af == AF_INET6){
769
638
    ret = connect(tcp_sd, &to.in6, sizeof(to));
770
639
  } else {
771
640
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
772
641
  }
773
642
  if(ret < 0){
774
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
775
 
      int e = errno;
776
 
      perror_plus("connect");
777
 
      errno = e;
778
 
    }
779
 
    goto mandos_end;
780
 
  }
781
 
  
782
 
  if(quit_now){
783
 
    errno = EINTR;
784
 
    goto mandos_end;
 
643
    perror("connect");
 
644
    return -1;
785
645
  }
786
646
  
787
647
  const char *out = mandos_protocol_version;
789
649
  while(true){
790
650
    size_t out_size = strlen(out);
791
651
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
792
 
                                        out_size - written));
 
652
                                   out_size - written));
793
653
    if(ret == -1){
794
 
      int e = errno;
795
 
      perror_plus("write");
796
 
      errno = e;
 
654
      perror("write");
 
655
      retval = -1;
797
656
      goto mandos_end;
798
657
    }
799
658
    written += (size_t)ret;
807
666
        break;
808
667
      }
809
668
    }
810
 
  
811
 
    if(quit_now){
812
 
      errno = EINTR;
813
 
      goto mandos_end;
814
 
    }
815
669
  }
816
670
  
817
671
  if(debug){
818
 
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
819
 
  }
820
 
  
821
 
  if(quit_now){
822
 
    errno = EINTR;
823
 
    goto mandos_end;
824
 
  }
825
 
  
826
 
  /* This casting via intptr_t is to eliminate warning about casting
827
 
     an int to a pointer type.  This is exactly how the GnuTLS Guile
828
 
     function "set-session-transport-fd!" does it. */
829
 
  gnutls_transport_set_ptr(session,
830
 
                           (gnutls_transport_ptr_t)(intptr_t)tcp_sd);
831
 
  
832
 
  if(quit_now){
833
 
    errno = EINTR;
834
 
    goto mandos_end;
835
 
  }
836
 
  
837
 
  do {
 
672
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
673
  }
 
674
  
 
675
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
 
676
  
 
677
  do{
838
678
    ret = gnutls_handshake(session);
839
 
    if(quit_now){
840
 
      errno = EINTR;
841
 
      goto mandos_end;
842
 
    }
843
679
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
844
680
  
845
681
  if(ret != GNUTLS_E_SUCCESS){
846
682
    if(debug){
847
 
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
 
683
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
848
684
      gnutls_perror(ret);
849
685
    }
850
 
    errno = EPROTO;
 
686
    retval = -1;
851
687
    goto mandos_end;
852
688
  }
853
689
  
854
690
  /* Read OpenPGP packet that contains the wanted password */
855
691
  
856
692
  if(debug){
857
 
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
858
 
                 " %s\n", ip);
 
693
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
694
            ip);
859
695
  }
860
696
  
861
697
  while(true){
862
 
    
863
 
    if(quit_now){
864
 
      errno = EINTR;
865
 
      goto mandos_end;
866
 
    }
867
 
    
868
698
    buffer_capacity = incbuffer(&buffer, buffer_length,
869
 
                                buffer_capacity);
 
699
                                   buffer_capacity);
870
700
    if(buffer_capacity == 0){
871
 
      int e = errno;
872
 
      perror_plus("incbuffer");
873
 
      errno = e;
874
 
      goto mandos_end;
875
 
    }
876
 
    
877
 
    if(quit_now){
878
 
      errno = EINTR;
 
701
      perror("incbuffer");
 
702
      retval = -1;
879
703
      goto mandos_end;
880
704
    }
881
705
    
890
714
      case GNUTLS_E_AGAIN:
891
715
        break;
892
716
      case GNUTLS_E_REHANDSHAKE:
893
 
        do {
 
717
        do{
894
718
          ret = gnutls_handshake(session);
895
 
          
896
 
          if(quit_now){
897
 
            errno = EINTR;
898
 
            goto mandos_end;
899
 
          }
900
719
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
901
720
        if(ret < 0){
902
 
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
903
 
                       "***\n");
 
721
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
904
722
          gnutls_perror(ret);
905
 
          errno = EPROTO;
 
723
          retval = -1;
906
724
          goto mandos_end;
907
725
        }
908
726
        break;
909
727
      default:
910
 
        fprintf_plus(stderr, "Unknown error while reading data from"
911
 
                     " encrypted session with Mandos server\n");
 
728
        fprintf(stderr, "Unknown error while reading data from"
 
729
                " encrypted session with Mandos server\n");
 
730
        retval = -1;
912
731
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
913
 
        errno = EIO;
914
732
        goto mandos_end;
915
733
      }
916
734
    } else {
919
737
  }
920
738
  
921
739
  if(debug){
922
 
    fprintf_plus(stderr, "Closing TLS session\n");
923
 
  }
924
 
  
925
 
  if(quit_now){
926
 
    errno = EINTR;
927
 
    goto mandos_end;
928
 
  }
929
 
  
930
 
  do {
931
 
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
932
 
    if(quit_now){
933
 
      errno = EINTR;
934
 
      goto mandos_end;
935
 
    }
936
 
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
 
740
    fprintf(stderr, "Closing TLS session\n");
 
741
  }
 
742
  
 
743
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
937
744
  
938
745
  if(buffer_length > 0){
939
 
    ssize_t decrypted_buffer_size;
940
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
 
746
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
747
                                               buffer_length,
941
748
                                               &decrypted_buffer);
942
749
    if(decrypted_buffer_size >= 0){
943
 
      
944
750
      written = 0;
945
751
      while(written < (size_t) decrypted_buffer_size){
946
 
        if(quit_now){
947
 
          errno = EINTR;
948
 
          goto mandos_end;
949
 
        }
950
 
        
951
752
        ret = (int)fwrite(decrypted_buffer + written, 1,
952
753
                          (size_t)decrypted_buffer_size - written,
953
754
                          stdout);
954
755
        if(ret == 0 and ferror(stdout)){
955
 
          int e = errno;
956
756
          if(debug){
957
 
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
958
 
                         strerror(errno));
 
757
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
758
                    strerror(errno));
959
759
          }
960
 
          errno = e;
961
 
          goto mandos_end;
 
760
          retval = -1;
 
761
          break;
962
762
        }
963
763
        written += (size_t)ret;
964
764
      }
965
 
      retval = 0;
 
765
      free(decrypted_buffer);
 
766
    } else {
 
767
      retval = -1;
966
768
    }
 
769
  } else {
 
770
    retval = -1;
967
771
  }
968
772
  
969
773
  /* Shutdown procedure */
970
774
  
971
775
 mandos_end:
972
 
  {
973
 
    int e = errno;
974
 
    free(decrypted_buffer);
975
 
    free(buffer);
976
 
    if(tcp_sd >= 0){
977
 
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
978
 
    }
979
 
    if(ret == -1){
980
 
      if(e == 0){
981
 
        e = errno;
982
 
      }
983
 
      perror_plus("close");
984
 
    }
985
 
    gnutls_deinit(session);
986
 
    errno = e;
987
 
    if(quit_now){
988
 
      errno = EINTR;
989
 
      retval = -1;
990
 
    }
 
776
  free(buffer);
 
777
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
778
  if(ret == -1){
 
779
    perror("close");
991
780
  }
 
781
  gnutls_deinit(session);
992
782
  return retval;
993
783
}
994
784
 
1011
801
  /* Called whenever a service has been resolved successfully or
1012
802
     timed out */
1013
803
  
1014
 
  if(quit_now){
1015
 
    return;
1016
 
  }
1017
 
  
1018
804
  switch(event){
1019
805
  default:
1020
806
  case AVAHI_RESOLVER_FAILURE:
1021
 
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1022
 
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1023
 
                 domain,
1024
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
807
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
 
808
            " of type '%s' in domain '%s': %s\n", name, type, domain,
 
809
            avahi_strerror(avahi_server_errno(mc.server)));
1025
810
    break;
1026
811
    
1027
812
  case AVAHI_RESOLVER_FOUND:
1029
814
      char ip[AVAHI_ADDRESS_STR_MAX];
1030
815
      avahi_address_snprint(ip, sizeof(ip), address);
1031
816
      if(debug){
1032
 
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
1033
 
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1034
 
                     host_name, ip, (intmax_t)interface, port);
 
817
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
818
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
 
819
                ip, (intmax_t)interface, port);
1035
820
      }
1036
821
      int ret = start_mandos_communication(ip, port, interface,
1037
822
                                           avahi_proto_to_af(proto));
1038
823
      if(ret == 0){
1039
824
        avahi_simple_poll_quit(mc.simple_poll);
1040
 
      } else {
1041
 
        if(not add_server(ip, port, interface,
1042
 
                          avahi_proto_to_af(proto))){
1043
 
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1044
 
                       " list\n", name);
1045
 
        }
1046
825
      }
1047
826
    }
1048
827
  }
1064
843
  /* Called whenever a new services becomes available on the LAN or
1065
844
     is removed from the LAN */
1066
845
  
1067
 
  if(quit_now){
1068
 
    return;
1069
 
  }
1070
 
  
1071
846
  switch(event){
1072
847
  default:
1073
848
  case AVAHI_BROWSER_FAILURE:
1074
849
    
1075
 
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1076
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
850
    fprintf(stderr, "(Avahi browser) %s\n",
 
851
            avahi_strerror(avahi_server_errno(mc.server)));
1077
852
    avahi_simple_poll_quit(mc.simple_poll);
1078
853
    return;
1079
854
    
1086
861
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1087
862
                                    name, type, domain, protocol, 0,
1088
863
                                    resolve_callback, NULL) == NULL)
1089
 
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1090
 
                   " %s\n", name,
1091
 
                   avahi_strerror(avahi_server_errno(mc.server)));
 
864
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
865
              name, avahi_strerror(avahi_server_errno(mc.server)));
1092
866
    break;
1093
867
    
1094
868
  case AVAHI_BROWSER_REMOVE:
1097
871
  case AVAHI_BROWSER_ALL_FOR_NOW:
1098
872
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1099
873
    if(debug){
1100
 
      fprintf_plus(stderr, "No Mandos server found, still"
1101
 
                   " searching...\n");
 
874
      fprintf(stderr, "No Mandos server found, still searching...\n");
1102
875
    }
1103
876
    break;
1104
877
  }
1105
878
}
1106
879
 
1107
 
/* Signal handler that stops main loop after SIGTERM */
1108
 
static void handle_sigterm(int sig){
 
880
sig_atomic_t quit_now = 0;
 
881
 
 
882
/* stop main loop after sigterm has been called */
 
883
static void handle_sigterm(__attribute__((unused)) int sig){
1109
884
  if(quit_now){
1110
885
    return;
1111
886
  }
1112
887
  quit_now = 1;
1113
 
  signal_received = sig;
1114
888
  int old_errno = errno;
1115
 
  /* set main loop to exit */
1116
889
  if(mc.simple_poll != NULL){
1117
890
    avahi_simple_poll_quit(mc.simple_poll);
1118
891
  }
1119
892
  errno = old_errno;
1120
893
}
1121
894
 
1122
 
bool get_flags(const char *ifname, struct ifreq *ifr){
1123
 
  int ret;
1124
 
  
1125
 
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1126
 
  if(s < 0){
1127
 
    perror_plus("socket");
1128
 
    return false;
1129
 
  }
1130
 
  strcpy(ifr->ifr_name, ifname);
1131
 
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1132
 
  if(ret == -1){
1133
 
    if(debug){
1134
 
      perror_plus("ioctl SIOCGIFFLAGS");
1135
 
    }
1136
 
    return false;
1137
 
  }
1138
 
  return true;
1139
 
}
1140
 
 
1141
 
bool good_flags(const char *ifname, const struct ifreq *ifr){
1142
 
  
1143
 
  /* Reject the loopback device */
1144
 
  if(ifr->ifr_flags & IFF_LOOPBACK){
1145
 
    if(debug){
1146
 
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1147
 
                   ifname);
1148
 
    }
1149
 
    return false;
1150
 
  }
1151
 
  /* Accept point-to-point devices only if connect_to is specified */
1152
 
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1153
 
    if(debug){
1154
 
      fprintf_plus(stderr, "Accepting point-to-point interface"
1155
 
                   " \"%s\"\n", ifname);
1156
 
    }
1157
 
    return true;
1158
 
  }
1159
 
  /* Otherwise, reject non-broadcast-capable devices */
1160
 
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1161
 
    if(debug){
1162
 
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
1163
 
                   " \"%s\"\n", ifname);
1164
 
    }
1165
 
    return false;
1166
 
  }
1167
 
  /* Reject non-ARP interfaces (including dummy interfaces) */
1168
 
  if(ifr->ifr_flags & IFF_NOARP){
1169
 
    if(debug){
1170
 
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1171
 
                   ifname);
1172
 
    }
1173
 
    return false;
1174
 
  }
1175
 
  
1176
 
  /* Accept this device */
1177
 
  if(debug){
1178
 
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1179
 
  }
1180
 
  return true;
1181
 
}
1182
 
 
1183
 
/* 
1184
 
 * This function determines if a directory entry in /sys/class/net
1185
 
 * corresponds to an acceptable network device.
1186
 
 * (This function is passed to scandir(3) as a filter function.)
1187
 
 */
1188
 
int good_interface(const struct dirent *if_entry){
1189
 
  if(if_entry->d_name[0] == '.'){
1190
 
    return 0;
1191
 
  }
1192
 
  
1193
 
  struct ifreq ifr;
1194
 
  if(not get_flags(if_entry->d_name, &ifr)){
1195
 
    if(debug){
1196
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1197
 
                   "\"%s\"\n", if_entry->d_name);
1198
 
    }
1199
 
    return 0;
1200
 
  }
1201
 
  
1202
 
  if(not good_flags(if_entry->d_name, &ifr)){
1203
 
    return 0;
1204
 
  }
1205
 
  return 1;
1206
 
}
1207
 
 
1208
 
/* 
1209
 
 * This function determines if a directory entry in /sys/class/net
1210
 
 * corresponds to an acceptable network device which is up.
1211
 
 * (This function is passed to scandir(3) as a filter function.)
1212
 
 */
1213
 
int up_interface(const struct dirent *if_entry){
1214
 
  if(if_entry->d_name[0] == '.'){
1215
 
    return 0;
1216
 
  }
1217
 
  
1218
 
  struct ifreq ifr;
1219
 
  if(not get_flags(if_entry->d_name, &ifr)){
1220
 
    if(debug){
1221
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1222
 
                   "\"%s\"\n", if_entry->d_name);
1223
 
    }
1224
 
    return 0;
1225
 
  }
1226
 
  
1227
 
  /* Reject down interfaces */
1228
 
  if(not (ifr.ifr_flags & IFF_UP)){
1229
 
    if(debug){
1230
 
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
1231
 
                   if_entry->d_name);
1232
 
    }
1233
 
    return 0;
1234
 
  }
1235
 
  
1236
 
  /* Reject non-running interfaces */
1237
 
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1238
 
    if(debug){
1239
 
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
1240
 
                   if_entry->d_name);
1241
 
    }
1242
 
    return 0;
1243
 
  }
1244
 
  
1245
 
  if(not good_flags(if_entry->d_name, &ifr)){
1246
 
    return 0;
1247
 
  }
1248
 
  return 1;
1249
 
}
1250
 
 
1251
 
int notdotentries(const struct dirent *direntry){
1252
 
  /* Skip "." and ".." */
1253
 
  if(direntry->d_name[0] == '.'
1254
 
     and (direntry->d_name[1] == '\0'
1255
 
          or (direntry->d_name[1] == '.'
1256
 
              and direntry->d_name[2] == '\0'))){
1257
 
    return 0;
1258
 
  }
1259
 
  return 1;
1260
 
}
1261
 
 
1262
 
/* Is this directory entry a runnable program? */
1263
 
int runnable_hook(const struct dirent *direntry){
1264
 
  int ret;
1265
 
  size_t sret;
1266
 
  struct stat st;
1267
 
  
1268
 
  if((direntry->d_name)[0] == '\0'){
1269
 
    /* Empty name? */
1270
 
    return 0;
1271
 
  }
1272
 
  
1273
 
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1274
 
                "abcdefghijklmnopqrstuvwxyz"
1275
 
                "0123456789"
1276
 
                "_-");
1277
 
  if((direntry->d_name)[sret] != '\0'){
1278
 
    /* Contains non-allowed characters */
1279
 
    if(debug){
1280
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
1281
 
                   direntry->d_name);
1282
 
    }
1283
 
    return 0;
1284
 
  }
1285
 
  
1286
 
  char *fullname = NULL;
1287
 
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1288
 
  if(ret < 0){
1289
 
    perror_plus("asprintf");
1290
 
    return 0;
1291
 
  }
1292
 
  
1293
 
  ret = stat(fullname, &st);
1294
 
  if(ret == -1){
1295
 
    if(debug){
1296
 
      perror_plus("Could not stat hook");
1297
 
    }
1298
 
    return 0;
1299
 
  }
1300
 
  if(not (S_ISREG(st.st_mode))){
1301
 
    /* Not a regular file */
1302
 
    if(debug){
1303
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
1304
 
                   direntry->d_name);
1305
 
    }
1306
 
    return 0;
1307
 
  }
1308
 
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1309
 
    /* Not executable */
1310
 
    if(debug){
1311
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
1312
 
                   direntry->d_name);
1313
 
    }
1314
 
    return 0;
1315
 
  }
1316
 
  if(debug){
1317
 
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
1318
 
                 direntry->d_name);
1319
 
  }
1320
 
  return 1;
1321
 
}
1322
 
 
1323
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1324
 
  int ret;
1325
 
  struct timespec now;
1326
 
  struct timespec waited_time;
1327
 
  intmax_t block_time;
1328
 
  
1329
 
  while(true){
1330
 
    if(mc.current_server == NULL){
1331
 
      if (debug){
1332
 
        fprintf_plus(stderr, "Wait until first server is found."
1333
 
                     " No timeout!\n");
1334
 
      }
1335
 
      ret = avahi_simple_poll_iterate(s, -1);
1336
 
    } else {
1337
 
      if (debug){
1338
 
        fprintf_plus(stderr, "Check current_server if we should run"
1339
 
                     " it, or wait\n");
1340
 
      }
1341
 
      /* the current time */
1342
 
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1343
 
      if(ret == -1){
1344
 
        perror_plus("clock_gettime");
1345
 
        return -1;
1346
 
      }
1347
 
      /* Calculating in ms how long time between now and server
1348
 
         who we visted longest time ago. Now - last seen.  */
1349
 
      waited_time.tv_sec = (now.tv_sec
1350
 
                            - mc.current_server->last_seen.tv_sec);
1351
 
      waited_time.tv_nsec = (now.tv_nsec
1352
 
                             - mc.current_server->last_seen.tv_nsec);
1353
 
      /* total time is 10s/10,000ms.
1354
 
         Converting to s from ms by dividing by 1,000,
1355
 
         and ns to ms by dividing by 1,000,000. */
1356
 
      block_time = ((retry_interval
1357
 
                     - ((intmax_t)waited_time.tv_sec * 1000))
1358
 
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1359
 
      
1360
 
      if (debug){
1361
 
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1362
 
                     block_time);
1363
 
      }
1364
 
      
1365
 
      if(block_time <= 0){
1366
 
        ret = start_mandos_communication(mc.current_server->ip,
1367
 
                                         mc.current_server->port,
1368
 
                                         mc.current_server->if_index,
1369
 
                                         mc.current_server->af);
1370
 
        if(ret == 0){
1371
 
          avahi_simple_poll_quit(mc.simple_poll);
1372
 
          return 0;
1373
 
        }
1374
 
        ret = clock_gettime(CLOCK_MONOTONIC,
1375
 
                            &mc.current_server->last_seen);
1376
 
        if(ret == -1){
1377
 
          perror_plus("clock_gettime");
1378
 
          return -1;
1379
 
        }
1380
 
        mc.current_server = mc.current_server->next;
1381
 
        block_time = 0;         /* Call avahi to find new Mandos
1382
 
                                   servers, but don't block */
1383
 
      }
1384
 
      
1385
 
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1386
 
    }
1387
 
    if(ret != 0){
1388
 
      if (ret > 0 or errno != EINTR){
1389
 
        return (ret != 1) ? ret : 0;
1390
 
      }
1391
 
    }
1392
 
  }
1393
 
}
1394
 
 
1395
 
/* Set effective uid to 0, return errno */
1396
 
int raise_privileges(void){
1397
 
  int old_errno = errno;
1398
 
  int ret_errno = 0;
1399
 
  errno = 0;
1400
 
  if(seteuid(0) == -1){
1401
 
    perror_plus("seteuid");
1402
 
  }
1403
 
  ret_errno = errno;
1404
 
  errno = old_errno;
1405
 
  return ret_errno;
1406
 
}
1407
 
 
1408
 
/* Set effective and real user ID to 0.  Return errno. */
1409
 
int raise_privileges_permanently(void){
1410
 
  int old_errno = errno;
1411
 
  int ret_errno = raise_privileges();
1412
 
  if(ret_errno != 0){
1413
 
    errno = old_errno;
1414
 
    return ret_errno;
1415
 
  }
1416
 
  errno = 0;
1417
 
  if(setuid(0) == -1){
1418
 
    perror_plus("seteuid");
1419
 
  }
1420
 
  ret_errno = errno;
1421
 
  errno = old_errno;
1422
 
  return ret_errno;
1423
 
}
1424
 
 
1425
 
/* Set effective user ID to unprivileged saved user ID */
1426
 
int lower_privileges(void){
1427
 
  int old_errno = errno;
1428
 
  int ret_errno = 0;
1429
 
  errno = 0;
1430
 
  if(seteuid(uid) == -1){
1431
 
    perror_plus("seteuid");
1432
 
  }
1433
 
  ret_errno = errno;
1434
 
  errno = old_errno;
1435
 
  return ret_errno;
1436
 
}
1437
 
 
1438
 
bool run_network_hooks(const char *mode, const char *interface,
1439
 
                       const float delay){
1440
 
  struct dirent **direntries;
1441
 
  struct dirent *direntry;
1442
 
  int ret;
1443
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1444
 
                         alphasort);
1445
 
  if(numhooks == -1){
1446
 
    perror_plus("scandir");
1447
 
  } else {
1448
 
    int devnull = open("/dev/null", O_RDONLY);
1449
 
    for(int i = 0; i < numhooks; i++){
1450
 
      direntry = direntries[i];
1451
 
      char *fullname = NULL;
1452
 
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1453
 
      if(ret < 0){
1454
 
        perror_plus("asprintf");
1455
 
        continue;
1456
 
      }
1457
 
      if(debug){
1458
 
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
1459
 
                     direntry->d_name);
1460
 
      }
1461
 
      pid_t hook_pid = fork();
1462
 
      if(hook_pid == 0){
1463
 
        /* Child */
1464
 
        /* Raise privileges */
1465
 
        raise_privileges_permanently();
1466
 
        /* Set group */
1467
 
        errno = 0;
1468
 
        ret = setgid(0);
1469
 
        if(ret == -1){
1470
 
          perror_plus("setgid");
1471
 
        }
1472
 
        /* Reset supplementary groups */
1473
 
        errno = 0;
1474
 
        ret = setgroups(0, NULL);
1475
 
        if(ret == -1){
1476
 
          perror_plus("setgroups");
1477
 
        }
1478
 
        dup2(devnull, STDIN_FILENO);
1479
 
        close(devnull);
1480
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1481
 
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1482
 
        if(ret == -1){
1483
 
          perror_plus("setenv");
1484
 
          _exit(EX_OSERR);
1485
 
        }
1486
 
        ret = setenv("DEVICE", interface, 1);
1487
 
        if(ret == -1){
1488
 
          perror_plus("setenv");
1489
 
          _exit(EX_OSERR);
1490
 
        }
1491
 
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1492
 
        if(ret == -1){
1493
 
          perror_plus("setenv");
1494
 
          _exit(EX_OSERR);
1495
 
        }
1496
 
        ret = setenv("MODE", mode, 1);
1497
 
        if(ret == -1){
1498
 
          perror_plus("setenv");
1499
 
          _exit(EX_OSERR);
1500
 
        }
1501
 
        char *delaystring;
1502
 
        ret = asprintf(&delaystring, "%f", delay);
1503
 
        if(ret == -1){
1504
 
          perror_plus("asprintf");
1505
 
          _exit(EX_OSERR);
1506
 
        }
1507
 
        ret = setenv("DELAY", delaystring, 1);
1508
 
        if(ret == -1){
1509
 
          free(delaystring);
1510
 
          perror_plus("setenv");
1511
 
          _exit(EX_OSERR);
1512
 
        }
1513
 
        free(delaystring);
1514
 
        if(connect_to != NULL){
1515
 
          ret = setenv("CONNECT", connect_to, 1);
1516
 
          if(ret == -1){
1517
 
            perror_plus("setenv");
1518
 
            _exit(EX_OSERR);
1519
 
          }
1520
 
        }
1521
 
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
1522
 
          perror_plus("execl");
1523
 
          _exit(EXIT_FAILURE);
1524
 
        }
1525
 
      } else {
1526
 
        int status;
1527
 
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1528
 
          perror_plus("waitpid");
1529
 
          free(fullname);
1530
 
          continue;
1531
 
        }
1532
 
        if(WIFEXITED(status)){
1533
 
          if(WEXITSTATUS(status) != 0){
1534
 
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1535
 
                         " with status %d\n", direntry->d_name,
1536
 
                         WEXITSTATUS(status));
1537
 
            free(fullname);
1538
 
            continue;
1539
 
          }
1540
 
        } else if(WIFSIGNALED(status)){
1541
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1542
 
                       " signal %d\n", direntry->d_name,
1543
 
                       WTERMSIG(status));
1544
 
          free(fullname);
1545
 
          continue;
1546
 
        } else {
1547
 
          fprintf_plus(stderr, "Warning: network hook \"%s\""
1548
 
                       " crashed\n", direntry->d_name);
1549
 
          free(fullname);
1550
 
          continue;
1551
 
        }
1552
 
      }
1553
 
      free(fullname);
1554
 
      if(debug){
1555
 
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1556
 
                     direntry->d_name);
1557
 
      }
1558
 
    }
1559
 
    close(devnull);
1560
 
  }
1561
 
  return true;
1562
 
}
1563
 
 
1564
 
int bring_up_interface(const char * const interface, const float delay){
1565
 
  int sd = -1;
1566
 
  int ret;
1567
 
  struct ifreq network;
1568
 
  AvahiIfIndex if_index = (AvahiIfIndex)if_nametoindex(interface);
1569
 
  if(if_index == 0){
1570
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1571
 
    return EX_UNAVAILABLE;
1572
 
  }
1573
 
  
1574
 
  if(quit_now){
1575
 
    return EINTR;
1576
 
  }
1577
 
  
1578
 
  /* Re-raise priviliges */
1579
 
  raise_privileges();
1580
 
    
1581
 
#ifdef __linux__
1582
 
  /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1583
 
     messages about the network interface to mess up the prompt */
1584
 
  ret = klogctl(8, NULL, 5);
1585
 
  bool restore_loglevel = true;
1586
 
  if(ret == -1){
1587
 
    restore_loglevel = false;
1588
 
    perror_plus("klogctl");
1589
 
  }
1590
 
#endif  /* __linux__ */
1591
 
    
1592
 
  sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1593
 
  if(sd < 0){
1594
 
    perror_plus("socket");
1595
 
#ifdef __linux__
1596
 
    if(restore_loglevel){
1597
 
      ret = klogctl(7, NULL, 0);
1598
 
      if(ret == -1){
1599
 
        perror_plus("klogctl");
1600
 
      }
1601
 
    }
1602
 
#endif  /* __linux__ */
1603
 
    /* Lower privileges */
1604
 
    lower_privileges();
1605
 
    return EX_OSERR;
1606
 
;
1607
 
  }
1608
 
  strcpy(network.ifr_name, interface);
1609
 
  ret = ioctl(sd, SIOCGIFFLAGS, &network);
1610
 
  if(ret == -1){
1611
 
    perror_plus("ioctl SIOCGIFFLAGS");
1612
 
#ifdef __linux__
1613
 
    if(restore_loglevel){
1614
 
      ret = klogctl(7, NULL, 0);
1615
 
      if(ret == -1){
1616
 
        perror_plus("klogctl");
1617
 
      }
1618
 
    }
1619
 
#endif  /* __linux__ */
1620
 
    /* Lower privileges */
1621
 
    lower_privileges();
1622
 
    return EX_OSERR;
1623
 
  }
1624
 
  if((network.ifr_flags & IFF_UP) == 0){
1625
 
    network.ifr_flags |= IFF_UP;
1626
 
    ret = ioctl(sd, SIOCSIFFLAGS, &network);
1627
 
    if(ret == -1){
1628
 
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1629
 
#ifdef __linux__
1630
 
      if(restore_loglevel){
1631
 
        ret = klogctl(7, NULL, 0);
1632
 
        if(ret == -1){
1633
 
          perror_plus("klogctl");
1634
 
        }
1635
 
      }
1636
 
#endif  /* __linux__ */
1637
 
        /* Lower privileges */
1638
 
      lower_privileges();
1639
 
      return EX_OSERR;
1640
 
    }
1641
 
  }
1642
 
  /* Sleep checking until interface is running.
1643
 
     Check every 0.25s, up to total time of delay */
1644
 
  for(int i=0; i < delay * 4; i++){
1645
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1646
 
    if(ret == -1){
1647
 
      perror_plus("ioctl SIOCGIFFLAGS");
1648
 
    } else if(network.ifr_flags & IFF_RUNNING){
1649
 
      break;
1650
 
    }
1651
 
    struct timespec sleeptime = { .tv_nsec = 250000000 };
1652
 
    ret = nanosleep(&sleeptime, NULL);
1653
 
    if(ret == -1 and errno != EINTR){
1654
 
      perror_plus("nanosleep");
1655
 
    }
1656
 
  }
1657
 
  /* Close the socket */
1658
 
  ret = (int)TEMP_FAILURE_RETRY(close(sd));
1659
 
  if(ret == -1){
1660
 
    perror_plus("close");
1661
 
  }
1662
 
#ifdef __linux__
1663
 
  if(restore_loglevel){
1664
 
    /* Restores kernel loglevel to default */
1665
 
    ret = klogctl(7, NULL, 0);
1666
 
    if(ret == -1){
1667
 
      perror_plus("klogctl");
1668
 
    }
1669
 
  }
1670
 
#endif  /* __linux__ */
1671
 
  /* Lower privileges */
1672
 
  lower_privileges();
1673
 
  return errno;
1674
 
}
1675
 
 
1676
895
int main(int argc, char *argv[]){
1677
896
  AvahiSServiceBrowser *sb = NULL;
1678
897
  int error;
1680
899
  intmax_t tmpmax;
1681
900
  char *tmp;
1682
901
  int exitcode = EXIT_SUCCESS;
1683
 
  const char *interface = "";
 
902
  const char *interface = "eth0";
1684
903
  struct ifreq network;
1685
 
  int sd = -1;
1686
 
  bool take_down_interface = false;
 
904
  int sd;
 
905
  uid_t uid;
 
906
  gid_t gid;
 
907
  char *connect_to = NULL;
1687
908
  char tempdir[] = "/tmp/mandosXXXXXX";
1688
909
  bool tempdir_created = false;
1689
910
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1693
914
  bool gnutls_initialized = false;
1694
915
  bool gpgme_initialized = false;
1695
916
  float delay = 2.5f;
1696
 
  double retry_interval = 10; /* 10s between trying a server and
1697
 
                                 retrying the same server again */
1698
917
  
1699
 
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
 
918
  struct sigaction old_sigterm_action;
1700
919
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1701
920
  
1702
 
  uid = getuid();
1703
 
  gid = getgid();
1704
 
  
1705
 
  /* Lower any group privileges we might have, just to be safe */
1706
 
  errno = 0;
1707
 
  ret = setgid(gid);
1708
 
  if(ret == -1){
1709
 
    perror_plus("setgid");
1710
 
  }
1711
 
  
1712
 
  /* Lower user privileges (temporarily) */
1713
 
  errno = 0;
1714
 
  ret = seteuid(uid);
1715
 
  if(ret == -1){
1716
 
    perror_plus("seteuid");
1717
 
  }
1718
 
  
1719
 
  if(quit_now){
1720
 
    goto end;
1721
 
  }
1722
 
  
1723
921
  {
1724
922
    struct argp_option options[] = {
1725
923
      { .name = "debug", .key = 128,
1754
952
        .arg = "SECONDS",
1755
953
        .doc = "Maximum delay to wait for interface startup",
1756
954
        .group = 2 },
1757
 
      { .name = "retry", .key = 132,
1758
 
        .arg = "SECONDS",
1759
 
        .doc = "Retry interval used when denied by the Mandos server",
1760
 
        .group = 2 },
1761
 
      { .name = "network-hook-dir", .key = 133,
1762
 
        .arg = "DIR",
1763
 
        .doc = "Directory where network hooks are located",
1764
 
        .group = 2 },
1765
 
      /*
1766
 
       * These reproduce what we would get without ARGP_NO_HELP
1767
 
       */
1768
 
      { .name = "help", .key = '?',
1769
 
        .doc = "Give this help list", .group = -1 },
1770
 
      { .name = "usage", .key = -3,
1771
 
        .doc = "Give a short usage message", .group = -1 },
1772
 
      { .name = "version", .key = 'V',
1773
 
        .doc = "Print program version", .group = -1 },
1774
955
      { .name = NULL }
1775
956
    };
1776
957
    
1777
958
    error_t parse_opt(int key, char *arg,
1778
959
                      struct argp_state *state){
1779
 
      errno = 0;
1780
960
      switch(key){
1781
961
      case 128:                 /* --debug */
1782
962
        debug = true;
1798
978
        tmpmax = strtoimax(arg, &tmp, 10);
1799
979
        if(errno != 0 or tmp == arg or *tmp != '\0'
1800
980
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
1801
 
          argp_error(state, "Bad number of DH bits");
 
981
          fprintf(stderr, "Bad number of DH bits\n");
 
982
          exit(EXIT_FAILURE);
1802
983
        }
1803
984
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1804
985
        break;
1809
990
        errno = 0;
1810
991
        delay = strtof(arg, &tmp);
1811
992
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1812
 
          argp_error(state, "Bad delay");
1813
 
        }
1814
 
      case 132:                 /* --retry */
1815
 
        errno = 0;
1816
 
        retry_interval = strtod(arg, &tmp);
1817
 
        if(errno != 0 or tmp == arg or *tmp != '\0'
1818
 
           or (retry_interval * 1000) > INT_MAX
1819
 
           or retry_interval < 0){
1820
 
          argp_error(state, "Bad retry interval");
1821
 
        }
1822
 
        break;
1823
 
      case 133:                 /* --network-hook-dir */
1824
 
        hookdir = arg;
1825
 
        break;
1826
 
        /*
1827
 
         * These reproduce what we would get without ARGP_NO_HELP
1828
 
         */
1829
 
      case '?':                 /* --help */
1830
 
        argp_state_help(state, state->out_stream,
1831
 
                        (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
1832
 
                        & ~(unsigned int)ARGP_HELP_EXIT_OK);
1833
 
      case -3:                  /* --usage */
1834
 
        argp_state_help(state, state->out_stream,
1835
 
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1836
 
      case 'V':                 /* --version */
1837
 
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1838
 
        exit(argp_err_exit_status);
 
993
          fprintf(stderr, "Bad delay\n");
 
994
          exit(EXIT_FAILURE);
 
995
        }
 
996
        break;
 
997
      case ARGP_KEY_ARG:
 
998
        argp_usage(state);
 
999
      case ARGP_KEY_END:
1839
1000
        break;
1840
1001
      default:
1841
1002
        return ARGP_ERR_UNKNOWN;
1842
1003
      }
1843
 
      return errno;
 
1004
      return 0;
1844
1005
    }
1845
1006
    
1846
1007
    struct argp argp = { .options = options, .parser = parse_opt,
1847
1008
                         .args_doc = "",
1848
1009
                         .doc = "Mandos client -- Get and decrypt"
1849
1010
                         " passwords from a Mandos server" };
1850
 
    ret = argp_parse(&argp, argc, argv,
1851
 
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
1852
 
    switch(ret){
1853
 
    case 0:
1854
 
      break;
1855
 
    case ENOMEM:
1856
 
    default:
1857
 
      errno = ret;
1858
 
      perror_plus("argp_parse");
1859
 
      exitcode = EX_OSERR;
1860
 
      goto end;
1861
 
    case EINVAL:
1862
 
      exitcode = EX_USAGE;
1863
 
      goto end;
1864
 
    }
1865
 
  }
1866
 
    
1867
 
  {
1868
 
    /* Work around Debian bug #633582:
1869
 
       <http://bugs.debian.org/633582> */
1870
 
    
1871
 
    /* Re-raise priviliges */
1872
 
    if(raise_privileges() == 0){
1873
 
      struct stat st;
1874
 
      
1875
 
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1876
 
        int seckey_fd = open(seckey, O_RDONLY);
1877
 
        if(seckey_fd == -1){
1878
 
          perror_plus("open");
1879
 
        } else {
1880
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1881
 
          if(ret == -1){
1882
 
            perror_plus("fstat");
1883
 
          } else {
1884
 
            if(S_ISREG(st.st_mode)
1885
 
               and st.st_uid == 0 and st.st_gid == 0){
1886
 
              ret = fchown(seckey_fd, uid, gid);
1887
 
              if(ret == -1){
1888
 
                perror_plus("fchown");
1889
 
              }
1890
 
            }
1891
 
          }
1892
 
          TEMP_FAILURE_RETRY(close(seckey_fd));
1893
 
        }
1894
 
      }
1895
 
    
1896
 
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1897
 
        int pubkey_fd = open(pubkey, O_RDONLY);
1898
 
        if(pubkey_fd == -1){
1899
 
          perror_plus("open");
1900
 
        } else {
1901
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1902
 
          if(ret == -1){
1903
 
            perror_plus("fstat");
1904
 
          } else {
1905
 
            if(S_ISREG(st.st_mode)
1906
 
               and st.st_uid == 0 and st.st_gid == 0){
1907
 
              ret = fchown(pubkey_fd, uid, gid);
1908
 
              if(ret == -1){
1909
 
                perror_plus("fchown");
1910
 
              }
1911
 
            }
1912
 
          }
1913
 
          TEMP_FAILURE_RETRY(close(pubkey_fd));
1914
 
        }
1915
 
      }
1916
 
    
1917
 
      /* Lower privileges */
1918
 
      errno = 0;
1919
 
      ret = seteuid(uid);
1920
 
      if(ret == -1){
1921
 
        perror_plus("seteuid");
1922
 
      }
1923
 
    }
1924
 
  }
1925
 
  
1926
 
  /* Run network hooks */
1927
 
  if(not run_network_hooks("start", interface, delay)){
1928
 
    goto end;
 
1011
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
 
1012
    if(ret == ARGP_ERR_UNKNOWN){
 
1013
      fprintf(stderr, "Unknown error while parsing arguments\n");
 
1014
      exitcode = EXIT_FAILURE;
 
1015
      goto end;
 
1016
    }
1929
1017
  }
1930
1018
  
1931
1019
  if(not debug){
1932
1020
    avahi_set_log_function(empty_log);
1933
1021
  }
1934
1022
  
1935
 
  if(interface[0] == '\0'){
1936
 
    struct dirent **direntries;
1937
 
    /* First look for interfaces that are up */
1938
 
    ret = scandir(sys_class_net, &direntries, up_interface,
1939
 
                  alphasort);
1940
 
    if(ret == 0){
1941
 
      /* No up interfaces, look for any good interfaces */
1942
 
      free(direntries);
1943
 
      ret = scandir(sys_class_net, &direntries, good_interface,
1944
 
                    alphasort);
1945
 
    }
1946
 
    if(ret >= 1){
1947
 
      /* Pick the first interface returned */
1948
 
      interface = strdup(direntries[0]->d_name);
1949
 
      if(debug){
1950
 
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1951
 
      }
1952
 
      if(interface == NULL){
1953
 
        perror_plus("malloc");
1954
 
        free(direntries);
1955
 
        exitcode = EXIT_FAILURE;
1956
 
        goto end;
1957
 
      }
1958
 
      free(direntries);
1959
 
    } else {
1960
 
      free(direntries);
1961
 
      fprintf_plus(stderr, "Could not find a network interface\n");
1962
 
      exitcode = EXIT_FAILURE;
1963
 
      goto end;
1964
 
    }
1965
 
  }
1966
 
  
1967
1023
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1968
1024
     from the signal handler */
1969
1025
  /* Initialize the pseudo-RNG for Avahi */
1970
1026
  srand((unsigned int) time(NULL));
1971
1027
  mc.simple_poll = avahi_simple_poll_new();
1972
1028
  if(mc.simple_poll == NULL){
1973
 
    fprintf_plus(stderr,
1974
 
                 "Avahi: Failed to create simple poll object.\n");
1975
 
    exitcode = EX_UNAVAILABLE;
 
1029
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1030
    exitcode = EXIT_FAILURE;
1976
1031
    goto end;
1977
1032
  }
1978
1033
  
1979
1034
  sigemptyset(&sigterm_action.sa_mask);
1980
1035
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1981
1036
  if(ret == -1){
1982
 
    perror_plus("sigaddset");
1983
 
    exitcode = EX_OSERR;
 
1037
    perror("sigaddset");
 
1038
    exitcode = EXIT_FAILURE;
1984
1039
    goto end;
1985
1040
  }
1986
1041
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1987
1042
  if(ret == -1){
1988
 
    perror_plus("sigaddset");
1989
 
    exitcode = EX_OSERR;
 
1043
    perror("sigaddset");
 
1044
    exitcode = EXIT_FAILURE;
1990
1045
    goto end;
1991
1046
  }
1992
1047
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1993
1048
  if(ret == -1){
1994
 
    perror_plus("sigaddset");
1995
 
    exitcode = EX_OSERR;
1996
 
    goto end;
1997
 
  }
1998
 
  /* Need to check if the handler is SIG_IGN before handling:
1999
 
     | [[info:libc:Initial Signal Actions]] |
2000
 
     | [[info:libc:Basic Signal Handling]]  |
2001
 
  */
2002
 
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
2003
 
  if(ret == -1){
2004
 
    perror_plus("sigaction");
2005
 
    return EX_OSERR;
2006
 
  }
2007
 
  if(old_sigterm_action.sa_handler != SIG_IGN){
2008
 
    ret = sigaction(SIGINT, &sigterm_action, NULL);
2009
 
    if(ret == -1){
2010
 
      perror_plus("sigaction");
2011
 
      exitcode = EX_OSERR;
2012
 
      goto end;
2013
 
    }
2014
 
  }
2015
 
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
2016
 
  if(ret == -1){
2017
 
    perror_plus("sigaction");
2018
 
    return EX_OSERR;
2019
 
  }
2020
 
  if(old_sigterm_action.sa_handler != SIG_IGN){
2021
 
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
2022
 
    if(ret == -1){
2023
 
      perror_plus("sigaction");
2024
 
      exitcode = EX_OSERR;
2025
 
      goto end;
2026
 
    }
2027
 
  }
2028
 
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
2029
 
  if(ret == -1){
2030
 
    perror_plus("sigaction");
2031
 
    return EX_OSERR;
2032
 
  }
2033
 
  if(old_sigterm_action.sa_handler != SIG_IGN){
2034
 
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
2035
 
    if(ret == -1){
2036
 
      perror_plus("sigaction");
2037
 
      exitcode = EX_OSERR;
2038
 
      goto end;
2039
 
    }
2040
 
  }
 
1049
    perror("sigaddset");
 
1050
    exitcode = EXIT_FAILURE;
 
1051
    goto end;
 
1052
  }
 
1053
  ret = sigaction(SIGTERM, &sigterm_action, &old_sigterm_action);
 
1054
  if(ret == -1){
 
1055
    perror("sigaction");
 
1056
    exitcode = EXIT_FAILURE;
 
1057
    goto end;
 
1058
  }  
2041
1059
  
2042
1060
  /* If the interface is down, bring it up */
2043
 
  if((interface[0] != '\0') and (strcmp(interface, "none") != 0)){
2044
 
    ret = bring_up_interface(interface, delay);
2045
 
    if(ret){
2046
 
      errno = ret;
2047
 
      perror_plus("Failed to bring up interface");
2048
 
    }
2049
 
  }
2050
 
  
2051
 
  if(quit_now){
2052
 
    goto end;
 
1061
  if(interface[0] != '\0'){
 
1062
#ifdef __linux__
 
1063
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1064
       messages to mess up the prompt */
 
1065
    ret = klogctl(8, NULL, 5);
 
1066
    bool restore_loglevel = true;
 
1067
    if(ret == -1){
 
1068
      restore_loglevel = false;
 
1069
      perror("klogctl");
 
1070
    }
 
1071
#endif  /* __linux__ */
 
1072
    
 
1073
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1074
    if(sd < 0){
 
1075
      perror("socket");
 
1076
      exitcode = EXIT_FAILURE;
 
1077
#ifdef __linux__
 
1078
      if(restore_loglevel){
 
1079
        ret = klogctl(7, NULL, 0);
 
1080
        if(ret == -1){
 
1081
          perror("klogctl");
 
1082
        }
 
1083
      }
 
1084
#endif  /* __linux__ */
 
1085
      goto end;
 
1086
    }
 
1087
    strcpy(network.ifr_name, interface);
 
1088
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1089
    if(ret == -1){
 
1090
      perror("ioctl SIOCGIFFLAGS");
 
1091
#ifdef __linux__
 
1092
      if(restore_loglevel){
 
1093
        ret = klogctl(7, NULL, 0);
 
1094
        if(ret == -1){
 
1095
          perror("klogctl");
 
1096
        }
 
1097
      }
 
1098
#endif  /* __linux__ */
 
1099
      exitcode = EXIT_FAILURE;
 
1100
      goto end;
 
1101
    }
 
1102
    if((network.ifr_flags & IFF_UP) == 0){
 
1103
      network.ifr_flags |= IFF_UP;
 
1104
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1105
      if(ret == -1){
 
1106
        perror("ioctl SIOCSIFFLAGS");
 
1107
        exitcode = EXIT_FAILURE;
 
1108
#ifdef __linux__
 
1109
        if(restore_loglevel){
 
1110
          ret = klogctl(7, NULL, 0);
 
1111
          if(ret == -1){
 
1112
            perror("klogctl");
 
1113
          }
 
1114
        }
 
1115
#endif  /* __linux__ */
 
1116
        goto end;
 
1117
      }
 
1118
    }
 
1119
    /* sleep checking until interface is running */
 
1120
    for(int i=0; i < delay * 4; i++){
 
1121
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1122
      if(ret == -1){
 
1123
        perror("ioctl SIOCGIFFLAGS");
 
1124
      } else if(network.ifr_flags & IFF_RUNNING){
 
1125
        break;
 
1126
      }
 
1127
      struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1128
      ret = nanosleep(&sleeptime, NULL);
 
1129
      if(ret == -1 and errno != EINTR){
 
1130
        perror("nanosleep");
 
1131
      }
 
1132
    }
 
1133
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1134
    if(ret == -1){
 
1135
      perror("close");
 
1136
    }
 
1137
#ifdef __linux__
 
1138
    if(restore_loglevel){
 
1139
      /* Restores kernel loglevel to default */
 
1140
      ret = klogctl(7, NULL, 0);
 
1141
      if(ret == -1){
 
1142
        perror("klogctl");
 
1143
      }
 
1144
    }
 
1145
#endif  /* __linux__ */
 
1146
  }
 
1147
  
 
1148
  uid = getuid();
 
1149
  gid = getgid();
 
1150
  
 
1151
  errno = 0;
 
1152
  setgid(gid);
 
1153
  if(ret == -1){
 
1154
    perror("setgid");
 
1155
  }
 
1156
  
 
1157
  ret = setuid(uid);
 
1158
  if(ret == -1){
 
1159
    perror("setuid");
2053
1160
  }
2054
1161
  
2055
1162
  ret = init_gnutls_global(pubkey, seckey);
2056
1163
  if(ret == -1){
2057
 
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2058
 
    exitcode = EX_UNAVAILABLE;
 
1164
    fprintf(stderr, "init_gnutls_global failed\n");
 
1165
    exitcode = EXIT_FAILURE;
2059
1166
    goto end;
2060
1167
  } else {
2061
1168
    gnutls_initialized = true;
2062
1169
  }
2063
1170
  
2064
 
  if(quit_now){
2065
 
    goto end;
2066
 
  }
2067
 
  
2068
1171
  if(mkdtemp(tempdir) == NULL){
2069
 
    perror_plus("mkdtemp");
 
1172
    perror("mkdtemp");
2070
1173
    goto end;
2071
1174
  }
2072
1175
  tempdir_created = true;
2073
1176
  
2074
 
  if(quit_now){
2075
 
    goto end;
2076
 
  }
2077
 
  
2078
1177
  if(not init_gpgme(pubkey, seckey, tempdir)){
2079
 
    fprintf_plus(stderr, "init_gpgme failed\n");
2080
 
    exitcode = EX_UNAVAILABLE;
 
1178
    fprintf(stderr, "init_gpgme failed\n");
 
1179
    exitcode = EXIT_FAILURE;
2081
1180
    goto end;
2082
1181
  } else {
2083
1182
    gpgme_initialized = true;
2084
1183
  }
2085
1184
  
2086
 
  if(quit_now){
2087
 
    goto end;
 
1185
  if(interface[0] != '\0'){
 
1186
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1187
    if(if_index == 0){
 
1188
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1189
      exitcode = EXIT_FAILURE;
 
1190
      goto end;
 
1191
    }
2088
1192
  }
2089
1193
  
2090
1194
  if(connect_to != NULL){
2091
1195
    /* Connect directly, do not use Zeroconf */
2092
1196
    /* (Mainly meant for debugging) */
2093
1197
    char *address = strrchr(connect_to, ':');
2094
 
    
2095
1198
    if(address == NULL){
2096
 
      fprintf_plus(stderr, "No colon in address\n");
2097
 
      exitcode = EX_USAGE;
2098
 
      goto end;
2099
 
    }
2100
 
    
2101
 
    if(quit_now){
2102
 
      goto end;
2103
 
    }
2104
 
    
 
1199
      fprintf(stderr, "No colon in address\n");
 
1200
      exitcode = EXIT_FAILURE;
 
1201
      goto end;
 
1202
    }
2105
1203
    uint16_t port;
2106
1204
    errno = 0;
2107
1205
    tmpmax = strtoimax(address+1, &tmp, 10);
2108
1206
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2109
1207
       or tmpmax != (uint16_t)tmpmax){
2110
 
      fprintf_plus(stderr, "Bad port number\n");
2111
 
      exitcode = EX_USAGE;
2112
 
      goto end;
2113
 
    }
2114
 
  
2115
 
    if(quit_now){
2116
 
      goto end;
2117
 
    }
2118
 
    
 
1208
      fprintf(stderr, "Bad port number\n");
 
1209
      exitcode = EXIT_FAILURE;
 
1210
      goto end;
 
1211
    }
2119
1212
    port = (uint16_t)tmpmax;
2120
1213
    *address = '\0';
 
1214
    address = connect_to;
2121
1215
    /* Colon in address indicates IPv6 */
2122
1216
    int af;
2123
 
    if(strchr(connect_to, ':') != NULL){
 
1217
    if(strchr(address, ':') != NULL){
2124
1218
      af = AF_INET6;
2125
 
      /* Accept [] around IPv6 address - see RFC 5952 */
2126
 
      if(connect_to[0] == '[' and address[-1] == ']')
2127
 
        {
2128
 
          connect_to++;
2129
 
          address[-1] = '\0';
2130
 
        }
2131
1219
    } else {
2132
1220
      af = AF_INET;
2133
1221
    }
2134
 
    address = connect_to;
2135
 
    
2136
 
    if(quit_now){
2137
 
      goto end;
2138
 
    }
2139
 
    
2140
 
    while(not quit_now){
2141
 
      ret = start_mandos_communication(address, port, if_index, af);
2142
 
      if(quit_now or ret == 0){
2143
 
        break;
2144
 
      }
2145
 
      if(debug){
2146
 
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2147
 
                     (int)retry_interval);
2148
 
      }
2149
 
      sleep((int)retry_interval);
2150
 
    }
2151
 
    
2152
 
    if (not quit_now){
 
1222
    ret = start_mandos_communication(address, port, if_index, af);
 
1223
    if(ret < 0){
 
1224
      exitcode = EXIT_FAILURE;
 
1225
    } else {
2153
1226
      exitcode = EXIT_SUCCESS;
2154
1227
    }
 
1228
    goto end;
 
1229
  }
2155
1230
    
2156
 
    goto end;
2157
 
  }
2158
 
  
2159
 
  if(quit_now){
2160
 
    goto end;
2161
 
  }
2162
 
  
2163
1231
  {
2164
1232
    AvahiServerConfig config;
2165
1233
    /* Do not publish any local Zeroconf records */
2180
1248
  
2181
1249
  /* Check if creating the Avahi server object succeeded */
2182
1250
  if(mc.server == NULL){
2183
 
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2184
 
                 avahi_strerror(error));
2185
 
    exitcode = EX_UNAVAILABLE;
2186
 
    goto end;
2187
 
  }
2188
 
  
2189
 
  if(quit_now){
 
1251
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
1252
            avahi_strerror(error));
 
1253
    exitcode = EXIT_FAILURE;
2190
1254
    goto end;
2191
1255
  }
2192
1256
  
2195
1259
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2196
1260
                                   NULL, 0, browse_callback, NULL);
2197
1261
  if(sb == NULL){
2198
 
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2199
 
                 avahi_strerror(avahi_server_errno(mc.server)));
2200
 
    exitcode = EX_UNAVAILABLE;
2201
 
    goto end;
2202
 
  }
2203
 
  
2204
 
  if(quit_now){
 
1262
    fprintf(stderr, "Failed to create service browser: %s\n",
 
1263
            avahi_strerror(avahi_server_errno(mc.server)));
 
1264
    exitcode = EXIT_FAILURE;
2205
1265
    goto end;
2206
1266
  }
2207
1267
  
2208
1268
  /* Run the main loop */
2209
1269
  
2210
1270
  if(debug){
2211
 
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2212
 
  }
2213
 
 
2214
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
2215
 
                                (int)(retry_interval * 1000));
2216
 
  if(debug){
2217
 
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2218
 
                 (ret == 0) ? "successfully" : "with error");
2219
 
  }
 
1271
    fprintf(stderr, "Starting Avahi loop search\n");
 
1272
  }
 
1273
  
 
1274
  avahi_simple_poll_loop(mc.simple_poll);
2220
1275
  
2221
1276
 end:
2222
1277
  
2223
1278
  if(debug){
2224
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
1279
    fprintf(stderr, "%s exiting\n", argv[0]);
2225
1280
  }
2226
1281
  
2227
1282
  /* Cleanup things */
2244
1299
    gpgme_release(mc.ctx);
2245
1300
  }
2246
1301
  
2247
 
  /* Cleans up the circular linked list of Mandos servers the client
2248
 
     has seen */
2249
 
  if(mc.current_server != NULL){
2250
 
    mc.current_server->prev->next = NULL;
2251
 
    while(mc.current_server != NULL){
2252
 
      server *next = mc.current_server->next;
2253
 
      free(mc.current_server);
2254
 
      mc.current_server = next;
2255
 
    }
2256
 
  }
2257
 
  
2258
 
  /* Run network hooks */
2259
 
  run_network_hooks("stop", interface, delay);
2260
 
  
2261
 
  /* Re-raise priviliges */
2262
 
  {
2263
 
    raise_privileges();
2264
 
    
2265
 
    /* Take down the network interface */
2266
 
    if(take_down_interface and geteuid() == 0){
2267
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2268
 
      if(ret == -1){
2269
 
        perror_plus("ioctl SIOCGIFFLAGS");
2270
 
      } else if(network.ifr_flags & IFF_UP){
2271
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2272
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2273
 
        if(ret == -1){
2274
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
2275
 
        }
2276
 
      }
2277
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2278
 
      if(ret == -1){
2279
 
        perror_plus("close");
2280
 
      }
2281
 
    }
2282
 
  }
2283
 
  /* Lower privileges permanently */
2284
 
  errno = 0;
2285
 
  ret = setuid(uid);
2286
 
  if(ret == -1){
2287
 
    perror_plus("setuid");
2288
 
  }
2289
 
  
2290
 
  /* Removes the GPGME temp directory and all files inside */
 
1302
  /* Removes the temp directory used by GPGME */
2291
1303
  if(tempdir_created){
2292
 
    struct dirent **direntries = NULL;
2293
 
    struct dirent *direntry = NULL;
2294
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
2295
 
                             alphasort);
2296
 
    if (numentries > 0){
2297
 
      for(int i = 0; i < numentries; i++){
2298
 
        direntry = direntries[i];
 
1304
    DIR *d;
 
1305
    struct dirent *direntry;
 
1306
    d = opendir(tempdir);
 
1307
    if(d == NULL){
 
1308
      if(errno != ENOENT){
 
1309
        perror("opendir");
 
1310
      }
 
1311
    } else {
 
1312
      while(true){
 
1313
        direntry = readdir(d);
 
1314
        if(direntry == NULL){
 
1315
          break;
 
1316
        }
 
1317
        /* Skip "." and ".." */
 
1318
        if(direntry->d_name[0] == '.'
 
1319
           and (direntry->d_name[1] == '\0'
 
1320
                or (direntry->d_name[1] == '.'
 
1321
                    and direntry->d_name[2] == '\0'))){
 
1322
          continue;
 
1323
        }
2299
1324
        char *fullname = NULL;
2300
1325
        ret = asprintf(&fullname, "%s/%s", tempdir,
2301
1326
                       direntry->d_name);
2302
1327
        if(ret < 0){
2303
 
          perror_plus("asprintf");
 
1328
          perror("asprintf");
2304
1329
          continue;
2305
1330
        }
2306
1331
        ret = remove(fullname);
2307
1332
        if(ret == -1){
2308
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2309
 
                       strerror(errno));
 
1333
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
1334
                  strerror(errno));
2310
1335
        }
2311
1336
        free(fullname);
2312
1337
      }
2313
 
    }
2314
 
 
2315
 
    /* need to clean even if 0 because man page doesn't specify */
2316
 
    free(direntries);
2317
 
    if (numentries == -1){
2318
 
      perror_plus("scandir");
 
1338
      closedir(d);
2319
1339
    }
2320
1340
    ret = rmdir(tempdir);
2321
1341
    if(ret == -1 and errno != ENOENT){
2322
 
      perror_plus("rmdir");
2323
 
    }
2324
 
  }
2325
 
  
2326
 
  if(quit_now){
2327
 
    sigemptyset(&old_sigterm_action.sa_mask);
2328
 
    old_sigterm_action.sa_handler = SIG_DFL;
2329
 
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
2330
 
                                            &old_sigterm_action,
2331
 
                                            NULL));
2332
 
    if(ret == -1){
2333
 
      perror_plus("sigaction");
2334
 
    }
2335
 
    do {
2336
 
      ret = raise(signal_received);
2337
 
    } while(ret != 0 and errno == EINTR);
2338
 
    if(ret != 0){
2339
 
      perror_plus("raise");
2340
 
      abort();
2341
 
    }
2342
 
    TEMP_FAILURE_RETRY(pause());
 
1342
      perror("rmdir");
 
1343
    }
2343
1344
  }
2344
1345
  
2345
1346
  return exitcode;