/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2009-10-30 16:27:17 UTC
  • Revision ID: teddy@fukt.bsnet.se-20091030162717-dun2a9li8bu6jm2w
* Makefile (DOCBOOKTOMAN, DOCBOOKTOHTML, common.ent, mandos,
            mandos-keygen, mandos-ctl, mandos.lsm): Add $(strip) to
                                                    make commands
                                                    easier to read
                                                    when run.
           (plugins.d/mandos-client): Use $(LINK.c) to compile in the
                                      same way as the other programs -
                                      i.e. not via an object file.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2011 Teddy Hogeborn
13
 
 * Copyright © 2008-2011 Björn Påhlsson
 
12
 * Copyright © 2008,2009 Teddy Hogeborn
 
13
 * Copyright © 2008,2009 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@recompile.se>.
 
29
 * Contact the authors at <mandos@fukt.bsnet.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
43
43
                                   stdout, ferror(), remove() */
44
44
#include <stdint.h>             /* uint16_t, uint32_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
 
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
 
                                   strtof(), abort() */
 
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
 
47
                                   srand(), strtof(), abort() */
48
48
#include <stdbool.h>            /* bool, false, true */
49
49
#include <string.h>             /* memset(), strcmp(), strlen(),
50
50
                                   strerror(), asprintf(), strcpy() */
53
53
                                   sockaddr_in6, PF_INET6,
54
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
55
                                   opendir(), DIR */
56
 
#include <sys/stat.h>           /* open(), S_ISREG */
 
56
#include <sys/stat.h>           /* open() */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect() */
59
59
#include <fcntl.h>              /* open() */
62
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
63
                                   strtoimax() */
64
64
#include <assert.h>             /* assert() */
65
 
#include <errno.h>              /* perror(), errno,
66
 
                                   program_invocation_short_name */
67
 
#include <time.h>               /* nanosleep(), time(), sleep() */
 
65
#include <errno.h>              /* perror(), errno */
 
66
#include <time.h>               /* nanosleep(), time() */
68
67
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
69
68
                                   SIOCSIFFLAGS, if_indextoname(),
70
69
                                   if_nametoindex(), IF_NAMESIZE */
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,
83
82
#include <signal.h>             /* sigemptyset(), sigaddset(),
84
83
                                   sigaction(), SIGTERM, sig_atomic_t,
85
84
                                   raise() */
86
 
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
 
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
 
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
 
                                   WEXITSTATUS(), WTERMSIG() */
 
85
#include <sysexits.h>           /* EX_OSERR, EX_USAGE */
90
86
 
91
87
#ifdef __linux__
92
88
#include <sys/klog.h>           /* klogctl() */
110
106
                                   init_gnutls_session(),
111
107
                                   GNUTLS_* */
112
108
#include <gnutls/openpgp.h>
113
 
                         /* gnutls_certificate_set_openpgp_key_file(),
114
 
                            GNUTLS_OPENPGP_FMT_BASE64 */
 
109
                          /* gnutls_certificate_set_openpgp_key_file(),
 
110
                                   GNUTLS_OPENPGP_FMT_BASE64 */
115
111
 
116
112
/* GPGME */
117
113
#include <gpgme.h>              /* All GPGME types, constants and
125
121
#define PATHDIR "/conf/conf.d/mandos"
126
122
#define SECKEY "seckey.txt"
127
123
#define PUBKEY "pubkey.txt"
128
 
#define HOOKDIR "/lib/mandos/network-hooks.d"
129
124
 
130
125
bool debug = false;
131
126
static const char mandos_protocol_version[] = "1";
132
127
const char *argp_program_version = "mandos-client " VERSION;
133
 
const char *argp_program_bug_address = "<mandos@recompile.se>";
134
 
static const char sys_class_net[] = "/sys/class/net";
135
 
char *connect_to = NULL;
136
 
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;
 
128
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
148
129
 
149
130
/* Used for passing in values through the Avahi callback functions */
150
131
typedef struct {
155
136
  gnutls_dh_params_t dh_params;
156
137
  const char *priority;
157
138
  gpgme_ctx_t ctx;
158
 
  server *current_server;
159
139
} mandos_context;
160
140
 
161
141
/* global context so signal handler can reach it*/
162
142
mandos_context mc = { .simple_poll = NULL, .server = NULL,
163
143
                      .dh_bits = 1024, .priority = "SECURE256"
164
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
165
 
                      .current_server = NULL };
 
144
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
166
145
 
167
146
sig_atomic_t quit_now = 0;
168
147
int signal_received = 0;
169
148
 
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
149
/*
186
150
 * Make additional room in "buffer" for at least BUFFER_SIZE more
187
151
 * bytes. "buffer_capacity" is how much is currently allocated,
188
152
 * "buffer_length" is how much is already used.
189
153
 */
190
154
size_t incbuffer(char **buffer, size_t buffer_length,
191
 
                 size_t buffer_capacity){
 
155
                  size_t buffer_capacity){
192
156
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
193
157
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
194
158
    if(buffer == NULL){
199
163
  return buffer_capacity;
200
164
}
201
165
 
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
166
/* 
240
167
 * Initialize GPGME.
241
168
 */
242
 
static bool init_gpgme(const char *seckey, const char *pubkey,
243
 
                       const char *tempdir){
 
169
static bool init_gpgme(const char *seckey,
 
170
                       const char *pubkey, const char *tempdir){
244
171
  gpgme_error_t rc;
245
172
  gpgme_engine_info_t engine_info;
246
173
  
255
182
    
256
183
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
257
184
    if(fd == -1){
258
 
      perror_plus("open");
 
185
      perror("open");
259
186
      return false;
260
187
    }
261
188
    
262
189
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
263
190
    if(rc != GPG_ERR_NO_ERROR){
264
 
      fprintf(stderr, "Mandos plugin mandos-client: "
265
 
              "bad gpgme_data_new_from_fd: %s: %s\n",
 
191
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
266
192
              gpgme_strsource(rc), gpgme_strerror(rc));
267
193
      return false;
268
194
    }
269
195
    
270
196
    rc = gpgme_op_import(mc.ctx, pgp_data);
271
197
    if(rc != GPG_ERR_NO_ERROR){
272
 
      fprintf(stderr, "Mandos plugin mandos-client: "
273
 
              "bad gpgme_op_import: %s: %s\n",
 
198
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
274
199
              gpgme_strsource(rc), gpgme_strerror(rc));
275
200
      return false;
276
201
    }
277
202
    
278
203
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
279
204
    if(ret == -1){
280
 
      perror_plus("close");
 
205
      perror("close");
281
206
    }
282
207
    gpgme_data_release(pgp_data);
283
208
    return true;
284
209
  }
285
210
  
286
211
  if(debug){
287
 
    fprintf(stderr, "Mandos plugin mandos-client: "
288
 
            "Initializing GPGME\n");
 
212
    fprintf(stderr, "Initializing GPGME\n");
289
213
  }
290
214
  
291
215
  /* Init GPGME */
292
216
  gpgme_check_version(NULL);
293
217
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
294
218
  if(rc != GPG_ERR_NO_ERROR){
295
 
    fprintf(stderr, "Mandos plugin mandos-client: "
296
 
            "bad gpgme_engine_check_version: %s: %s\n",
 
219
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
297
220
            gpgme_strsource(rc), gpgme_strerror(rc));
298
221
    return false;
299
222
  }
300
223
  
301
 
  /* Set GPGME home directory for the OpenPGP engine only */
 
224
    /* Set GPGME home directory for the OpenPGP engine only */
302
225
  rc = gpgme_get_engine_info(&engine_info);
303
226
  if(rc != GPG_ERR_NO_ERROR){
304
 
    fprintf(stderr, "Mandos plugin mandos-client: "
305
 
            "bad gpgme_get_engine_info: %s: %s\n",
 
227
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
306
228
            gpgme_strsource(rc), gpgme_strerror(rc));
307
229
    return false;
308
230
  }
315
237
    engine_info = engine_info->next;
316
238
  }
317
239
  if(engine_info == NULL){
318
 
    fprintf(stderr, "Mandos plugin mandos-client: "
319
 
            "Could not set GPGME home dir to %s\n", tempdir);
 
240
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
320
241
    return false;
321
242
  }
322
243
  
323
244
  /* Create new GPGME "context" */
324
245
  rc = gpgme_new(&(mc.ctx));
325
246
  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));
 
247
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
248
            gpgme_strsource(rc), gpgme_strerror(rc));
329
249
    return false;
330
250
  }
331
251
  
350
270
  ssize_t plaintext_length = 0;
351
271
  
352
272
  if(debug){
353
 
    fprintf(stderr, "Mandos plugin mandos-client: "
354
 
            "Trying to decrypt OpenPGP data\n");
 
273
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
355
274
  }
356
275
  
357
276
  /* Create new GPGME data buffer from memory cryptotext */
358
277
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
359
278
                               0);
360
279
  if(rc != GPG_ERR_NO_ERROR){
361
 
    fprintf(stderr, "Mandos plugin mandos-client: "
362
 
            "bad gpgme_data_new_from_mem: %s: %s\n",
 
280
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
363
281
            gpgme_strsource(rc), gpgme_strerror(rc));
364
282
    return -1;
365
283
  }
367
285
  /* Create new empty GPGME data buffer for the plaintext */
368
286
  rc = gpgme_data_new(&dh_plain);
369
287
  if(rc != GPG_ERR_NO_ERROR){
370
 
    fprintf(stderr, "Mandos plugin mandos-client: "
371
 
            "bad gpgme_data_new: %s: %s\n",
 
288
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
372
289
            gpgme_strsource(rc), gpgme_strerror(rc));
373
290
    gpgme_data_release(dh_crypto);
374
291
    return -1;
378
295
     data buffer */
379
296
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
380
297
  if(rc != GPG_ERR_NO_ERROR){
381
 
    fprintf(stderr, "Mandos plugin mandos-client: "
382
 
            "bad gpgme_op_decrypt: %s: %s\n",
 
298
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
383
299
            gpgme_strsource(rc), gpgme_strerror(rc));
384
300
    plaintext_length = -1;
385
301
    if(debug){
386
302
      gpgme_decrypt_result_t result;
387
303
      result = gpgme_op_decrypt_result(mc.ctx);
388
304
      if(result == NULL){
389
 
        fprintf(stderr, "Mandos plugin mandos-client: "
390
 
                "gpgme_op_decrypt_result failed\n");
 
305
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
391
306
      } else {
392
 
        fprintf(stderr, "Mandos plugin mandos-client: "
393
 
                "Unsupported algorithm: %s\n",
 
307
        fprintf(stderr, "Unsupported algorithm: %s\n",
394
308
                result->unsupported_algorithm);
395
 
        fprintf(stderr, "Mandos plugin mandos-client: "
396
 
                "Wrong key usage: %u\n",
 
309
        fprintf(stderr, "Wrong key usage: %u\n",
397
310
                result->wrong_key_usage);
398
311
        if(result->file_name != NULL){
399
 
          fprintf(stderr, "Mandos plugin mandos-client: "
400
 
                  "File name: %s\n", result->file_name);
 
312
          fprintf(stderr, "File name: %s\n", result->file_name);
401
313
        }
402
314
        gpgme_recipient_t recipient;
403
315
        recipient = result->recipients;
404
316
        while(recipient != NULL){
405
 
          fprintf(stderr, "Mandos plugin mandos-client: "
406
 
                  "Public key algorithm: %s\n",
 
317
          fprintf(stderr, "Public key algorithm: %s\n",
407
318
                  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",
 
319
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
320
          fprintf(stderr, "Secret key available: %s\n",
412
321
                  recipient->status == GPG_ERR_NO_SECKEY
413
322
                  ? "No" : "Yes");
414
323
          recipient = recipient->next;
419
328
  }
420
329
  
421
330
  if(debug){
422
 
    fprintf(stderr, "Mandos plugin mandos-client: "
423
 
            "Decryption of OpenPGP data succeeded\n");
 
331
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
424
332
  }
425
333
  
426
334
  /* Seek back to the beginning of the GPGME plaintext data buffer */
427
335
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
428
 
    perror_plus("gpgme_data_seek");
 
336
    perror("gpgme_data_seek");
429
337
    plaintext_length = -1;
430
338
    goto decrypt_end;
431
339
  }
433
341
  *plaintext = NULL;
434
342
  while(true){
435
343
    plaintext_capacity = incbuffer(plaintext,
436
 
                                   (size_t)plaintext_length,
437
 
                                   plaintext_capacity);
 
344
                                      (size_t)plaintext_length,
 
345
                                      plaintext_capacity);
438
346
    if(plaintext_capacity == 0){
439
 
      perror_plus("incbuffer");
440
 
      plaintext_length = -1;
441
 
      goto decrypt_end;
 
347
        perror("incbuffer");
 
348
        plaintext_length = -1;
 
349
        goto decrypt_end;
442
350
    }
443
351
    
444
352
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
449
357
      break;
450
358
    }
451
359
    if(ret < 0){
452
 
      perror_plus("gpgme_data_read");
 
360
      perror("gpgme_data_read");
453
361
      plaintext_length = -1;
454
362
      goto decrypt_end;
455
363
    }
457
365
  }
458
366
  
459
367
  if(debug){
460
 
    fprintf(stderr, "Mandos plugin mandos-client: "
461
 
            "Decrypted password is: ");
 
368
    fprintf(stderr, "Decrypted password is: ");
462
369
    for(ssize_t i = 0; i < plaintext_length; i++){
463
370
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
464
371
    }
486
393
/* GnuTLS log function callback */
487
394
static void debuggnutls(__attribute__((unused)) int level,
488
395
                        const char* string){
489
 
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
 
396
  fprintf(stderr, "GnuTLS: %s", string);
490
397
}
491
398
 
492
399
static int init_gnutls_global(const char *pubkeyfilename,
494
401
  int ret;
495
402
  
496
403
  if(debug){
497
 
    fprintf(stderr, "Mandos plugin mandos-client: "
498
 
            "Initializing GnuTLS\n");
 
404
    fprintf(stderr, "Initializing GnuTLS\n");
499
405
  }
500
406
  
501
407
  ret = gnutls_global_init();
502
408
  if(ret != GNUTLS_E_SUCCESS){
503
 
    fprintf(stderr, "Mandos plugin mandos-client: "
504
 
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
 
409
    fprintf(stderr, "GnuTLS global_init: %s\n",
 
410
            safer_gnutls_strerror(ret));
505
411
    return -1;
506
412
  }
507
413
  
514
420
  }
515
421
  
516
422
  /* OpenPGP credentials */
517
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
423
  gnutls_certificate_allocate_credentials(&mc.cred);
518
424
  if(ret != GNUTLS_E_SUCCESS){
519
 
    fprintf(stderr, "Mandos plugin mandos-client: "
520
 
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
 
425
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
 
426
                                                    from
 
427
                                                    -Wunreachable-code
 
428
                                                 */
 
429
            safer_gnutls_strerror(ret));
521
430
    gnutls_global_deinit();
522
431
    return -1;
523
432
  }
524
433
  
525
434
  if(debug){
526
 
    fprintf(stderr, "Mandos plugin mandos-client: "
527
 
            "Attempting to use OpenPGP public key %s and"
 
435
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
528
436
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
529
437
            seckeyfilename);
530
438
  }
534
442
     GNUTLS_OPENPGP_FMT_BASE64);
535
443
  if(ret != GNUTLS_E_SUCCESS){
536
444
    fprintf(stderr,
537
 
            "Mandos plugin mandos-client: "
538
445
            "Error[%d] while reading the OpenPGP key pair ('%s',"
539
446
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
540
 
    fprintf(stderr, "Mandos plugin mandos-client: "
541
 
            "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
 
447
    fprintf(stderr, "The GnuTLS error is: %s\n",
 
448
            safer_gnutls_strerror(ret));
542
449
    goto globalfail;
543
450
  }
544
451
  
545
452
  /* GnuTLS server initialization */
546
453
  ret = gnutls_dh_params_init(&mc.dh_params);
547
454
  if(ret != GNUTLS_E_SUCCESS){
548
 
    fprintf(stderr, "Mandos plugin mandos-client: "
549
 
            "Error in GnuTLS DH parameter initialization:"
 
455
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
550
456
            " %s\n", safer_gnutls_strerror(ret));
551
457
    goto globalfail;
552
458
  }
553
459
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
554
460
  if(ret != GNUTLS_E_SUCCESS){
555
 
    fprintf(stderr, "Mandos plugin mandos-client: "
556
 
            "Error in GnuTLS prime generation: %s\n",
 
461
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
557
462
            safer_gnutls_strerror(ret));
558
463
    goto globalfail;
559
464
  }
580
485
    }
581
486
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
582
487
  if(ret != GNUTLS_E_SUCCESS){
583
 
    fprintf(stderr, "Mandos plugin mandos-client: "
584
 
            "Error in GnuTLS session initialization: %s\n",
 
488
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
585
489
            safer_gnutls_strerror(ret));
586
490
  }
587
491
  
595
499
      }
596
500
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
597
501
    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));
 
502
      fprintf(stderr, "Syntax error at: %s\n", err);
 
503
      fprintf(stderr, "GnuTLS error: %s\n",
 
504
              safer_gnutls_strerror(ret));
602
505
      gnutls_deinit(*session);
603
506
      return -1;
604
507
    }
613
516
    }
614
517
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
615
518
  if(ret != GNUTLS_E_SUCCESS){
616
 
    fprintf(stderr, "Mandos plugin mandos-client: "
617
 
            "Error setting GnuTLS credentials: %s\n",
 
519
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
618
520
            safer_gnutls_strerror(ret));
619
521
    gnutls_deinit(*session);
620
522
    return -1;
651
553
  gnutls_session_t session;
652
554
  int pf;                       /* Protocol family */
653
555
  
654
 
  errno = 0;
655
 
  
656
556
  if(quit_now){
657
 
    errno = EINTR;
658
557
    return -1;
659
558
  }
660
559
  
666
565
    pf = PF_INET;
667
566
    break;
668
567
  default:
669
 
    fprintf(stderr, "Mandos plugin mandos-client: "
670
 
            "Bad address family: %d\n", af);
671
 
    errno = EINVAL;
 
568
    fprintf(stderr, "Bad address family: %d\n", af);
672
569
    return -1;
673
570
  }
674
571
  
678
575
  }
679
576
  
680
577
  if(debug){
681
 
    fprintf(stderr, "Mandos plugin mandos-client: "
682
 
            "Setting up a TCP connection to %s, port %" PRIu16
 
578
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
683
579
            "\n", ip, port);
684
580
  }
685
581
  
686
582
  tcp_sd = socket(pf, SOCK_STREAM, 0);
687
583
  if(tcp_sd < 0){
688
 
    int e = errno;
689
 
    perror_plus("socket");
690
 
    errno = e;
 
584
    perror("socket");
691
585
    goto mandos_end;
692
586
  }
693
587
  
694
588
  if(quit_now){
695
 
    errno = EINTR;
696
589
    goto mandos_end;
697
590
  }
698
591
  
705
598
    ret = inet_pton(af, ip, &to.in.sin_addr);
706
599
  }
707
600
  if(ret < 0 ){
708
 
    int e = errno;
709
 
    perror_plus("inet_pton");
710
 
    errno = e;
 
601
    perror("inet_pton");
711
602
    goto mandos_end;
712
603
  }
713
604
  if(ret == 0){
714
 
    int e = errno;
715
 
    fprintf(stderr, "Mandos plugin mandos-client: "
716
 
            "Bad address: %s\n", ip);
717
 
    errno = e;
 
605
    fprintf(stderr, "Bad address: %s\n", ip);
718
606
    goto mandos_end;
719
607
  }
720
608
  if(af == AF_INET6){
724
612
    
725
613
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
726
614
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
727
 
                                -Wunreachable-code*/
 
615
                              -Wunreachable-code*/
728
616
      if(if_index == AVAHI_IF_UNSPEC){
729
 
        fprintf(stderr, "Mandos plugin mandos-client: "
730
 
                "An IPv6 link-local address is incomplete"
 
617
        fprintf(stderr, "An IPv6 link-local address is incomplete"
731
618
                " without a network interface\n");
732
 
        errno = EINVAL;
733
619
        goto mandos_end;
734
620
      }
735
621
      /* Set the network interface number as scope */
742
628
  }
743
629
  
744
630
  if(quit_now){
745
 
    errno = EINTR;
746
631
    goto mandos_end;
747
632
  }
748
633
  
750
635
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
751
636
      char interface[IF_NAMESIZE];
752
637
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
753
 
        perror_plus("if_indextoname");
 
638
        perror("if_indextoname");
754
639
      } else {
755
 
        fprintf(stderr, "Mandos plugin mandos-client: "
756
 
                "Connection to: %s%%%s, port %" PRIu16 "\n",
 
640
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
757
641
                ip, interface, port);
758
642
      }
759
643
    } else {
760
 
      fprintf(stderr, "Mandos plugin mandos-client: "
761
 
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
 
644
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
645
              port);
762
646
    }
763
647
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
764
648
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
771
655
                        sizeof(addrstr));
772
656
    }
773
657
    if(pcret == NULL){
774
 
      perror_plus("inet_ntop");
 
658
      perror("inet_ntop");
775
659
    } else {
776
660
      if(strcmp(addrstr, ip) != 0){
777
 
        fprintf(stderr, "Mandos plugin mandos-client: "
778
 
                "Canonical address form: %s\n", addrstr);
 
661
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
779
662
      }
780
663
    }
781
664
  }
782
665
  
783
666
  if(quit_now){
784
 
    errno = EINTR;
785
667
    goto mandos_end;
786
668
  }
787
669
  
791
673
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
792
674
  }
793
675
  if(ret < 0){
794
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
795
 
      int e = errno;
796
 
      perror_plus("connect");
797
 
      errno = e;
798
 
    }
 
676
    perror("connect");
799
677
    goto mandos_end;
800
678
  }
801
679
  
802
680
  if(quit_now){
803
 
    errno = EINTR;
804
681
    goto mandos_end;
805
682
  }
806
683
  
809
686
  while(true){
810
687
    size_t out_size = strlen(out);
811
688
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
812
 
                                        out_size - written));
 
689
                                   out_size - written));
813
690
    if(ret == -1){
814
 
      int e = errno;
815
 
      perror_plus("write");
816
 
      errno = e;
 
691
      perror("write");
817
692
      goto mandos_end;
818
693
    }
819
694
    written += (size_t)ret;
829
704
    }
830
705
  
831
706
    if(quit_now){
832
 
      errno = EINTR;
833
707
      goto mandos_end;
834
708
    }
835
709
  }
836
710
  
837
711
  if(debug){
838
 
    fprintf(stderr, "Mandos plugin mandos-client: "
839
 
            "Establishing TLS session with %s\n", ip);
 
712
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
840
713
  }
841
714
  
842
715
  if(quit_now){
843
 
    errno = EINTR;
844
716
    goto mandos_end;
845
717
  }
846
718
  
847
 
  /* Spurious warning from -Wint-to-pointer-cast */
848
719
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
849
720
  
850
721
  if(quit_now){
851
 
    errno = EINTR;
852
722
    goto mandos_end;
853
723
  }
854
724
  
855
725
  do {
856
726
    ret = gnutls_handshake(session);
857
727
    if(quit_now){
858
 
      errno = EINTR;
859
728
      goto mandos_end;
860
729
    }
861
730
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
862
731
  
863
732
  if(ret != GNUTLS_E_SUCCESS){
864
733
    if(debug){
865
 
      fprintf(stderr, "Mandos plugin mandos-client: "
866
 
              "*** GnuTLS Handshake failed ***\n");
 
734
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
867
735
      gnutls_perror(ret);
868
736
    }
869
 
    errno = EPROTO;
870
737
    goto mandos_end;
871
738
  }
872
739
  
873
740
  /* Read OpenPGP packet that contains the wanted password */
874
741
  
875
742
  if(debug){
876
 
    fprintf(stderr, "Mandos plugin mandos-client: "
877
 
            "Retrieving OpenPGP encrypted password from %s\n", ip);
 
743
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
744
            ip);
878
745
  }
879
746
  
880
747
  while(true){
881
748
    
882
749
    if(quit_now){
883
 
      errno = EINTR;
884
750
      goto mandos_end;
885
751
    }
886
752
    
887
753
    buffer_capacity = incbuffer(&buffer, buffer_length,
888
 
                                buffer_capacity);
 
754
                                   buffer_capacity);
889
755
    if(buffer_capacity == 0){
890
 
      int e = errno;
891
 
      perror_plus("incbuffer");
892
 
      errno = e;
 
756
      perror("incbuffer");
893
757
      goto mandos_end;
894
758
    }
895
759
    
896
760
    if(quit_now){
897
 
      errno = EINTR;
898
761
      goto mandos_end;
899
762
    }
900
763
    
913
776
          ret = gnutls_handshake(session);
914
777
          
915
778
          if(quit_now){
916
 
            errno = EINTR;
917
779
            goto mandos_end;
918
780
          }
919
781
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
920
782
        if(ret < 0){
921
 
          fprintf(stderr, "Mandos plugin mandos-client: "
922
 
                  "*** GnuTLS Re-handshake failed ***\n");
 
783
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
923
784
          gnutls_perror(ret);
924
 
          errno = EPROTO;
925
785
          goto mandos_end;
926
786
        }
927
787
        break;
928
788
      default:
929
 
        fprintf(stderr, "Mandos plugin mandos-client: "
930
 
                "Unknown error while reading data from"
 
789
        fprintf(stderr, "Unknown error while reading data from"
931
790
                " encrypted session with Mandos server\n");
932
791
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
933
 
        errno = EIO;
934
792
        goto mandos_end;
935
793
      }
936
794
    } else {
939
797
  }
940
798
  
941
799
  if(debug){
942
 
    fprintf(stderr, "Mandos plugin mandos-client: "
943
 
            "Closing TLS session\n");
 
800
    fprintf(stderr, "Closing TLS session\n");
944
801
  }
945
802
  
946
803
  if(quit_now){
947
 
    errno = EINTR;
948
804
    goto mandos_end;
949
805
  }
950
806
  
951
807
  do {
952
808
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
953
809
    if(quit_now){
954
 
      errno = EINTR;
955
810
      goto mandos_end;
956
811
    }
957
812
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
958
813
  
959
814
  if(buffer_length > 0){
960
815
    ssize_t decrypted_buffer_size;
961
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
 
816
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
817
                                               buffer_length,
962
818
                                               &decrypted_buffer);
963
819
    if(decrypted_buffer_size >= 0){
964
820
      
965
821
      written = 0;
966
822
      while(written < (size_t) decrypted_buffer_size){
967
823
        if(quit_now){
968
 
          errno = EINTR;
969
824
          goto mandos_end;
970
825
        }
971
826
        
973
828
                          (size_t)decrypted_buffer_size - written,
974
829
                          stdout);
975
830
        if(ret == 0 and ferror(stdout)){
976
 
          int e = errno;
977
831
          if(debug){
978
 
            fprintf(stderr, "Mandos plugin mandos-client: "
979
 
                    "Error writing encrypted data: %s\n",
 
832
            fprintf(stderr, "Error writing encrypted data: %s\n",
980
833
                    strerror(errno));
981
834
          }
982
 
          errno = e;
983
835
          goto mandos_end;
984
836
        }
985
837
        written += (size_t)ret;
991
843
  /* Shutdown procedure */
992
844
  
993
845
 mandos_end:
994
 
  {
995
 
    int e = errno;
996
 
    free(decrypted_buffer);
997
 
    free(buffer);
998
 
    if(tcp_sd >= 0){
999
 
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
1000
 
    }
1001
 
    if(ret == -1){
1002
 
      if(e == 0){
1003
 
        e = errno;
1004
 
      }
1005
 
      perror_plus("close");
1006
 
    }
1007
 
    gnutls_deinit(session);
1008
 
    errno = e;
1009
 
    if(quit_now){
1010
 
      errno = EINTR;
1011
 
      retval = -1;
1012
 
    }
 
846
  free(decrypted_buffer);
 
847
  free(buffer);
 
848
  if(tcp_sd >= 0){
 
849
    ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
850
  }
 
851
  if(ret == -1){
 
852
    perror("close");
 
853
  }
 
854
  gnutls_deinit(session);
 
855
  if(quit_now){
 
856
    retval = -1;
1013
857
  }
1014
858
  return retval;
1015
859
}
1040
884
  switch(event){
1041
885
  default:
1042
886
  case AVAHI_RESOLVER_FAILURE:
1043
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1044
 
            "(Avahi Resolver) Failed to resolve service '%s'"
 
887
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
1045
888
            " of type '%s' in domain '%s': %s\n", name, type, domain,
1046
889
            avahi_strerror(avahi_server_errno(mc.server)));
1047
890
    break;
1051
894
      char ip[AVAHI_ADDRESS_STR_MAX];
1052
895
      avahi_address_snprint(ip, sizeof(ip), address);
1053
896
      if(debug){
1054
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1055
 
                "Mandos server \"%s\" found on %s (%s, %"
 
897
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
1056
898
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1057
899
                ip, (intmax_t)interface, port);
1058
900
      }
1060
902
                                           avahi_proto_to_af(proto));
1061
903
      if(ret == 0){
1062
904
        avahi_simple_poll_quit(mc.simple_poll);
1063
 
      } else {
1064
 
        ret = add_server(ip, port, interface,
1065
 
                         avahi_proto_to_af(proto));
1066
905
      }
1067
906
    }
1068
907
  }
1092
931
  default:
1093
932
  case AVAHI_BROWSER_FAILURE:
1094
933
    
1095
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1096
 
            "(Avahi browser) %s\n",
 
934
    fprintf(stderr, "(Avahi browser) %s\n",
1097
935
            avahi_strerror(avahi_server_errno(mc.server)));
1098
936
    avahi_simple_poll_quit(mc.simple_poll);
1099
937
    return;
1107
945
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1108
946
                                    name, type, domain, protocol, 0,
1109
947
                                    resolve_callback, NULL) == NULL)
1110
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1111
 
              "Avahi: Failed to resolve service '%s': %s\n",
 
948
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
1112
949
              name, avahi_strerror(avahi_server_errno(mc.server)));
1113
950
    break;
1114
951
    
1118
955
  case AVAHI_BROWSER_ALL_FOR_NOW:
1119
956
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1120
957
    if(debug){
1121
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1122
 
              "No Mandos server found, still searching...\n");
 
958
      fprintf(stderr, "No Mandos server found, still searching...\n");
1123
959
    }
1124
960
    break;
1125
961
  }
1126
962
}
1127
963
 
1128
 
/* Signal handler that stops main loop after SIGTERM */
 
964
/* stop main loop after sigterm has been called */
1129
965
static void handle_sigterm(int sig){
1130
966
  if(quit_now){
1131
967
    return;
1133
969
  quit_now = 1;
1134
970
  signal_received = sig;
1135
971
  int old_errno = errno;
1136
 
  /* set main loop to exit */
1137
972
  if(mc.simple_poll != NULL){
1138
973
    avahi_simple_poll_quit(mc.simple_poll);
1139
974
  }
1140
975
  errno = old_errno;
1141
976
}
1142
977
 
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){
1154
 
    if(debug){
1155
 
      perror_plus("ioctl SIOCGIFFLAGS");
1156
 
    }
1157
 
    return false;
1158
 
  }
1159
 
  return true;
1160
 
}
1161
 
 
1162
 
bool good_flags(const char *ifname, const struct ifreq *ifr){
1163
 
  
1164
 
  /* Reject the loopback device */
1165
 
  if(ifr->ifr_flags & IFF_LOOPBACK){
1166
 
    if(debug){
1167
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1168
 
              "Rejecting loopback interface \"%s\"\n", ifname);
1169
 
    }
1170
 
    return false;
1171
 
  }
1172
 
  /* Accept point-to-point devices only if connect_to is specified */
1173
 
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1174
 
    if(debug){
1175
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1176
 
              "Accepting point-to-point interface \"%s\"\n", ifname);
1177
 
    }
1178
 
    return true;
1179
 
  }
1180
 
  /* 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
 
  
1197
 
  /* Accept this device */
1198
 
  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
 
  }
1419
 
}
1420
 
 
1421
978
int main(int argc, char *argv[]){
1422
979
  AvahiSServiceBrowser *sb = NULL;
1423
980
  int error;
1425
982
  intmax_t tmpmax;
1426
983
  char *tmp;
1427
984
  int exitcode = EXIT_SUCCESS;
1428
 
  const char *interface = "";
 
985
  const char *interface = "eth0";
1429
986
  struct ifreq network;
1430
987
  int sd = -1;
1431
988
  bool take_down_interface = false;
1432
989
  uid_t uid;
1433
990
  gid_t gid;
 
991
  char *connect_to = NULL;
1434
992
  char tempdir[] = "/tmp/mandosXXXXXX";
1435
993
  bool tempdir_created = false;
1436
994
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1440
998
  bool gnutls_initialized = false;
1441
999
  bool gpgme_initialized = false;
1442
1000
  float delay = 2.5f;
1443
 
  double retry_interval = 10; /* 10s between trying a server and
1444
 
                                 retrying the same server again */
1445
1001
  
1446
1002
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1447
1003
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1453
1009
  errno = 0;
1454
1010
  ret = setgid(gid);
1455
1011
  if(ret == -1){
1456
 
    perror_plus("setgid");
 
1012
    perror("setgid");
1457
1013
  }
1458
1014
  
1459
1015
  /* Lower user privileges (temporarily) */
1460
1016
  errno = 0;
1461
1017
  ret = seteuid(uid);
1462
1018
  if(ret == -1){
1463
 
    perror_plus("seteuid");
 
1019
    perror("seteuid");
1464
1020
  }
1465
1021
  
1466
1022
  if(quit_now){
1501
1057
        .arg = "SECONDS",
1502
1058
        .doc = "Maximum delay to wait for interface startup",
1503
1059
        .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
1060
      /*
1513
1061
       * These reproduce what we would get without ARGP_NO_HELP
1514
1062
       */
1558
1106
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1559
1107
          argp_error(state, "Bad delay");
1560
1108
        }
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
1109
        break;
1573
1110
        /*
1574
1111
         * These reproduce what we would get without ARGP_NO_HELP
1581
1118
        argp_state_help(state, state->out_stream,
1582
1119
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1583
1120
      case 'V':                 /* --version */
1584
 
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
1585
1121
        fprintf(state->out_stream, "%s\n", argp_program_version);
1586
1122
        exit(argp_err_exit_status);
1587
1123
        break;
1603
1139
    case ENOMEM:
1604
1140
    default:
1605
1141
      errno = ret;
1606
 
      perror_plus("argp_parse");
 
1142
      perror("argp_parse");
1607
1143
      exitcode = EX_OSERR;
1608
1144
      goto end;
1609
1145
    case EINVAL:
1611
1147
      goto end;
1612
1148
    }
1613
1149
  }
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
1150
  
1774
1151
  if(not debug){
1775
1152
    avahi_set_log_function(empty_log);
1776
1153
  }
1777
1154
  
1778
 
  if(interface[0] == '\0'){
1779
 
    struct dirent **direntries;
1780
 
    /* First look for interfaces that are up */
1781
 
    ret = scandir(sys_class_net, &direntries, up_interface,
1782
 
                  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
 
    if(ret >= 1){
1790
 
      /* Pick the first interface returned */
1791
 
      interface = strdup(direntries[0]->d_name);
1792
 
      if(debug){
1793
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1794
 
                "Using interface \"%s\"\n", interface);
1795
 
      }
1796
 
      if(interface == NULL){
1797
 
        perror_plus("malloc");
1798
 
        free(direntries);
1799
 
        exitcode = EXIT_FAILURE;
1800
 
        goto end;
1801
 
      }
1802
 
      free(direntries);
1803
 
    } else {
1804
 
      free(direntries);
1805
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1806
 
              "Could not find a network interface\n");
1807
 
      exitcode = EXIT_FAILURE;
1808
 
      goto end;
1809
 
    }
1810
 
  }
1811
 
  
1812
1155
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1813
1156
     from the signal handler */
1814
1157
  /* Initialize the pseudo-RNG for Avahi */
1815
1158
  srand((unsigned int) time(NULL));
1816
1159
  mc.simple_poll = avahi_simple_poll_new();
1817
1160
  if(mc.simple_poll == NULL){
1818
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1819
 
            "Avahi: Failed to create simple poll object.\n");
1820
 
    exitcode = EX_UNAVAILABLE;
 
1161
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1162
    exitcode = EXIT_FAILURE;
1821
1163
    goto end;
1822
1164
  }
1823
1165
  
1824
1166
  sigemptyset(&sigterm_action.sa_mask);
1825
1167
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1826
1168
  if(ret == -1){
1827
 
    perror_plus("sigaddset");
1828
 
    exitcode = EX_OSERR;
 
1169
    perror("sigaddset");
 
1170
    exitcode = EXIT_FAILURE;
1829
1171
    goto end;
1830
1172
  }
1831
1173
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1832
1174
  if(ret == -1){
1833
 
    perror_plus("sigaddset");
1834
 
    exitcode = EX_OSERR;
 
1175
    perror("sigaddset");
 
1176
    exitcode = EXIT_FAILURE;
1835
1177
    goto end;
1836
1178
  }
1837
1179
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1838
1180
  if(ret == -1){
1839
 
    perror_plus("sigaddset");
1840
 
    exitcode = EX_OSERR;
 
1181
    perror("sigaddset");
 
1182
    exitcode = EXIT_FAILURE;
1841
1183
    goto end;
1842
1184
  }
1843
1185
  /* Need to check if the handler is SIG_IGN before handling:
1846
1188
  */
1847
1189
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1848
1190
  if(ret == -1){
1849
 
    perror_plus("sigaction");
1850
 
    return EX_OSERR;
 
1191
    perror("sigaction");
 
1192
    return EXIT_FAILURE;
1851
1193
  }
1852
1194
  if(old_sigterm_action.sa_handler != SIG_IGN){
1853
1195
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1854
1196
    if(ret == -1){
1855
 
      perror_plus("sigaction");
1856
 
      exitcode = EX_OSERR;
 
1197
      perror("sigaction");
 
1198
      exitcode = EXIT_FAILURE;
1857
1199
      goto end;
1858
1200
    }
1859
1201
  }
1860
1202
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1861
1203
  if(ret == -1){
1862
 
    perror_plus("sigaction");
1863
 
    return EX_OSERR;
 
1204
    perror("sigaction");
 
1205
    return EXIT_FAILURE;
1864
1206
  }
1865
1207
  if(old_sigterm_action.sa_handler != SIG_IGN){
1866
1208
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1867
1209
    if(ret == -1){
1868
 
      perror_plus("sigaction");
1869
 
      exitcode = EX_OSERR;
 
1210
      perror("sigaction");
 
1211
      exitcode = EXIT_FAILURE;
1870
1212
      goto end;
1871
1213
    }
1872
1214
  }
1873
1215
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1874
1216
  if(ret == -1){
1875
 
    perror_plus("sigaction");
1876
 
    return EX_OSERR;
 
1217
    perror("sigaction");
 
1218
    return EXIT_FAILURE;
1877
1219
  }
1878
1220
  if(old_sigterm_action.sa_handler != SIG_IGN){
1879
1221
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1880
1222
    if(ret == -1){
1881
 
      perror_plus("sigaction");
1882
 
      exitcode = EX_OSERR;
 
1223
      perror("sigaction");
 
1224
      exitcode = EXIT_FAILURE;
1883
1225
      goto end;
1884
1226
    }
1885
1227
  }
1886
1228
  
1887
1229
  /* If the interface is down, bring it up */
1888
 
  if(strcmp(interface, "none") != 0){
 
1230
  if(interface[0] != '\0'){
1889
1231
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1890
1232
    if(if_index == 0){
1891
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1892
 
              "No such interface: \"%s\"\n", interface);
1893
 
      exitcode = EX_UNAVAILABLE;
 
1233
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1234
      exitcode = EXIT_FAILURE;
1894
1235
      goto end;
1895
1236
    }
1896
1237
    
1902
1243
    errno = 0;
1903
1244
    ret = seteuid(0);
1904
1245
    if(ret == -1){
1905
 
      perror_plus("seteuid");
 
1246
      perror("seteuid");
1906
1247
    }
1907
1248
    
1908
1249
#ifdef __linux__
1912
1253
    bool restore_loglevel = true;
1913
1254
    if(ret == -1){
1914
1255
      restore_loglevel = false;
1915
 
      perror_plus("klogctl");
 
1256
      perror("klogctl");
1916
1257
    }
1917
1258
#endif  /* __linux__ */
1918
1259
    
1919
1260
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1920
1261
    if(sd < 0){
1921
 
      perror_plus("socket");
1922
 
      exitcode = EX_OSERR;
 
1262
      perror("socket");
 
1263
      exitcode = EXIT_FAILURE;
1923
1264
#ifdef __linux__
1924
1265
      if(restore_loglevel){
1925
1266
        ret = klogctl(7, NULL, 0);
1926
1267
        if(ret == -1){
1927
 
          perror_plus("klogctl");
 
1268
          perror("klogctl");
1928
1269
        }
1929
1270
      }
1930
1271
#endif  /* __linux__ */
1932
1273
      errno = 0;
1933
1274
      ret = seteuid(uid);
1934
1275
      if(ret == -1){
1935
 
        perror_plus("seteuid");
 
1276
        perror("seteuid");
1936
1277
      }
1937
1278
      goto end;
1938
1279
    }
1939
1280
    strcpy(network.ifr_name, interface);
1940
1281
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1941
1282
    if(ret == -1){
1942
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1283
      perror("ioctl SIOCGIFFLAGS");
1943
1284
#ifdef __linux__
1944
1285
      if(restore_loglevel){
1945
1286
        ret = klogctl(7, NULL, 0);
1946
1287
        if(ret == -1){
1947
 
          perror_plus("klogctl");
 
1288
          perror("klogctl");
1948
1289
        }
1949
1290
      }
1950
1291
#endif  /* __linux__ */
1951
 
      exitcode = EX_OSERR;
 
1292
      exitcode = EXIT_FAILURE;
1952
1293
      /* Lower privileges */
1953
1294
      errno = 0;
1954
1295
      ret = seteuid(uid);
1955
1296
      if(ret == -1){
1956
 
        perror_plus("seteuid");
 
1297
        perror("seteuid");
1957
1298
      }
1958
1299
      goto end;
1959
1300
    }
1963
1304
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1964
1305
      if(ret == -1){
1965
1306
        take_down_interface = false;
1966
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1967
 
        exitcode = EX_OSERR;
 
1307
        perror("ioctl SIOCSIFFLAGS");
 
1308
        exitcode = EXIT_FAILURE;
1968
1309
#ifdef __linux__
1969
1310
        if(restore_loglevel){
1970
1311
          ret = klogctl(7, NULL, 0);
1971
1312
          if(ret == -1){
1972
 
            perror_plus("klogctl");
 
1313
            perror("klogctl");
1973
1314
          }
1974
1315
        }
1975
1316
#endif  /* __linux__ */
1977
1318
        errno = 0;
1978
1319
        ret = seteuid(uid);
1979
1320
        if(ret == -1){
1980
 
          perror_plus("seteuid");
 
1321
          perror("seteuid");
1981
1322
        }
1982
1323
        goto end;
1983
1324
      }
1984
1325
    }
1985
 
    /* Sleep checking until interface is running.
1986
 
       Check every 0.25s, up to total time of delay */
 
1326
    /* sleep checking until interface is running */
1987
1327
    for(int i=0; i < delay * 4; i++){
1988
1328
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1989
1329
      if(ret == -1){
1990
 
        perror_plus("ioctl SIOCGIFFLAGS");
 
1330
        perror("ioctl SIOCGIFFLAGS");
1991
1331
      } else if(network.ifr_flags & IFF_RUNNING){
1992
1332
        break;
1993
1333
      }
1994
1334
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1995
1335
      ret = nanosleep(&sleeptime, NULL);
1996
1336
      if(ret == -1 and errno != EINTR){
1997
 
        perror_plus("nanosleep");
 
1337
        perror("nanosleep");
1998
1338
      }
1999
1339
    }
2000
1340
    if(not take_down_interface){
2001
1341
      /* We won't need the socket anymore */
2002
1342
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2003
1343
      if(ret == -1){
2004
 
        perror_plus("close");
 
1344
        perror("close");
2005
1345
      }
2006
1346
    }
2007
1347
#ifdef __linux__
2009
1349
      /* Restores kernel loglevel to default */
2010
1350
      ret = klogctl(7, NULL, 0);
2011
1351
      if(ret == -1){
2012
 
        perror_plus("klogctl");
 
1352
        perror("klogctl");
2013
1353
      }
2014
1354
    }
2015
1355
#endif  /* __linux__ */
2019
1359
      /* Lower privileges */
2020
1360
      ret = seteuid(uid);
2021
1361
      if(ret == -1){
2022
 
        perror_plus("seteuid");
 
1362
        perror("seteuid");
2023
1363
      }
2024
1364
    } else {
2025
1365
      /* Lower privileges permanently */
2026
1366
      ret = setuid(uid);
2027
1367
      if(ret == -1){
2028
 
        perror_plus("setuid");
 
1368
        perror("setuid");
2029
1369
      }
2030
1370
    }
2031
1371
  }
2036
1376
  
2037
1377
  ret = init_gnutls_global(pubkey, seckey);
2038
1378
  if(ret == -1){
2039
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2040
 
            "init_gnutls_global failed\n");
2041
 
    exitcode = EX_UNAVAILABLE;
 
1379
    fprintf(stderr, "init_gnutls_global failed\n");
 
1380
    exitcode = EXIT_FAILURE;
2042
1381
    goto end;
2043
1382
  } else {
2044
1383
    gnutls_initialized = true;
2048
1387
    goto end;
2049
1388
  }
2050
1389
  
 
1390
  tempdir_created = true;
2051
1391
  if(mkdtemp(tempdir) == NULL){
2052
 
    perror_plus("mkdtemp");
 
1392
    tempdir_created = false;
 
1393
    perror("mkdtemp");
2053
1394
    goto end;
2054
1395
  }
2055
 
  tempdir_created = true;
2056
1396
  
2057
1397
  if(quit_now){
2058
1398
    goto end;
2059
1399
  }
2060
1400
  
2061
1401
  if(not init_gpgme(pubkey, seckey, tempdir)){
2062
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2063
 
            "init_gpgme failed\n");
2064
 
    exitcode = EX_UNAVAILABLE;
 
1402
    fprintf(stderr, "init_gpgme failed\n");
 
1403
    exitcode = EXIT_FAILURE;
2065
1404
    goto end;
2066
1405
  } else {
2067
1406
    gpgme_initialized = true;
2076
1415
    /* (Mainly meant for debugging) */
2077
1416
    char *address = strrchr(connect_to, ':');
2078
1417
    if(address == NULL){
2079
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2080
 
              "No colon in address\n");
2081
 
      exitcode = EX_USAGE;
 
1418
      fprintf(stderr, "No colon in address\n");
 
1419
      exitcode = EXIT_FAILURE;
2082
1420
      goto end;
2083
1421
    }
2084
1422
    
2091
1429
    tmpmax = strtoimax(address+1, &tmp, 10);
2092
1430
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2093
1431
       or tmpmax != (uint16_t)tmpmax){
2094
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2095
 
              "Bad port number\n");
2096
 
      exitcode = EX_USAGE;
 
1432
      fprintf(stderr, "Bad port number\n");
 
1433
      exitcode = EXIT_FAILURE;
2097
1434
      goto end;
2098
1435
    }
2099
1436
  
2103
1440
    
2104
1441
    port = (uint16_t)tmpmax;
2105
1442
    *address = '\0';
 
1443
    address = connect_to;
2106
1444
    /* Colon in address indicates IPv6 */
2107
1445
    int af;
2108
 
    if(strchr(connect_to, ':') != NULL){
 
1446
    if(strchr(address, ':') != NULL){
2109
1447
      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
1448
    } else {
2117
1449
      af = AF_INET;
2118
1450
    }
2119
 
    address = connect_to;
2120
1451
    
2121
1452
    if(quit_now){
2122
1453
      goto end;
2123
1454
    }
2124
1455
    
2125
 
    while(not quit_now){
2126
 
      ret = start_mandos_communication(address, port, if_index, af);
2127
 
      if(quit_now or ret == 0){
2128
 
        break;
2129
 
      }
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
 
    
2137
 
    if (not quit_now){
 
1456
    ret = start_mandos_communication(address, port, if_index, af);
 
1457
    if(ret < 0){
 
1458
      exitcode = EXIT_FAILURE;
 
1459
    } else {
2138
1460
      exitcode = EXIT_SUCCESS;
2139
1461
    }
2140
 
    
2141
1462
    goto end;
2142
1463
  }
2143
1464
  
2165
1486
  
2166
1487
  /* Check if creating the Avahi server object succeeded */
2167
1488
  if(mc.server == NULL){
2168
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2169
 
            "Failed to create Avahi server: %s\n",
 
1489
    fprintf(stderr, "Failed to create Avahi server: %s\n",
2170
1490
            avahi_strerror(error));
2171
 
    exitcode = EX_UNAVAILABLE;
 
1491
    exitcode = EXIT_FAILURE;
2172
1492
    goto end;
2173
1493
  }
2174
1494
  
2181
1501
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2182
1502
                                   NULL, 0, browse_callback, NULL);
2183
1503
  if(sb == NULL){
2184
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2185
 
            "Failed to create service browser: %s\n",
 
1504
    fprintf(stderr, "Failed to create service browser: %s\n",
2186
1505
            avahi_strerror(avahi_server_errno(mc.server)));
2187
 
    exitcode = EX_UNAVAILABLE;
 
1506
    exitcode = EXIT_FAILURE;
2188
1507
    goto end;
2189
1508
  }
2190
1509
  
2195
1514
  /* Run the main loop */
2196
1515
  
2197
1516
  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
 
  }
 
1517
    fprintf(stderr, "Starting Avahi loop search\n");
 
1518
  }
 
1519
  
 
1520
  avahi_simple_poll_loop(mc.simple_poll);
2209
1521
  
2210
1522
 end:
2211
1523
  
2212
1524
  if(debug){
2213
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2214
 
            "%s exiting\n", argv[0]);
 
1525
    fprintf(stderr, "%s exiting\n", argv[0]);
2215
1526
  }
2216
1527
  
2217
1528
  /* Cleanup things */
2233
1544
  if(gpgme_initialized){
2234
1545
    gpgme_release(mc.ctx);
2235
1546
  }
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
1547
  
2250
1548
  /* Take down the network interface */
2251
1549
  if(take_down_interface){
2253
1551
    errno = 0;
2254
1552
    ret = seteuid(0);
2255
1553
    if(ret == -1){
2256
 
      perror_plus("seteuid");
 
1554
      perror("seteuid");
2257
1555
    }
2258
1556
    if(geteuid() == 0){
2259
1557
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2260
1558
      if(ret == -1){
2261
 
        perror_plus("ioctl SIOCGIFFLAGS");
2262
 
      } else if(network.ifr_flags & IFF_UP){
 
1559
        perror("ioctl SIOCGIFFLAGS");
 
1560
      } else if(network.ifr_flags & IFF_UP) {
2263
1561
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2264
1562
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2265
1563
        if(ret == -1){
2266
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1564
          perror("ioctl SIOCSIFFLAGS");
2267
1565
        }
2268
1566
      }
2269
1567
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2270
1568
      if(ret == -1){
2271
 
        perror_plus("close");
 
1569
        perror("close");
2272
1570
      }
2273
1571
      /* Lower privileges permanently */
2274
1572
      errno = 0;
2275
1573
      ret = setuid(uid);
2276
1574
      if(ret == -1){
2277
 
        perror_plus("setuid");
 
1575
        perror("setuid");
2278
1576
      }
2279
1577
    }
2280
1578
  }
2281
1579
  
2282
 
  /* Removes the GPGME temp directory and all files inside */
 
1580
  /* Removes the temp directory used by GPGME */
2283
1581
  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];
 
1582
    DIR *d;
 
1583
    struct dirent *direntry;
 
1584
    d = opendir(tempdir);
 
1585
    if(d == NULL){
 
1586
      if(errno != ENOENT){
 
1587
        perror("opendir");
 
1588
      }
 
1589
    } else {
 
1590
      while(true){
 
1591
        direntry = readdir(d);
 
1592
        if(direntry == NULL){
 
1593
          break;
 
1594
        }
 
1595
        /* Skip "." and ".." */
 
1596
        if(direntry->d_name[0] == '.'
 
1597
           and (direntry->d_name[1] == '\0'
 
1598
                or (direntry->d_name[1] == '.'
 
1599
                    and direntry->d_name[2] == '\0'))){
 
1600
          continue;
 
1601
        }
2291
1602
        char *fullname = NULL;
2292
1603
        ret = asprintf(&fullname, "%s/%s", tempdir,
2293
1604
                       direntry->d_name);
2294
1605
        if(ret < 0){
2295
 
          perror_plus("asprintf");
 
1606
          perror("asprintf");
2296
1607
          continue;
2297
1608
        }
2298
1609
        ret = remove(fullname);
2299
1610
        if(ret == -1){
2300
 
          fprintf(stderr, "Mandos plugin mandos-client: "
2301
 
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
 
1611
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
1612
                  strerror(errno));
2302
1613
        }
2303
1614
        free(fullname);
2304
1615
      }
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");
 
1616
      closedir(d);
2311
1617
    }
2312
1618
    ret = rmdir(tempdir);
2313
1619
    if(ret == -1 and errno != ENOENT){
2314
 
      perror_plus("rmdir");
 
1620
      perror("rmdir");
2315
1621
    }
2316
1622
  }
2317
1623
  
2322
1628
                                            &old_sigterm_action,
2323
1629
                                            NULL));
2324
1630
    if(ret == -1){
2325
 
      perror_plus("sigaction");
 
1631
      perror("sigaction");
2326
1632
    }
2327
1633
    do {
2328
1634
      ret = raise(signal_received);
2329
1635
    } while(ret != 0 and errno == EINTR);
2330
1636
    if(ret != 0){
2331
 
      perror_plus("raise");
 
1637
      perror("raise");
2332
1638
      abort();
2333
1639
    }
2334
1640
    TEMP_FAILURE_RETRY(pause());