/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2011-03-17 18:14:34 UTC
  • Revision ID: teddy@fukt.bsnet.se-20110317181434-si1m0l8q5fakzgjx
* DBUS-API: Fix grammar.

Show diffs side-by-side

added added

removed removed

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