/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: teddy at bsnet
  • Date: 2011-12-24 19:43:26 UTC
  • mto: This revision was merged to the branch mainline in revision 531.
  • Revision ID: teddy@fukt.bsnet.se-20111224194326-egfeyd0140t03xmf
* plugins.d/mandos-client.c (add_server): Return bool; all callers
                                          changed.
  (resolve_callback): Check return value from add_server().
  (main/parse_opt): Bug fix; Remove extra message on --version.

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