/mandos/release

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

« back to all changes in this revision

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

* plugins.d/mandos-client.c: Prefix all printouts with "Mandos plugin
                             mandos-client: ".
* plugins.d/mandos-client.c (main): Wait for network hooks and check
                                    the completion status.

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,2009 Teddy Hogeborn
13
 
 * Copyright © 2008,2009 Björn Påhlsson
 
12
 * Copyright © 2008-2011 Teddy Hogeborn
 
13
 * Copyright © 2008-2011 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@fukt.bsnet.se>.
 
29
 * Contact the authors at <mandos@recompile.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
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() */
 
56
#include <sys/stat.h>           /* open(), S_ISREG */
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
 
#include <time.h>               /* nanosleep(), time() */
 
65
#include <errno.h>              /* perror(), errno,
 
66
                                   program_invocation_short_name */
 
67
#include <time.h>               /* nanosleep(), time(), sleep() */
67
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
68
69
                                   SIOCSIFFLAGS, if_indextoname(),
69
70
                                   if_nametoindex(), IF_NAMESIZE */
73
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
74
75
                                   getuid(), getgid(), seteuid(),
75
76
                                   setgid(), pause() */
76
 
#include <arpa/inet.h>          /* inet_pton(), htons */
 
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
77
78
#include <iso646.h>             /* not, or, and */
78
79
#include <argp.h>               /* struct argp_option, error_t, struct
79
80
                                   argp_state, struct argp,
84
85
                                   raise() */
85
86
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
86
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
 
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
 
89
                                   WEXITSTATUS(), WTERMSIG() */
87
90
 
88
91
#ifdef __linux__
89
92
#include <sys/klog.h>           /* klogctl() */
122
125
#define PATHDIR "/conf/conf.d/mandos"
123
126
#define SECKEY "seckey.txt"
124
127
#define PUBKEY "pubkey.txt"
 
128
#define HOOKDIR "/lib/mandos/network-hooks.d"
125
129
 
126
130
bool debug = false;
127
131
static const char mandos_protocol_version[] = "1";
128
132
const char *argp_program_version = "mandos-client " VERSION;
129
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
133
const char *argp_program_bug_address = "<mandos@recompile.se>";
 
134
static const char sys_class_net[] = "/sys/class/net";
 
135
char *connect_to = NULL;
 
136
 
 
137
/* Doubly linked list that need to be circularly linked when used */
 
138
typedef struct server{
 
139
  const char *ip;
 
140
  uint16_t port;
 
141
  AvahiIfIndex if_index;
 
142
  int af;
 
143
  struct timespec last_seen;
 
144
  struct server *next;
 
145
  struct server *prev;
 
146
} server;
130
147
 
131
148
/* Used for passing in values through the Avahi callback functions */
132
149
typedef struct {
137
154
  gnutls_dh_params_t dh_params;
138
155
  const char *priority;
139
156
  gpgme_ctx_t ctx;
 
157
  server *current_server;
140
158
} mandos_context;
141
159
 
142
160
/* global context so signal handler can reach it*/
143
161
mandos_context mc = { .simple_poll = NULL, .server = NULL,
144
162
                      .dh_bits = 1024, .priority = "SECURE256"
145
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
163
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
164
                      .current_server = NULL };
146
165
 
147
166
sig_atomic_t quit_now = 0;
148
167
int signal_received = 0;
149
168
 
 
169
/* Function to use when printing errors */
 
170
void perror_plus(const char *print_text){
 
171
  fprintf(stderr, "Mandos plugin %s: ",
 
172
          program_invocation_short_name);
 
173
  perror(print_text);
 
174
}
 
175
 
150
176
/*
151
177
 * Make additional room in "buffer" for at least BUFFER_SIZE more
152
178
 * bytes. "buffer_capacity" is how much is currently allocated,
164
190
  return buffer_capacity;
165
191
}
166
192
 
 
193
/* Add server to set of servers to retry periodically */
 
194
int add_server(const char *ip, uint16_t port,
 
195
                 AvahiIfIndex if_index,
 
196
                 int af){
 
197
  int ret;
 
198
  server *new_server = malloc(sizeof(server));
 
199
  if(new_server == NULL){
 
200
    perror_plus("malloc");
 
201
    return -1;
 
202
  }
 
203
  *new_server = (server){ .ip = strdup(ip),
 
204
                         .port = port,
 
205
                         .if_index = if_index,
 
206
                         .af = af };
 
207
  if(new_server->ip == NULL){
 
208
    perror_plus("strdup");
 
209
    return -1;
 
210
  }
 
211
  /* Special case of first server */
 
212
  if (mc.current_server == NULL){
 
213
    new_server->next = new_server;
 
214
    new_server->prev = new_server;
 
215
    mc.current_server = new_server;
 
216
  /* Place the new server last in the list */
 
217
  } else {
 
218
    new_server->next = mc.current_server;
 
219
    new_server->prev = mc.current_server->prev;
 
220
    new_server->prev->next = new_server;
 
221
    mc.current_server->prev = new_server;
 
222
  }
 
223
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
224
  if(ret == -1){
 
225
    perror_plus("clock_gettime");
 
226
    return -1;
 
227
  }
 
228
  return 0;
 
229
}
 
230
 
167
231
/* 
168
232
 * Initialize GPGME.
169
233
 */
183
247
    
184
248
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
185
249
    if(fd == -1){
186
 
      perror("open");
 
250
      perror_plus("open");
187
251
      return false;
188
252
    }
189
253
    
190
254
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
191
255
    if(rc != GPG_ERR_NO_ERROR){
192
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
256
      fprintf(stderr, "Mandos plugin mandos-client: "
 
257
              "bad gpgme_data_new_from_fd: %s: %s\n",
193
258
              gpgme_strsource(rc), gpgme_strerror(rc));
194
259
      return false;
195
260
    }
196
261
    
197
262
    rc = gpgme_op_import(mc.ctx, pgp_data);
198
263
    if(rc != GPG_ERR_NO_ERROR){
199
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
264
      fprintf(stderr, "Mandos plugin mandos-client: "
 
265
              "bad gpgme_op_import: %s: %s\n",
200
266
              gpgme_strsource(rc), gpgme_strerror(rc));
201
267
      return false;
202
268
    }
203
269
    
204
270
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
205
271
    if(ret == -1){
206
 
      perror("close");
 
272
      perror_plus("close");
207
273
    }
208
274
    gpgme_data_release(pgp_data);
209
275
    return true;
210
276
  }
211
277
  
212
278
  if(debug){
213
 
    fprintf(stderr, "Initializing GPGME\n");
 
279
    fprintf(stderr, "Mandos plugin mandos-client: "
 
280
            "Initializing GPGME\n");
214
281
  }
215
282
  
216
283
  /* Init GPGME */
217
284
  gpgme_check_version(NULL);
218
285
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
219
286
  if(rc != GPG_ERR_NO_ERROR){
220
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
287
    fprintf(stderr, "Mandos plugin mandos-client: "
 
288
            "bad gpgme_engine_check_version: %s: %s\n",
221
289
            gpgme_strsource(rc), gpgme_strerror(rc));
222
290
    return false;
223
291
  }
224
292
  
225
 
    /* Set GPGME home directory for the OpenPGP engine only */
 
293
  /* Set GPGME home directory for the OpenPGP engine only */
226
294
  rc = gpgme_get_engine_info(&engine_info);
227
295
  if(rc != GPG_ERR_NO_ERROR){
228
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
296
    fprintf(stderr, "Mandos plugin mandos-client: "
 
297
            "bad gpgme_get_engine_info: %s: %s\n",
229
298
            gpgme_strsource(rc), gpgme_strerror(rc));
230
299
    return false;
231
300
  }
238
307
    engine_info = engine_info->next;
239
308
  }
240
309
  if(engine_info == NULL){
241
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
310
    fprintf(stderr, "Mandos plugin mandos-client: "
 
311
            "Could not set GPGME home dir to %s\n", tempdir);
242
312
    return false;
243
313
  }
244
314
  
245
315
  /* Create new GPGME "context" */
246
316
  rc = gpgme_new(&(mc.ctx));
247
317
  if(rc != GPG_ERR_NO_ERROR){
248
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
249
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
318
    fprintf(stderr, "Mandos plugin mandos-client: "
 
319
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
320
            gpgme_strerror(rc));
250
321
    return false;
251
322
  }
252
323
  
271
342
  ssize_t plaintext_length = 0;
272
343
  
273
344
  if(debug){
274
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
345
    fprintf(stderr, "Mandos plugin mandos-client: "
 
346
            "Trying to decrypt OpenPGP data\n");
275
347
  }
276
348
  
277
349
  /* Create new GPGME data buffer from memory cryptotext */
278
350
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
279
351
                               0);
280
352
  if(rc != GPG_ERR_NO_ERROR){
281
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
353
    fprintf(stderr, "Mandos plugin mandos-client: "
 
354
            "bad gpgme_data_new_from_mem: %s: %s\n",
282
355
            gpgme_strsource(rc), gpgme_strerror(rc));
283
356
    return -1;
284
357
  }
286
359
  /* Create new empty GPGME data buffer for the plaintext */
287
360
  rc = gpgme_data_new(&dh_plain);
288
361
  if(rc != GPG_ERR_NO_ERROR){
289
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
362
    fprintf(stderr, "Mandos plugin mandos-client: "
 
363
            "bad gpgme_data_new: %s: %s\n",
290
364
            gpgme_strsource(rc), gpgme_strerror(rc));
291
365
    gpgme_data_release(dh_crypto);
292
366
    return -1;
296
370
     data buffer */
297
371
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
298
372
  if(rc != GPG_ERR_NO_ERROR){
299
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
373
    fprintf(stderr, "Mandos plugin mandos-client: "
 
374
            "bad gpgme_op_decrypt: %s: %s\n",
300
375
            gpgme_strsource(rc), gpgme_strerror(rc));
301
376
    plaintext_length = -1;
302
377
    if(debug){
303
378
      gpgme_decrypt_result_t result;
304
379
      result = gpgme_op_decrypt_result(mc.ctx);
305
380
      if(result == NULL){
306
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
381
        fprintf(stderr, "Mandos plugin mandos-client: "
 
382
                "gpgme_op_decrypt_result failed\n");
307
383
      } else {
308
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
384
        fprintf(stderr, "Mandos plugin mandos-client: "
 
385
                "Unsupported algorithm: %s\n",
309
386
                result->unsupported_algorithm);
310
 
        fprintf(stderr, "Wrong key usage: %u\n",
 
387
        fprintf(stderr, "Mandos plugin mandos-client: "
 
388
                "Wrong key usage: %u\n",
311
389
                result->wrong_key_usage);
312
390
        if(result->file_name != NULL){
313
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
391
          fprintf(stderr, "Mandos plugin mandos-client: "
 
392
                  "File name: %s\n", result->file_name);
314
393
        }
315
394
        gpgme_recipient_t recipient;
316
395
        recipient = result->recipients;
317
396
        while(recipient != NULL){
318
 
          fprintf(stderr, "Public key algorithm: %s\n",
 
397
          fprintf(stderr, "Mandos plugin mandos-client: "
 
398
                  "Public key algorithm: %s\n",
319
399
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
320
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
321
 
          fprintf(stderr, "Secret key available: %s\n",
 
400
          fprintf(stderr, "Mandos plugin mandos-client: "
 
401
                  "Key ID: %s\n", recipient->keyid);
 
402
          fprintf(stderr, "Mandos plugin mandos-client: "
 
403
                  "Secret key available: %s\n",
322
404
                  recipient->status == GPG_ERR_NO_SECKEY
323
405
                  ? "No" : "Yes");
324
406
          recipient = recipient->next;
329
411
  }
330
412
  
331
413
  if(debug){
332
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
414
    fprintf(stderr, "Mandos plugin mandos-client: "
 
415
            "Decryption of OpenPGP data succeeded\n");
333
416
  }
334
417
  
335
418
  /* Seek back to the beginning of the GPGME plaintext data buffer */
336
419
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
337
 
    perror("gpgme_data_seek");
 
420
    perror_plus("gpgme_data_seek");
338
421
    plaintext_length = -1;
339
422
    goto decrypt_end;
340
423
  }
345
428
                                      (size_t)plaintext_length,
346
429
                                      plaintext_capacity);
347
430
    if(plaintext_capacity == 0){
348
 
        perror("incbuffer");
 
431
        perror_plus("incbuffer");
349
432
        plaintext_length = -1;
350
433
        goto decrypt_end;
351
434
    }
358
441
      break;
359
442
    }
360
443
    if(ret < 0){
361
 
      perror("gpgme_data_read");
 
444
      perror_plus("gpgme_data_read");
362
445
      plaintext_length = -1;
363
446
      goto decrypt_end;
364
447
    }
366
449
  }
367
450
  
368
451
  if(debug){
369
 
    fprintf(stderr, "Decrypted password is: ");
 
452
    fprintf(stderr, "Mandos plugin mandos-client: "
 
453
            "Decrypted password is: ");
370
454
    for(ssize_t i = 0; i < plaintext_length; i++){
371
455
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
372
456
    }
394
478
/* GnuTLS log function callback */
395
479
static void debuggnutls(__attribute__((unused)) int level,
396
480
                        const char* string){
397
 
  fprintf(stderr, "GnuTLS: %s", string);
 
481
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
398
482
}
399
483
 
400
484
static int init_gnutls_global(const char *pubkeyfilename,
402
486
  int ret;
403
487
  
404
488
  if(debug){
405
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
489
    fprintf(stderr, "Mandos plugin mandos-client: "
 
490
            "Initializing GnuTLS\n");
406
491
  }
407
492
  
408
493
  ret = gnutls_global_init();
409
494
  if(ret != GNUTLS_E_SUCCESS){
410
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
411
 
            safer_gnutls_strerror(ret));
 
495
    fprintf(stderr, "Mandos plugin mandos-client: "
 
496
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
412
497
    return -1;
413
498
  }
414
499
  
421
506
  }
422
507
  
423
508
  /* OpenPGP credentials */
424
 
  gnutls_certificate_allocate_credentials(&mc.cred);
 
509
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
425
510
  if(ret != GNUTLS_E_SUCCESS){
426
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
427
 
                                                    from
428
 
                                                    -Wunreachable-code
429
 
                                                 */
430
 
            safer_gnutls_strerror(ret));
 
511
    fprintf(stderr, "Mandos plugin mandos-client: "
 
512
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
431
513
    gnutls_global_deinit();
432
514
    return -1;
433
515
  }
434
516
  
435
517
  if(debug){
436
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
518
    fprintf(stderr, "Mandos plugin mandos-client: "
 
519
            "Attempting to use OpenPGP public key %s and"
437
520
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
438
521
            seckeyfilename);
439
522
  }
443
526
     GNUTLS_OPENPGP_FMT_BASE64);
444
527
  if(ret != GNUTLS_E_SUCCESS){
445
528
    fprintf(stderr,
 
529
            "Mandos plugin mandos-client: "
446
530
            "Error[%d] while reading the OpenPGP key pair ('%s',"
447
531
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
448
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
449
 
            safer_gnutls_strerror(ret));
 
532
    fprintf(stderr, "Mandos plugin mandos-client: "
 
533
            "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
450
534
    goto globalfail;
451
535
  }
452
536
  
453
537
  /* GnuTLS server initialization */
454
538
  ret = gnutls_dh_params_init(&mc.dh_params);
455
539
  if(ret != GNUTLS_E_SUCCESS){
456
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
540
    fprintf(stderr, "Mandos plugin mandos-client: "
 
541
            "Error in GnuTLS DH parameter initialization:"
457
542
            " %s\n", safer_gnutls_strerror(ret));
458
543
    goto globalfail;
459
544
  }
460
545
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
461
546
  if(ret != GNUTLS_E_SUCCESS){
462
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
547
    fprintf(stderr, "Mandos plugin mandos-client: "
 
548
            "Error in GnuTLS prime generation: %s\n",
463
549
            safer_gnutls_strerror(ret));
464
550
    goto globalfail;
465
551
  }
486
572
    }
487
573
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
488
574
  if(ret != GNUTLS_E_SUCCESS){
489
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
575
    fprintf(stderr, "Mandos plugin mandos-client: "
 
576
            "Error in GnuTLS session initialization: %s\n",
490
577
            safer_gnutls_strerror(ret));
491
578
  }
492
579
  
500
587
      }
501
588
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
502
589
    if(ret != GNUTLS_E_SUCCESS){
503
 
      fprintf(stderr, "Syntax error at: %s\n", err);
504
 
      fprintf(stderr, "GnuTLS error: %s\n",
505
 
              safer_gnutls_strerror(ret));
 
590
      fprintf(stderr, "Mandos plugin mandos-client: "
 
591
              "Syntax error at: %s\n", err);
 
592
      fprintf(stderr, "Mandos plugin mandos-client: "
 
593
              "GnuTLS error: %s\n", safer_gnutls_strerror(ret));
506
594
      gnutls_deinit(*session);
507
595
      return -1;
508
596
    }
517
605
    }
518
606
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
519
607
  if(ret != GNUTLS_E_SUCCESS){
520
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
608
    fprintf(stderr, "Mandos plugin mandos-client: "
 
609
            "Error setting GnuTLS credentials: %s\n",
521
610
            safer_gnutls_strerror(ret));
522
611
    gnutls_deinit(*session);
523
612
    return -1;
569
658
    pf = PF_INET;
570
659
    break;
571
660
  default:
572
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
661
    fprintf(stderr, "Mandos plugin mandos-client: "
 
662
            "Bad address family: %d\n", af);
573
663
    errno = EINVAL;
574
664
    return -1;
575
665
  }
580
670
  }
581
671
  
582
672
  if(debug){
583
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
673
    fprintf(stderr, "Mandos plugin mandos-client: "
 
674
            "Setting up a TCP connection to %s, port %" PRIu16
584
675
            "\n", ip, port);
585
676
  }
586
677
  
587
678
  tcp_sd = socket(pf, SOCK_STREAM, 0);
588
679
  if(tcp_sd < 0){
589
680
    int e = errno;
590
 
    perror("socket");
 
681
    perror_plus("socket");
591
682
    errno = e;
592
683
    goto mandos_end;
593
684
  }
607
698
  }
608
699
  if(ret < 0 ){
609
700
    int e = errno;
610
 
    perror("inet_pton");
 
701
    perror_plus("inet_pton");
611
702
    errno = e;
612
703
    goto mandos_end;
613
704
  }
614
705
  if(ret == 0){
615
706
    int e = errno;
616
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
707
    fprintf(stderr, "Mandos plugin mandos-client: "
 
708
            "Bad address: %s\n", ip);
617
709
    errno = e;
618
710
    goto mandos_end;
619
711
  }
626
718
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
627
719
                              -Wunreachable-code*/
628
720
      if(if_index == AVAHI_IF_UNSPEC){
629
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
721
        fprintf(stderr, "Mandos plugin mandos-client: "
 
722
                "An IPv6 link-local address is incomplete"
630
723
                " without a network interface\n");
631
724
        errno = EINVAL;
632
725
        goto mandos_end;
649
742
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
650
743
      char interface[IF_NAMESIZE];
651
744
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
652
 
        perror("if_indextoname");
 
745
        perror_plus("if_indextoname");
653
746
      } else {
654
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
747
        fprintf(stderr, "Mandos plugin mandos-client: "
 
748
                "Connection to: %s%%%s, port %" PRIu16 "\n",
655
749
                ip, interface, port);
656
750
      }
657
751
    } else {
658
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
659
 
              port);
 
752
      fprintf(stderr, "Mandos plugin mandos-client: "
 
753
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
660
754
    }
661
755
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
662
756
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
669
763
                        sizeof(addrstr));
670
764
    }
671
765
    if(pcret == NULL){
672
 
      perror("inet_ntop");
 
766
      perror_plus("inet_ntop");
673
767
    } else {
674
768
      if(strcmp(addrstr, ip) != 0){
675
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
769
        fprintf(stderr, "Mandos plugin mandos-client: "
 
770
                "Canonical address form: %s\n", addrstr);
676
771
      }
677
772
    }
678
773
  }
688
783
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
689
784
  }
690
785
  if(ret < 0){
691
 
    int e = errno;
692
 
    perror("connect");
693
 
    errno = e;
 
786
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
787
      int e = errno;
 
788
      perror_plus("connect");
 
789
      errno = e;
 
790
    }
694
791
    goto mandos_end;
695
792
  }
696
793
  
707
804
                                   out_size - written));
708
805
    if(ret == -1){
709
806
      int e = errno;
710
 
      perror("write");
 
807
      perror_plus("write");
711
808
      errno = e;
712
809
      goto mandos_end;
713
810
    }
730
827
  }
731
828
  
732
829
  if(debug){
733
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
830
    fprintf(stderr, "Mandos plugin mandos-client: "
 
831
            "Establishing TLS session with %s\n", ip);
734
832
  }
735
833
  
736
834
  if(quit_now){
738
836
    goto mandos_end;
739
837
  }
740
838
  
 
839
  /* Spurious warning from -Wint-to-pointer-cast */
741
840
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
742
841
  
743
842
  if(quit_now){
755
854
  
756
855
  if(ret != GNUTLS_E_SUCCESS){
757
856
    if(debug){
758
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
857
      fprintf(stderr, "Mandos plugin mandos-client: "
 
858
              "*** GnuTLS Handshake failed ***\n");
759
859
      gnutls_perror(ret);
760
860
    }
761
861
    errno = EPROTO;
765
865
  /* Read OpenPGP packet that contains the wanted password */
766
866
  
767
867
  if(debug){
768
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
769
 
            ip);
 
868
    fprintf(stderr, "Mandos plugin mandos-client: "
 
869
            "Retrieving OpenPGP encrypted password from %s\n", ip);
770
870
  }
771
871
  
772
872
  while(true){
780
880
                                   buffer_capacity);
781
881
    if(buffer_capacity == 0){
782
882
      int e = errno;
783
 
      perror("incbuffer");
 
883
      perror_plus("incbuffer");
784
884
      errno = e;
785
885
      goto mandos_end;
786
886
    }
810
910
          }
811
911
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
812
912
        if(ret < 0){
813
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
913
          fprintf(stderr, "Mandos plugin mandos-client: "
 
914
                  "*** GnuTLS Re-handshake failed ***\n");
814
915
          gnutls_perror(ret);
815
916
          errno = EPROTO;
816
917
          goto mandos_end;
817
918
        }
818
919
        break;
819
920
      default:
820
 
        fprintf(stderr, "Unknown error while reading data from"
 
921
        fprintf(stderr, "Mandos plugin mandos-client: "
 
922
                "Unknown error while reading data from"
821
923
                " encrypted session with Mandos server\n");
822
924
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
823
925
        errno = EIO;
829
931
  }
830
932
  
831
933
  if(debug){
832
 
    fprintf(stderr, "Closing TLS session\n");
 
934
    fprintf(stderr, "Mandos plugin mandos-client: "
 
935
            "Closing TLS session\n");
833
936
  }
834
937
  
835
938
  if(quit_now){
865
968
        if(ret == 0 and ferror(stdout)){
866
969
          int e = errno;
867
970
          if(debug){
868
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
971
            fprintf(stderr, "Mandos plugin mandos-client: "
 
972
                    "Error writing encrypted data: %s\n",
869
973
                    strerror(errno));
870
974
          }
871
975
          errno = e;
891
995
      if(e == 0){
892
996
        e = errno;
893
997
      }
894
 
      perror("close");
 
998
      perror_plus("close");
895
999
    }
896
1000
    gnutls_deinit(session);
 
1001
    errno = e;
897
1002
    if(quit_now){
898
 
      e = EINTR;
 
1003
      errno = EINTR;
899
1004
      retval = -1;
900
1005
    }
901
 
    errno = e;
902
1006
  }
903
1007
  return retval;
904
1008
}
929
1033
  switch(event){
930
1034
  default:
931
1035
  case AVAHI_RESOLVER_FAILURE:
932
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
 
1036
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1037
            "(Avahi Resolver) Failed to resolve service '%s'"
933
1038
            " of type '%s' in domain '%s': %s\n", name, type, domain,
934
1039
            avahi_strerror(avahi_server_errno(mc.server)));
935
1040
    break;
939
1044
      char ip[AVAHI_ADDRESS_STR_MAX];
940
1045
      avahi_address_snprint(ip, sizeof(ip), address);
941
1046
      if(debug){
942
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1047
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1048
                "Mandos server \"%s\" found on %s (%s, %"
943
1049
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
944
1050
                ip, (intmax_t)interface, port);
945
1051
      }
947
1053
                                           avahi_proto_to_af(proto));
948
1054
      if(ret == 0){
949
1055
        avahi_simple_poll_quit(mc.simple_poll);
 
1056
      } else {
 
1057
        ret = add_server(ip, port, interface,
 
1058
                         avahi_proto_to_af(proto));
950
1059
      }
951
1060
    }
952
1061
  }
976
1085
  default:
977
1086
  case AVAHI_BROWSER_FAILURE:
978
1087
    
979
 
    fprintf(stderr, "(Avahi browser) %s\n",
 
1088
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1089
            "(Avahi browser) %s\n",
980
1090
            avahi_strerror(avahi_server_errno(mc.server)));
981
1091
    avahi_simple_poll_quit(mc.simple_poll);
982
1092
    return;
990
1100
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
991
1101
                                    name, type, domain, protocol, 0,
992
1102
                                    resolve_callback, NULL) == NULL)
993
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
1103
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1104
              "Avahi: Failed to resolve service '%s': %s\n",
994
1105
              name, avahi_strerror(avahi_server_errno(mc.server)));
995
1106
    break;
996
1107
    
1000
1111
  case AVAHI_BROWSER_ALL_FOR_NOW:
1001
1112
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1002
1113
    if(debug){
1003
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1114
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1115
              "No Mandos server found, still searching...\n");
1004
1116
    }
1005
1117
    break;
1006
1118
  }
1007
1119
}
1008
1120
 
1009
 
/* stop main loop after sigterm has been called */
 
1121
/* Signal handler that stops main loop after SIGTERM */
1010
1122
static void handle_sigterm(int sig){
1011
1123
  if(quit_now){
1012
1124
    return;
1014
1126
  quit_now = 1;
1015
1127
  signal_received = sig;
1016
1128
  int old_errno = errno;
 
1129
  /* set main loop to exit */
1017
1130
  if(mc.simple_poll != NULL){
1018
1131
    avahi_simple_poll_quit(mc.simple_poll);
1019
1132
  }
1020
1133
  errno = old_errno;
1021
1134
}
1022
1135
 
 
1136
bool get_flags(const char *ifname, struct ifreq *ifr){
 
1137
  int ret;
 
1138
  
 
1139
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1140
  if(s < 0){
 
1141
    perror_plus("socket");
 
1142
    return false;
 
1143
  }
 
1144
  strcpy(ifr->ifr_name, ifname);
 
1145
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
 
1146
  if(ret == -1){
 
1147
    if(debug){
 
1148
      perror_plus("ioctl SIOCGIFFLAGS");
 
1149
    }
 
1150
    return false;
 
1151
  }
 
1152
  return true;
 
1153
}
 
1154
 
 
1155
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1156
  
 
1157
  /* Reject the loopback device */
 
1158
  if(ifr->ifr_flags & IFF_LOOPBACK){
 
1159
    if(debug){
 
1160
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1161
              "Rejecting loopback interface \"%s\"\n", ifname);
 
1162
    }
 
1163
    return false;
 
1164
  }
 
1165
  /* Accept point-to-point devices only if connect_to is specified */
 
1166
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
 
1167
    if(debug){
 
1168
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1169
              "Accepting point-to-point interface \"%s\"\n", ifname);
 
1170
    }
 
1171
    return true;
 
1172
  }
 
1173
  /* Otherwise, reject non-broadcast-capable devices */
 
1174
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
 
1175
    if(debug){
 
1176
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1177
              "Rejecting non-broadcast interface \"%s\"\n", ifname);
 
1178
    }
 
1179
    return false;
 
1180
  }
 
1181
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1182
  if(ifr->ifr_flags & IFF_NOARP){
 
1183
    if(debug){
 
1184
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1185
              "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1186
    }
 
1187
    return false;
 
1188
  }
 
1189
  
 
1190
  /* Accept this device */
 
1191
  if(debug){
 
1192
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1193
            "Interface \"%s\" is good\n", ifname);
 
1194
  }
 
1195
  return true;
 
1196
}
 
1197
 
 
1198
/* 
 
1199
 * This function determines if a directory entry in /sys/class/net
 
1200
 * corresponds to an acceptable network device.
 
1201
 * (This function is passed to scandir(3) as a filter function.)
 
1202
 */
 
1203
int good_interface(const struct dirent *if_entry){
 
1204
  if(if_entry->d_name[0] == '.'){
 
1205
    return 0;
 
1206
  }
 
1207
  
 
1208
  struct ifreq ifr;
 
1209
  if(not get_flags(if_entry->d_name, &ifr)){
 
1210
    if(debug){
 
1211
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1212
              "Failed to get flags for interface \"%s\"\n",
 
1213
              if_entry->d_name);
 
1214
    }
 
1215
    return 0;
 
1216
  }
 
1217
  
 
1218
  if(not good_flags(if_entry->d_name, &ifr)){
 
1219
    return 0;
 
1220
  }
 
1221
  return 1;
 
1222
}
 
1223
 
 
1224
/* 
 
1225
 * This function determines if a directory entry in /sys/class/net
 
1226
 * corresponds to an acceptable network device which is up.
 
1227
 * (This function is passed to scandir(3) as a filter function.)
 
1228
 */
 
1229
int up_interface(const struct dirent *if_entry){
 
1230
  if(if_entry->d_name[0] == '.'){
 
1231
    return 0;
 
1232
  }
 
1233
  
 
1234
  struct ifreq ifr;
 
1235
  if(not get_flags(if_entry->d_name, &ifr)){
 
1236
    if(debug){
 
1237
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1238
              "Failed to get flags for interface \"%s\"\n",
 
1239
              if_entry->d_name);
 
1240
    }
 
1241
    return 0;
 
1242
  }
 
1243
  
 
1244
  /* Reject down interfaces */
 
1245
  if(not (ifr.ifr_flags & IFF_UP)){
 
1246
    if(debug){
 
1247
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1248
              "Rejecting down interface \"%s\"\n",
 
1249
              if_entry->d_name);
 
1250
    }
 
1251
    return 0;
 
1252
  }
 
1253
  
 
1254
  /* Reject non-running interfaces */
 
1255
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1256
    if(debug){
 
1257
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1258
              "Rejecting non-running interface \"%s\"\n",
 
1259
              if_entry->d_name);
 
1260
    }
 
1261
    return 0;
 
1262
  }
 
1263
  
 
1264
  if(not good_flags(if_entry->d_name, &ifr)){
 
1265
    return 0;
 
1266
  }
 
1267
  return 1;
 
1268
}
 
1269
 
 
1270
int notdotentries(const struct dirent *direntry){
 
1271
  /* Skip "." and ".." */
 
1272
  if(direntry->d_name[0] == '.'
 
1273
     and (direntry->d_name[1] == '\0'
 
1274
          or (direntry->d_name[1] == '.'
 
1275
              and direntry->d_name[2] == '\0'))){
 
1276
    return 0;
 
1277
  }
 
1278
  return 1;
 
1279
}
 
1280
 
 
1281
/* Is this directory entry a runnable program? */
 
1282
int runnable_hook(const struct dirent *direntry){
 
1283
  int ret;
 
1284
  struct stat st;
 
1285
  
 
1286
  if((direntry->d_name)[0] == '\0'){
 
1287
    /* Empty name? */
 
1288
    return 0;
 
1289
  }
 
1290
  
 
1291
  /* Save pointer to last character */
 
1292
  char *end = strchr(direntry->d_name, '\0')-1;
 
1293
  
 
1294
  if(*end == '~'){
 
1295
    /* Backup name~ */
 
1296
    return 0;
 
1297
  }
 
1298
  
 
1299
  if(((direntry->d_name)[0] == '#')
 
1300
     and (*end == '#')){
 
1301
    /* Temporary #name# */
 
1302
    return 0;
 
1303
  }
 
1304
  
 
1305
  /* XXX more rules here */
 
1306
  
 
1307
  ret = stat(direntry->d_name, &st);
 
1308
  if(ret == -1){
 
1309
    if(debug){
 
1310
      perror_plus("Could not stat plugin");
 
1311
    }
 
1312
    return 0;
 
1313
  }
 
1314
  if(not (S_ISREG(st.st_mode))){
 
1315
    /* Not a regular file */
 
1316
    return 0;
 
1317
  }
 
1318
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
 
1319
    /* Not executable */
 
1320
    return 0;
 
1321
  }
 
1322
  return 1;
 
1323
}
 
1324
 
 
1325
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1326
  int ret;
 
1327
  struct timespec now;
 
1328
  struct timespec waited_time;
 
1329
  intmax_t block_time;
 
1330
  
 
1331
  while(true){
 
1332
    if(mc.current_server == NULL){
 
1333
      if (debug){
 
1334
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1335
                "Wait until first server is found. No timeout!\n");
 
1336
      }
 
1337
      ret = avahi_simple_poll_iterate(s, -1);
 
1338
    } else {
 
1339
      if (debug){
 
1340
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1341
                "Check current_server if we should run it,"
 
1342
                " or wait\n");
 
1343
      }
 
1344
      /* the current time */
 
1345
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
 
1346
      if(ret == -1){
 
1347
        perror_plus("clock_gettime");
 
1348
        return -1;
 
1349
      }
 
1350
      /* Calculating in ms how long time between now and server
 
1351
         who we visted longest time ago. Now - last seen.  */
 
1352
      waited_time.tv_sec = (now.tv_sec
 
1353
                            - mc.current_server->last_seen.tv_sec);
 
1354
      waited_time.tv_nsec = (now.tv_nsec
 
1355
                             - mc.current_server->last_seen.tv_nsec);
 
1356
      /* total time is 10s/10,000ms.
 
1357
         Converting to s from ms by dividing by 1,000,
 
1358
         and ns to ms by dividing by 1,000,000. */
 
1359
      block_time = ((retry_interval
 
1360
                     - ((intmax_t)waited_time.tv_sec * 1000))
 
1361
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
 
1362
      
 
1363
      if (debug){
 
1364
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1365
                "Blocking for %" PRIdMAX " ms\n", block_time);
 
1366
      }
 
1367
      
 
1368
      if(block_time <= 0){
 
1369
        ret = start_mandos_communication(mc.current_server->ip,
 
1370
                                         mc.current_server->port,
 
1371
                                         mc.current_server->if_index,
 
1372
                                         mc.current_server->af);
 
1373
        if(ret == 0){
 
1374
          avahi_simple_poll_quit(mc.simple_poll);
 
1375
          return 0;
 
1376
        }
 
1377
        ret = clock_gettime(CLOCK_MONOTONIC,
 
1378
                            &mc.current_server->last_seen);
 
1379
        if(ret == -1){
 
1380
          perror_plus("clock_gettime");
 
1381
          return -1;
 
1382
        }
 
1383
        mc.current_server = mc.current_server->next;
 
1384
        block_time = 0;         /* Call avahi to find new Mandos
 
1385
                                   servers, but don't block */
 
1386
      }
 
1387
      
 
1388
      ret = avahi_simple_poll_iterate(s, (int)block_time);
 
1389
    }
 
1390
    if(ret != 0){
 
1391
      if (ret > 0 or errno != EINTR){
 
1392
        return (ret != 1) ? ret : 0;
 
1393
      }
 
1394
    }
 
1395
  }
 
1396
}
 
1397
 
1023
1398
int main(int argc, char *argv[]){
1024
1399
  AvahiSServiceBrowser *sb = NULL;
1025
1400
  int error;
1027
1402
  intmax_t tmpmax;
1028
1403
  char *tmp;
1029
1404
  int exitcode = EXIT_SUCCESS;
1030
 
  const char *interface = "eth0";
 
1405
  const char *interface = "";
1031
1406
  struct ifreq network;
1032
1407
  int sd = -1;
1033
1408
  bool take_down_interface = false;
1034
1409
  uid_t uid;
1035
1410
  gid_t gid;
1036
 
  char *connect_to = NULL;
1037
1411
  char tempdir[] = "/tmp/mandosXXXXXX";
1038
1412
  bool tempdir_created = false;
1039
1413
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1043
1417
  bool gnutls_initialized = false;
1044
1418
  bool gpgme_initialized = false;
1045
1419
  float delay = 2.5f;
 
1420
  double retry_interval = 10; /* 10s between trying a server and
 
1421
                                 retrying the same server again */
1046
1422
  
1047
1423
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1048
1424
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1054
1430
  errno = 0;
1055
1431
  ret = setgid(gid);
1056
1432
  if(ret == -1){
1057
 
    perror("setgid");
 
1433
    perror_plus("setgid");
1058
1434
  }
1059
1435
  
1060
1436
  /* Lower user privileges (temporarily) */
1061
1437
  errno = 0;
1062
1438
  ret = seteuid(uid);
1063
1439
  if(ret == -1){
1064
 
    perror("seteuid");
 
1440
    perror_plus("seteuid");
1065
1441
  }
1066
1442
  
1067
1443
  if(quit_now){
1102
1478
        .arg = "SECONDS",
1103
1479
        .doc = "Maximum delay to wait for interface startup",
1104
1480
        .group = 2 },
 
1481
      { .name = "retry", .key = 132,
 
1482
        .arg = "SECONDS",
 
1483
        .doc = "Retry interval used when denied by the mandos server",
 
1484
        .group = 2 },
1105
1485
      /*
1106
1486
       * These reproduce what we would get without ARGP_NO_HELP
1107
1487
       */
1151
1531
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1152
1532
          argp_error(state, "Bad delay");
1153
1533
        }
 
1534
      case 132:                 /* --retry */
 
1535
        errno = 0;
 
1536
        retry_interval = strtod(arg, &tmp);
 
1537
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1538
           or (retry_interval * 1000) > INT_MAX
 
1539
           or retry_interval < 0){
 
1540
          argp_error(state, "Bad retry interval");
 
1541
        }
1154
1542
        break;
1155
1543
        /*
1156
1544
         * These reproduce what we would get without ARGP_NO_HELP
1163
1551
        argp_state_help(state, state->out_stream,
1164
1552
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1165
1553
      case 'V':                 /* --version */
 
1554
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
1166
1555
        fprintf(state->out_stream, "%s\n", argp_program_version);
1167
1556
        exit(argp_err_exit_status);
1168
1557
        break;
1184
1573
    case ENOMEM:
1185
1574
    default:
1186
1575
      errno = ret;
1187
 
      perror("argp_parse");
 
1576
      perror_plus("argp_parse");
1188
1577
      exitcode = EX_OSERR;
1189
1578
      goto end;
1190
1579
    case EINVAL:
1192
1581
      goto end;
1193
1582
    }
1194
1583
  }
 
1584
    
 
1585
  {
 
1586
    /* Work around Debian bug #633582:
 
1587
       <http://bugs.debian.org/633582> */
 
1588
    struct stat st;
 
1589
    
 
1590
    /* Re-raise priviliges */
 
1591
    errno = 0;
 
1592
    ret = seteuid(0);
 
1593
    if(ret == -1){
 
1594
      perror_plus("seteuid");
 
1595
    }
 
1596
    
 
1597
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1598
      int seckey_fd = open(seckey, O_RDONLY);
 
1599
      if(seckey_fd == -1){
 
1600
        perror_plus("open");
 
1601
      } else {
 
1602
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1603
        if(ret == -1){
 
1604
          perror_plus("fstat");
 
1605
        } else {
 
1606
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1607
            ret = fchown(seckey_fd, uid, gid);
 
1608
            if(ret == -1){
 
1609
              perror_plus("fchown");
 
1610
            }
 
1611
          }
 
1612
        }
 
1613
        TEMP_FAILURE_RETRY(close(seckey_fd));
 
1614
      }
 
1615
    }
 
1616
    
 
1617
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1618
      int pubkey_fd = open(pubkey, O_RDONLY);
 
1619
      if(pubkey_fd == -1){
 
1620
        perror_plus("open");
 
1621
      } else {
 
1622
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1623
        if(ret == -1){
 
1624
          perror_plus("fstat");
 
1625
        } else {
 
1626
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1627
            ret = fchown(pubkey_fd, uid, gid);
 
1628
            if(ret == -1){
 
1629
              perror_plus("fchown");
 
1630
            }
 
1631
          }
 
1632
        }
 
1633
        TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1634
      }
 
1635
    }
 
1636
    
 
1637
    /* Lower privileges */
 
1638
    errno = 0;
 
1639
    ret = seteuid(uid);
 
1640
    if(ret == -1){
 
1641
      perror_plus("seteuid");
 
1642
    }
 
1643
  }
 
1644
  
 
1645
  /* Find network hooks and run them */
 
1646
  {
 
1647
    struct dirent **direntries;
 
1648
    struct dirent *direntry;
 
1649
    int numhooks = scandir(HOOKDIR, &direntries, runnable_hook,
 
1650
                           alphasort);
 
1651
    if(numhooks == -1){
 
1652
      perror_plus("scandir");
 
1653
    } else {
 
1654
      int devnull = open("/dev/null", O_RDONLY);
 
1655
      for(int i = 0; i < numhooks; i++){
 
1656
        direntry = direntries[0];
 
1657
        char *fullname = NULL;
 
1658
        ret = asprintf(&fullname, "%s/%s", tempdir,
 
1659
                       direntry->d_name);
 
1660
        if(ret < 0){
 
1661
          perror_plus("asprintf");
 
1662
          continue;
 
1663
        }
 
1664
        pid_t hook_pid = fork();
 
1665
        if(hook_pid == 0){
 
1666
          /* Child */
 
1667
          dup2(devnull, STDIN_FILENO);
 
1668
          close(devnull);
 
1669
          dup2(STDERR_FILENO, STDOUT_FILENO);
 
1670
          ret = setenv("DEVICE", interface, 1);
 
1671
          if(ret == -1){
 
1672
            perror_plus("setenv");
 
1673
            exit(1);
 
1674
          }
 
1675
          ret = setenv("VERBOSE", debug ? "1" : "0", 1);
 
1676
          if(ret == -1){
 
1677
            perror_plus("setenv");
 
1678
            exit(1);
 
1679
          }
 
1680
          ret = setenv("MODE", "start", 1);
 
1681
          if(ret == -1){
 
1682
            perror_plus("setenv");
 
1683
            exit(1);
 
1684
          }
 
1685
          char *delaystring;
 
1686
          ret = asprintf(&delaystring, "%f", delay);
 
1687
          if(ret == -1){
 
1688
            perror_plus("asprintf");
 
1689
            exit(1);
 
1690
          }
 
1691
          ret = setenv("DELAY", delaystring, 1);
 
1692
          if(ret == -1){
 
1693
            free(delaystring);
 
1694
            perror_plus("setenv");
 
1695
            exit(1);
 
1696
          }
 
1697
          free(delaystring);
 
1698
          ret = execl(fullname, direntry->d_name, "start", NULL);
 
1699
          perror_plus("execl");
 
1700
        } else {
 
1701
          int status;
 
1702
          if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1703
            perror_plus("waitpid");
 
1704
            free(fullname);
 
1705
            continue;
 
1706
          }
 
1707
          if(WIFEXITED(status)){
 
1708
            if(WEXITSTATUS(status) != 0){
 
1709
              fprintf(stderr, "Mandos plugin mandos-client: "
 
1710
                      "Warning: network hook \"%s\" exited"
 
1711
                      " with status %d\n", direntry->d_name,
 
1712
                      WEXITSTATUS(status));
 
1713
              free(fullname);
 
1714
              continue;
 
1715
            }
 
1716
          } else if(WIFSIGNALED(status)){
 
1717
            fprintf(stderr, "Mandos plugin mandos-client: "
 
1718
                    "Warning: network hook \"%s\" died by"
 
1719
                    " signal %d\n", direntry->d_name,
 
1720
                    WTERMSIG(status));
 
1721
            free(fullname);
 
1722
            continue;
 
1723
          } else {
 
1724
            fprintf(stderr, "Mandos plugin mandos-client: "
 
1725
                    "Warning: network hook \"%s\" crashed\n",
 
1726
                    direntry->d_name);
 
1727
            free(fullname);
 
1728
            continue;
 
1729
          }
 
1730
        }
 
1731
        free(fullname);
 
1732
        if(quit_now){
 
1733
          goto end;
 
1734
        }
 
1735
      }
 
1736
      close(devnull);
 
1737
    }
 
1738
  }
1195
1739
  
1196
1740
  if(not debug){
1197
1741
    avahi_set_log_function(empty_log);
1198
1742
  }
1199
1743
  
 
1744
  if(interface[0] == '\0'){
 
1745
    struct dirent **direntries;
 
1746
    /* First look for interfaces that are up */
 
1747
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1748
                  alphasort);
 
1749
    if(ret == 0){
 
1750
      /* No up interfaces, look for any good interfaces */
 
1751
      free(direntries);
 
1752
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1753
                    alphasort);
 
1754
    }
 
1755
    if(ret >= 1){
 
1756
      /* Pick the first interface returned */
 
1757
      interface = strdup(direntries[0]->d_name);
 
1758
      if(debug){
 
1759
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1760
                "Using interface \"%s\"\n", interface);
 
1761
      }
 
1762
      if(interface == NULL){
 
1763
        perror_plus("malloc");
 
1764
        free(direntries);
 
1765
        exitcode = EXIT_FAILURE;
 
1766
        goto end;
 
1767
      }
 
1768
      free(direntries);
 
1769
    } else {
 
1770
      free(direntries);
 
1771
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1772
              "Could not find a network interface\n");
 
1773
      exitcode = EXIT_FAILURE;
 
1774
      goto end;
 
1775
    }
 
1776
  }
 
1777
  
1200
1778
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1201
1779
     from the signal handler */
1202
1780
  /* Initialize the pseudo-RNG for Avahi */
1203
1781
  srand((unsigned int) time(NULL));
1204
1782
  mc.simple_poll = avahi_simple_poll_new();
1205
1783
  if(mc.simple_poll == NULL){
1206
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1784
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1785
            "Avahi: Failed to create simple poll object.\n");
1207
1786
    exitcode = EX_UNAVAILABLE;
1208
1787
    goto end;
1209
1788
  }
1211
1790
  sigemptyset(&sigterm_action.sa_mask);
1212
1791
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1213
1792
  if(ret == -1){
1214
 
    perror("sigaddset");
 
1793
    perror_plus("sigaddset");
1215
1794
    exitcode = EX_OSERR;
1216
1795
    goto end;
1217
1796
  }
1218
1797
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1219
1798
  if(ret == -1){
1220
 
    perror("sigaddset");
 
1799
    perror_plus("sigaddset");
1221
1800
    exitcode = EX_OSERR;
1222
1801
    goto end;
1223
1802
  }
1224
1803
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1225
1804
  if(ret == -1){
1226
 
    perror("sigaddset");
 
1805
    perror_plus("sigaddset");
1227
1806
    exitcode = EX_OSERR;
1228
1807
    goto end;
1229
1808
  }
1233
1812
  */
1234
1813
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1235
1814
  if(ret == -1){
1236
 
    perror("sigaction");
 
1815
    perror_plus("sigaction");
1237
1816
    return EX_OSERR;
1238
1817
  }
1239
1818
  if(old_sigterm_action.sa_handler != SIG_IGN){
1240
1819
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1241
1820
    if(ret == -1){
1242
 
      perror("sigaction");
 
1821
      perror_plus("sigaction");
1243
1822
      exitcode = EX_OSERR;
1244
1823
      goto end;
1245
1824
    }
1246
1825
  }
1247
1826
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1248
1827
  if(ret == -1){
1249
 
    perror("sigaction");
 
1828
    perror_plus("sigaction");
1250
1829
    return EX_OSERR;
1251
1830
  }
1252
1831
  if(old_sigterm_action.sa_handler != SIG_IGN){
1253
1832
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1254
1833
    if(ret == -1){
1255
 
      perror("sigaction");
 
1834
      perror_plus("sigaction");
1256
1835
      exitcode = EX_OSERR;
1257
1836
      goto end;
1258
1837
    }
1259
1838
  }
1260
1839
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1261
1840
  if(ret == -1){
1262
 
    perror("sigaction");
 
1841
    perror_plus("sigaction");
1263
1842
    return EX_OSERR;
1264
1843
  }
1265
1844
  if(old_sigterm_action.sa_handler != SIG_IGN){
1266
1845
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1267
1846
    if(ret == -1){
1268
 
      perror("sigaction");
 
1847
      perror_plus("sigaction");
1269
1848
      exitcode = EX_OSERR;
1270
1849
      goto end;
1271
1850
    }
1272
1851
  }
1273
1852
  
1274
1853
  /* If the interface is down, bring it up */
1275
 
  if(interface[0] != '\0'){
 
1854
  if(strcmp(interface, "none") != 0){
1276
1855
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1277
1856
    if(if_index == 0){
1278
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1857
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1858
              "No such interface: \"%s\"\n", interface);
1279
1859
      exitcode = EX_UNAVAILABLE;
1280
1860
      goto end;
1281
1861
    }
1288
1868
    errno = 0;
1289
1869
    ret = seteuid(0);
1290
1870
    if(ret == -1){
1291
 
      perror("seteuid");
 
1871
      perror_plus("seteuid");
1292
1872
    }
1293
1873
    
1294
1874
#ifdef __linux__
1298
1878
    bool restore_loglevel = true;
1299
1879
    if(ret == -1){
1300
1880
      restore_loglevel = false;
1301
 
      perror("klogctl");
 
1881
      perror_plus("klogctl");
1302
1882
    }
1303
1883
#endif  /* __linux__ */
1304
1884
    
1305
1885
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1306
1886
    if(sd < 0){
1307
 
      perror("socket");
 
1887
      perror_plus("socket");
1308
1888
      exitcode = EX_OSERR;
1309
1889
#ifdef __linux__
1310
1890
      if(restore_loglevel){
1311
1891
        ret = klogctl(7, NULL, 0);
1312
1892
        if(ret == -1){
1313
 
          perror("klogctl");
 
1893
          perror_plus("klogctl");
1314
1894
        }
1315
1895
      }
1316
1896
#endif  /* __linux__ */
1318
1898
      errno = 0;
1319
1899
      ret = seteuid(uid);
1320
1900
      if(ret == -1){
1321
 
        perror("seteuid");
 
1901
        perror_plus("seteuid");
1322
1902
      }
1323
1903
      goto end;
1324
1904
    }
1325
1905
    strcpy(network.ifr_name, interface);
1326
1906
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1327
1907
    if(ret == -1){
1328
 
      perror("ioctl SIOCGIFFLAGS");
 
1908
      perror_plus("ioctl SIOCGIFFLAGS");
1329
1909
#ifdef __linux__
1330
1910
      if(restore_loglevel){
1331
1911
        ret = klogctl(7, NULL, 0);
1332
1912
        if(ret == -1){
1333
 
          perror("klogctl");
 
1913
          perror_plus("klogctl");
1334
1914
        }
1335
1915
      }
1336
1916
#endif  /* __linux__ */
1339
1919
      errno = 0;
1340
1920
      ret = seteuid(uid);
1341
1921
      if(ret == -1){
1342
 
        perror("seteuid");
 
1922
        perror_plus("seteuid");
1343
1923
      }
1344
1924
      goto end;
1345
1925
    }
1349
1929
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1350
1930
      if(ret == -1){
1351
1931
        take_down_interface = false;
1352
 
        perror("ioctl SIOCSIFFLAGS");
 
1932
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1353
1933
        exitcode = EX_OSERR;
1354
1934
#ifdef __linux__
1355
1935
        if(restore_loglevel){
1356
1936
          ret = klogctl(7, NULL, 0);
1357
1937
          if(ret == -1){
1358
 
            perror("klogctl");
 
1938
            perror_plus("klogctl");
1359
1939
          }
1360
1940
        }
1361
1941
#endif  /* __linux__ */
1363
1943
        errno = 0;
1364
1944
        ret = seteuid(uid);
1365
1945
        if(ret == -1){
1366
 
          perror("seteuid");
 
1946
          perror_plus("seteuid");
1367
1947
        }
1368
1948
        goto end;
1369
1949
      }
1370
1950
    }
1371
 
    /* sleep checking until interface is running */
 
1951
    /* Sleep checking until interface is running.
 
1952
       Check every 0.25s, up to total time of delay */
1372
1953
    for(int i=0; i < delay * 4; i++){
1373
1954
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1374
1955
      if(ret == -1){
1375
 
        perror("ioctl SIOCGIFFLAGS");
 
1956
        perror_plus("ioctl SIOCGIFFLAGS");
1376
1957
      } else if(network.ifr_flags & IFF_RUNNING){
1377
1958
        break;
1378
1959
      }
1379
1960
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1380
1961
      ret = nanosleep(&sleeptime, NULL);
1381
1962
      if(ret == -1 and errno != EINTR){
1382
 
        perror("nanosleep");
 
1963
        perror_plus("nanosleep");
1383
1964
      }
1384
1965
    }
1385
1966
    if(not take_down_interface){
1386
1967
      /* We won't need the socket anymore */
1387
1968
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1388
1969
      if(ret == -1){
1389
 
        perror("close");
 
1970
        perror_plus("close");
1390
1971
      }
1391
1972
    }
1392
1973
#ifdef __linux__
1394
1975
      /* Restores kernel loglevel to default */
1395
1976
      ret = klogctl(7, NULL, 0);
1396
1977
      if(ret == -1){
1397
 
        perror("klogctl");
 
1978
        perror_plus("klogctl");
1398
1979
      }
1399
1980
    }
1400
1981
#endif  /* __linux__ */
1404
1985
      /* Lower privileges */
1405
1986
      ret = seteuid(uid);
1406
1987
      if(ret == -1){
1407
 
        perror("seteuid");
 
1988
        perror_plus("seteuid");
1408
1989
      }
1409
1990
    } else {
1410
1991
      /* Lower privileges permanently */
1411
1992
      ret = setuid(uid);
1412
1993
      if(ret == -1){
1413
 
        perror("setuid");
 
1994
        perror_plus("setuid");
1414
1995
      }
1415
1996
    }
1416
1997
  }
1421
2002
  
1422
2003
  ret = init_gnutls_global(pubkey, seckey);
1423
2004
  if(ret == -1){
1424
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
2005
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2006
            "init_gnutls_global failed\n");
1425
2007
    exitcode = EX_UNAVAILABLE;
1426
2008
    goto end;
1427
2009
  } else {
1432
2014
    goto end;
1433
2015
  }
1434
2016
  
 
2017
  if(mkdtemp(tempdir) == NULL){
 
2018
    perror_plus("mkdtemp");
 
2019
    goto end;
 
2020
  }
1435
2021
  tempdir_created = true;
1436
 
  if(mkdtemp(tempdir) == NULL){
1437
 
    tempdir_created = false;
1438
 
    perror("mkdtemp");
1439
 
    goto end;
1440
 
  }
1441
2022
  
1442
2023
  if(quit_now){
1443
2024
    goto end;
1444
2025
  }
1445
2026
  
1446
2027
  if(not init_gpgme(pubkey, seckey, tempdir)){
1447
 
    fprintf(stderr, "init_gpgme failed\n");
 
2028
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2029
            "init_gpgme failed\n");
1448
2030
    exitcode = EX_UNAVAILABLE;
1449
2031
    goto end;
1450
2032
  } else {
1460
2042
    /* (Mainly meant for debugging) */
1461
2043
    char *address = strrchr(connect_to, ':');
1462
2044
    if(address == NULL){
1463
 
      fprintf(stderr, "No colon in address\n");
 
2045
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2046
              "No colon in address\n");
1464
2047
      exitcode = EX_USAGE;
1465
2048
      goto end;
1466
2049
    }
1474
2057
    tmpmax = strtoimax(address+1, &tmp, 10);
1475
2058
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1476
2059
       or tmpmax != (uint16_t)tmpmax){
1477
 
      fprintf(stderr, "Bad port number\n");
 
2060
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2061
              "Bad port number\n");
1478
2062
      exitcode = EX_USAGE;
1479
2063
      goto end;
1480
2064
    }
1485
2069
    
1486
2070
    port = (uint16_t)tmpmax;
1487
2071
    *address = '\0';
1488
 
    address = connect_to;
1489
2072
    /* Colon in address indicates IPv6 */
1490
2073
    int af;
1491
 
    if(strchr(address, ':') != NULL){
 
2074
    if(strchr(connect_to, ':') != NULL){
1492
2075
      af = AF_INET6;
 
2076
      /* Accept [] around IPv6 address - see RFC 5952 */
 
2077
      if(connect_to[0] == '[' and address[-1] == ']')
 
2078
        {
 
2079
          connect_to++;
 
2080
          address[-1] = '\0';
 
2081
        }
1493
2082
    } else {
1494
2083
      af = AF_INET;
1495
2084
    }
 
2085
    address = connect_to;
1496
2086
    
1497
2087
    if(quit_now){
1498
2088
      goto end;
1499
2089
    }
1500
2090
    
1501
 
    ret = start_mandos_communication(address, port, if_index, af);
1502
 
    if(ret < 0){
1503
 
      switch(errno){
1504
 
      case ENETUNREACH:
1505
 
      case EHOSTDOWN:
1506
 
      case EHOSTUNREACH:
1507
 
        exitcode = EX_NOHOST;
1508
 
        break;
1509
 
      case EINVAL:
1510
 
        exitcode = EX_USAGE;
1511
 
        break;
1512
 
      case EIO:
1513
 
        exitcode = EX_IOERR;
1514
 
        break;
1515
 
      case EPROTO:
1516
 
        exitcode = EX_PROTOCOL;
1517
 
        break;
1518
 
      default:
1519
 
        exitcode = EX_OSERR;
1520
 
        break;
1521
 
      }
1522
 
    } else {
 
2091
    while(not quit_now){
 
2092
      ret = start_mandos_communication(address, port, if_index, af);
 
2093
      if(quit_now or ret == 0){
 
2094
        break;
 
2095
      }
 
2096
      if(debug){
 
2097
        fprintf(stderr, "Mandos plugin mandos-client: "
 
2098
                "Retrying in %d seconds\n", (int)retry_interval);
 
2099
      }
 
2100
      sleep((int)retry_interval);
 
2101
    }
 
2102
    
 
2103
    if (not quit_now){
1523
2104
      exitcode = EXIT_SUCCESS;
1524
2105
    }
 
2106
    
1525
2107
    goto end;
1526
2108
  }
1527
2109
  
1549
2131
  
1550
2132
  /* Check if creating the Avahi server object succeeded */
1551
2133
  if(mc.server == NULL){
1552
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
2134
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2135
            "Failed to create Avahi server: %s\n",
1553
2136
            avahi_strerror(error));
1554
2137
    exitcode = EX_UNAVAILABLE;
1555
2138
    goto end;
1564
2147
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1565
2148
                                   NULL, 0, browse_callback, NULL);
1566
2149
  if(sb == NULL){
1567
 
    fprintf(stderr, "Failed to create service browser: %s\n",
 
2150
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2151
            "Failed to create service browser: %s\n",
1568
2152
            avahi_strerror(avahi_server_errno(mc.server)));
1569
2153
    exitcode = EX_UNAVAILABLE;
1570
2154
    goto end;
1577
2161
  /* Run the main loop */
1578
2162
  
1579
2163
  if(debug){
1580
 
    fprintf(stderr, "Starting Avahi loop search\n");
1581
 
  }
1582
 
  
1583
 
  avahi_simple_poll_loop(mc.simple_poll);
 
2164
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2165
            "Starting Avahi loop search\n");
 
2166
  }
 
2167
 
 
2168
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
2169
                                (int)(retry_interval * 1000));
 
2170
  if(debug){
 
2171
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2172
            "avahi_loop_with_timeout exited %s\n",
 
2173
            (ret == 0) ? "successfully" : "with error");
 
2174
  }
1584
2175
  
1585
2176
 end:
1586
2177
  
1587
2178
  if(debug){
1588
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2179
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2180
            "%s exiting\n", argv[0]);
1589
2181
  }
1590
2182
  
1591
2183
  /* Cleanup things */
1607
2199
  if(gpgme_initialized){
1608
2200
    gpgme_release(mc.ctx);
1609
2201
  }
 
2202
 
 
2203
  /* Cleans up the circular linked list of Mandos servers the client
 
2204
     has seen */
 
2205
  if(mc.current_server != NULL){
 
2206
    mc.current_server->prev->next = NULL;
 
2207
    while(mc.current_server != NULL){
 
2208
      server *next = mc.current_server->next;
 
2209
      free(mc.current_server);
 
2210
      mc.current_server = next;
 
2211
    }
 
2212
  }
 
2213
  
 
2214
  /* XXX run network hooks "stop" here  */
1610
2215
  
1611
2216
  /* Take down the network interface */
1612
2217
  if(take_down_interface){
1614
2219
    errno = 0;
1615
2220
    ret = seteuid(0);
1616
2221
    if(ret == -1){
1617
 
      perror("seteuid");
 
2222
      perror_plus("seteuid");
1618
2223
    }
1619
2224
    if(geteuid() == 0){
1620
2225
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1621
2226
      if(ret == -1){
1622
 
        perror("ioctl SIOCGIFFLAGS");
1623
 
      } else if(network.ifr_flags & IFF_UP) {
 
2227
        perror_plus("ioctl SIOCGIFFLAGS");
 
2228
      } else if(network.ifr_flags & IFF_UP){
1624
2229
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1625
2230
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1626
2231
        if(ret == -1){
1627
 
          perror("ioctl SIOCSIFFLAGS");
 
2232
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1628
2233
        }
1629
2234
      }
1630
2235
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1631
2236
      if(ret == -1){
1632
 
        perror("close");
 
2237
        perror_plus("close");
1633
2238
      }
1634
2239
      /* Lower privileges permanently */
1635
2240
      errno = 0;
1636
2241
      ret = setuid(uid);
1637
2242
      if(ret == -1){
1638
 
        perror("setuid");
 
2243
        perror_plus("setuid");
1639
2244
      }
1640
2245
    }
1641
2246
  }
1642
2247
  
1643
 
  /* Removes the temp directory used by GPGME */
 
2248
  /* Removes the GPGME temp directory and all files inside */
1644
2249
  if(tempdir_created){
1645
 
    DIR *d;
1646
 
    struct dirent *direntry;
1647
 
    d = opendir(tempdir);
1648
 
    if(d == NULL){
1649
 
      if(errno != ENOENT){
1650
 
        perror("opendir");
1651
 
      }
1652
 
    } else {
1653
 
      while(true){
1654
 
        direntry = readdir(d);
1655
 
        if(direntry == NULL){
1656
 
          break;
1657
 
        }
1658
 
        /* Skip "." and ".." */
1659
 
        if(direntry->d_name[0] == '.'
1660
 
           and (direntry->d_name[1] == '\0'
1661
 
                or (direntry->d_name[1] == '.'
1662
 
                    and direntry->d_name[2] == '\0'))){
1663
 
          continue;
1664
 
        }
 
2250
    struct dirent **direntries = NULL;
 
2251
    struct dirent *direntry = NULL;
 
2252
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2253
                             alphasort);
 
2254
    if (numentries > 0){
 
2255
      for(int i = 0; i < numentries; i++){
 
2256
        direntry = direntries[i];
1665
2257
        char *fullname = NULL;
1666
2258
        ret = asprintf(&fullname, "%s/%s", tempdir,
1667
2259
                       direntry->d_name);
1668
2260
        if(ret < 0){
1669
 
          perror("asprintf");
 
2261
          perror_plus("asprintf");
1670
2262
          continue;
1671
2263
        }
1672
2264
        ret = remove(fullname);
1673
2265
        if(ret == -1){
1674
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1675
 
                  strerror(errno));
 
2266
          fprintf(stderr, "Mandos plugin mandos-client: "
 
2267
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
1676
2268
        }
1677
2269
        free(fullname);
1678
2270
      }
1679
 
      closedir(d);
 
2271
    }
 
2272
 
 
2273
    /* need to clean even if 0 because man page doesn't specify */
 
2274
    free(direntries);
 
2275
    if (numentries == -1){
 
2276
      perror_plus("scandir");
1680
2277
    }
1681
2278
    ret = rmdir(tempdir);
1682
2279
    if(ret == -1 and errno != ENOENT){
1683
 
      perror("rmdir");
 
2280
      perror_plus("rmdir");
1684
2281
    }
1685
2282
  }
1686
2283
  
1691
2288
                                            &old_sigterm_action,
1692
2289
                                            NULL));
1693
2290
    if(ret == -1){
1694
 
      perror("sigaction");
 
2291
      perror_plus("sigaction");
1695
2292
    }
1696
2293
    do {
1697
2294
      ret = raise(signal_received);
1698
2295
    } while(ret != 0 and errno == EINTR);
1699
2296
    if(ret != 0){
1700
 
      perror("raise");
 
2297
      perror_plus("raise");
1701
2298
      abort();
1702
2299
    }
1703
2300
    TEMP_FAILURE_RETRY(pause());