/mandos/release

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

« back to all changes in this revision

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

* init.d-mandos (Required-Start, Required-Stop): Bug fix: Added
                 "$syslog", thanks to Petter Reinholdtsen
                 <pere@hungry.com> (Debian bug #546928).

* initramfs-tools-script: Removed erroneous comment.

* plugins.d/askpass-fifo.c: Removed TEMP_FAILURE_RETRY since it is
                            not needed.

* plugins.d/mandos-client.c (main): Bug fix: Initialize
                                    "old_sigterm_action".

* plugins.d/splashy.c (main): Bug fix: really check return value from
                              "sigaddset".  Fix some warnings on
                              64-bit systems.

* plugins.d/usplash.c (termination_handler, main): Save received
                                                   signal and
                                                   re-raise it on
                                                   exit.
  (usplash_write): Do not close FIFO, instead, take an additional file
                   descriptor pointer to it and open only when needed
                   (all callers changed).  Abort immediately on EINTR.
                   Bug fix:  Add NUL byte on single-word commands.
                   Ignore "interrupted_by_signal".
  (makeprompt, find_usplash): New; broken out from "main()".
  (find_usplash): Bug fix: close /proc/<pid>/cmdline FD on error.
  (main): Reorganized to jump to a new "failure" label on any error.
          Bug fix: check return values from sigaddset.
          New variable "usplash_accessed" to flag if usplash(8) needs
          to be killed and restarted.  Removed the "an_error_occured"
          variable.

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