/mandos/release

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

« back to all changes in this revision

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

* plugin-runner.c (getplugin, add_environment, main): Handle EINTR
                                                      properly.

* plugins.d/mandos-client.c (start_mandos_communication): Bug fix:
  move out "decrypted_buffer_size" to where it is needed.

* plugins.d/splashy.c (termination_handler): Save signal received.
  (main): Check return value from "sigaddset()".

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