/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 23:17:02 UTC
  • Revision ID: teddy@fukt.bsnet.se-20111224231702-1ffgu6r02p0bz9co
* plugins.d/splashy.c (error_plus): Check format string.
* plugins.d/askpass-fifo.c (error_plus): - '' -
* plugins.d/plymouth.c (error_plus): - '' -
* plugins.d/password-prompt.c (error_plus): - '' -
* plugins.d/usplash.c (error_plus): - '' -

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