/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

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

Show diffs side-by-side

added added

removed removed

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