/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-06-09 23:41:07 UTC
  • mto: This revision was merged to the branch mainline in revision 596.
  • Revision ID: teddy@recompile.se-20120609234107-vm6zilzz0y6aihsm
* plugins.d/mandos-client.c (raise_privileges,
  raise_privileges_permanently, lower_privileges): Return error_t and
                                                   save old errno
                                                   before calling any
                                                   other function.

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