/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2009-11-11 00:25:22 UTC
  • Revision ID: teddy@fukt.bsnet.se-20091111002522-t416fifqw46xaqn4
* debian/rules: Only set BROKEN_PIE if binutils is a specific range of
                versions.
* mandos-monitor (MandosClientWidget.keypress): Also accept "Ctrl-K"
                                                for removing client.
  (UserInterface.__init__): Use non-bold line drawing charater.
  (UserInterface.log_message): Scroll to bottom.
  (UserInterface.process_input): Also show help on "ESC" key.

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