/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

  • Committer: Björn Påhlsson
  • Date: 2010-09-07 18:48:56 UTC
  • mto: (237.7.1 mandos)
  • mto: This revision was merged to the branch mainline in revision 270.
  • Revision ID: belorn@fukt.bsnet.se-20100907184856-waz6cvxbm7ranha2
added the actually plugin file for plymouth

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