/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: teddy at bsnet
  • Date: 2010-08-16 19:00:59 UTC
  • mto: This revision was merged to the branch mainline in revision 420.
  • Revision ID: teddy@fukt.bsnet.se-20100816190059-69vvi27up95cgbbl
* Makefile (run-server, run-client): Add notices about harmless error
                                     messages.

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