/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2012-02-21 21:27:14 UTC
  • mfrom: (237.6.1 nmu)
  • mto: (237.4.31 release)
  • mto: This revision was merged to the branch mainline in revision 560.
  • Revision ID: teddy@recompile.se-20120221212714-40iub281d4yvrk9r
Tags: version-1.5.3-1.1
Merge NMU change.

Show diffs side-by-side

added added

removed removed

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