/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 at bsnet
  • Date: 2011-03-15 20:13:05 UTC
  • Revision ID: teddy@fukt.bsnet.se-20110315201305-1eptd9mvxem1qtr2
* mandos-ctl: Use the new argparse library instead of optparse.

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