/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: Björn Påhlsson
  • Date: 2010-10-02 18:28:21 UTC
  • mfrom: (237.4.6 mandos-release)
  • mto: This revision was merged to the branch mainline in revision 453.
  • Revision ID: belorn@fukt.bsnet.se-20101002182821-cazexo9y46o0g72o
Merge from release branch.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2012 Teddy Hogeborn
13
 
 * Copyright © 2008-2012 Björn Påhlsson
 
12
 * Copyright © 2008-2010 Teddy Hogeborn
 
13
 * Copyright © 2008-2010 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@recompile.se>.
 
29
 * Contact the authors at <mandos@fukt.bsnet.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
43
                                   stdout, ferror(), remove() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
 
44
#include <stdint.h>             /* uint16_t, uint32_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
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(), S_ISREG */
 
56
#include <sys/stat.h>           /* open() */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect() */
59
59
#include <fcntl.h>              /* open() */
62
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
63
                                   strtoimax() */
64
64
#include <assert.h>             /* assert() */
65
 
#include <errno.h>              /* perror(), errno,
66
 
                                   program_invocation_short_name */
 
65
#include <errno.h>              /* perror(), errno */
67
66
#include <time.h>               /* nanosleep(), time(), sleep() */
68
67
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
69
68
                                   SIOCSIFFLAGS, if_indextoname(),
73
72
                                */
74
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
74
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause(), _exit() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
75
                                   setgid(), pause() */
 
76
#include <arpa/inet.h>          /* inet_pton(), htons */
78
77
#include <iso646.h>             /* not, or, and */
79
78
#include <argp.h>               /* struct argp_option, error_t, struct
80
79
                                   argp_state, struct argp,
85
84
                                   raise() */
86
85
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
86
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
 
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
 
                                   WEXITSTATUS(), WTERMSIG() */
90
 
#include <grp.h>                /* setgroups() */
91
87
 
92
88
#ifdef __linux__
93
89
#include <sys/klog.h>           /* klogctl() */
111
107
                                   init_gnutls_session(),
112
108
                                   GNUTLS_* */
113
109
#include <gnutls/openpgp.h>
114
 
                         /* gnutls_certificate_set_openpgp_key_file(),
115
 
                            GNUTLS_OPENPGP_FMT_BASE64 */
 
110
                          /* gnutls_certificate_set_openpgp_key_file(),
 
111
                                   GNUTLS_OPENPGP_FMT_BASE64 */
116
112
 
117
113
/* GPGME */
118
114
#include <gpgme.h>              /* All GPGME types, constants and
126
122
#define PATHDIR "/conf/conf.d/mandos"
127
123
#define SECKEY "seckey.txt"
128
124
#define PUBKEY "pubkey.txt"
129
 
#define HOOKDIR "/lib/mandos/network-hooks.d"
130
125
 
131
126
bool debug = false;
132
127
static const char mandos_protocol_version[] = "1";
133
128
const char *argp_program_version = "mandos-client " VERSION;
134
 
const char *argp_program_bug_address = "<mandos@recompile.se>";
 
129
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
135
130
static const char sys_class_net[] = "/sys/class/net";
136
131
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;
151
132
 
152
133
/* Used for passing in values through the Avahi callback functions */
153
134
typedef struct {
158
139
  gnutls_dh_params_t dh_params;
159
140
  const char *priority;
160
141
  gpgme_ctx_t ctx;
161
 
  server *current_server;
162
142
} mandos_context;
163
143
 
164
144
/* global context so signal handler can reach it*/
165
145
mandos_context mc = { .simple_poll = NULL, .server = NULL,
166
146
                      .dh_bits = 1024, .priority = "SECURE256"
167
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
168
 
                      .current_server = NULL };
 
147
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
169
148
 
170
149
sig_atomic_t quit_now = 0;
171
150
int signal_received = 0;
172
151
 
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
 
 
192
152
/*
193
153
 * Make additional room in "buffer" for at least BUFFER_SIZE more
194
154
 * bytes. "buffer_capacity" is how much is currently allocated,
195
155
 * "buffer_length" is how much is already used.
196
156
 */
197
157
size_t incbuffer(char **buffer, size_t buffer_length,
198
 
                 size_t buffer_capacity){
 
158
                  size_t buffer_capacity){
199
159
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
200
160
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
201
161
    if(buffer == NULL){
206
166
  return buffer_capacity;
207
167
}
208
168
 
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
 
 
246
169
/* 
247
170
 * Initialize GPGME.
248
171
 */
249
 
static bool init_gpgme(const char *seckey, const char *pubkey,
250
 
                       const char *tempdir){
 
172
static bool init_gpgme(const char *seckey,
 
173
                       const char *pubkey, const char *tempdir){
251
174
  gpgme_error_t rc;
252
175
  gpgme_engine_info_t engine_info;
253
176
  
262
185
    
263
186
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
264
187
    if(fd == -1){
265
 
      perror_plus("open");
 
188
      perror("open");
266
189
      return false;
267
190
    }
268
191
    
269
192
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
270
193
    if(rc != GPG_ERR_NO_ERROR){
271
 
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
272
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
194
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
195
              gpgme_strsource(rc), gpgme_strerror(rc));
273
196
      return false;
274
197
    }
275
198
    
276
199
    rc = gpgme_op_import(mc.ctx, pgp_data);
277
200
    if(rc != GPG_ERR_NO_ERROR){
278
 
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
279
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
201
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
202
              gpgme_strsource(rc), gpgme_strerror(rc));
280
203
      return false;
281
204
    }
282
205
    
283
206
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
284
207
    if(ret == -1){
285
 
      perror_plus("close");
 
208
      perror("close");
286
209
    }
287
210
    gpgme_data_release(pgp_data);
288
211
    return true;
289
212
  }
290
213
  
291
214
  if(debug){
292
 
    fprintf_plus(stderr, "Initializing GPGME\n");
 
215
    fprintf(stderr, "Initializing GPGME\n");
293
216
  }
294
217
  
295
218
  /* Init GPGME */
296
219
  gpgme_check_version(NULL);
297
220
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
298
221
  if(rc != GPG_ERR_NO_ERROR){
299
 
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
300
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
222
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
223
            gpgme_strsource(rc), gpgme_strerror(rc));
301
224
    return false;
302
225
  }
303
226
  
304
 
  /* Set GPGME home directory for the OpenPGP engine only */
 
227
    /* Set GPGME home directory for the OpenPGP engine only */
305
228
  rc = gpgme_get_engine_info(&engine_info);
306
229
  if(rc != GPG_ERR_NO_ERROR){
307
 
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
308
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
230
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
231
            gpgme_strsource(rc), gpgme_strerror(rc));
309
232
    return false;
310
233
  }
311
234
  while(engine_info != NULL){
317
240
    engine_info = engine_info->next;
318
241
  }
319
242
  if(engine_info == NULL){
320
 
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
321
 
                 tempdir);
 
243
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
322
244
    return false;
323
245
  }
324
246
  
325
247
  /* Create new GPGME "context" */
326
248
  rc = gpgme_new(&(mc.ctx));
327
249
  if(rc != GPG_ERR_NO_ERROR){
328
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
329
 
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
330
 
                 gpgme_strerror(rc));
 
250
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
251
            gpgme_strsource(rc), gpgme_strerror(rc));
331
252
    return false;
332
253
  }
333
254
  
352
273
  ssize_t plaintext_length = 0;
353
274
  
354
275
  if(debug){
355
 
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
 
276
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
356
277
  }
357
278
  
358
279
  /* Create new GPGME data buffer from memory cryptotext */
359
280
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
360
281
                               0);
361
282
  if(rc != GPG_ERR_NO_ERROR){
362
 
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
363
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
283
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
284
            gpgme_strsource(rc), gpgme_strerror(rc));
364
285
    return -1;
365
286
  }
366
287
  
367
288
  /* Create new empty GPGME data buffer for the plaintext */
368
289
  rc = gpgme_data_new(&dh_plain);
369
290
  if(rc != GPG_ERR_NO_ERROR){
370
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
371
 
                 "bad gpgme_data_new: %s: %s\n",
372
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
291
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
292
            gpgme_strsource(rc), gpgme_strerror(rc));
373
293
    gpgme_data_release(dh_crypto);
374
294
    return -1;
375
295
  }
378
298
     data buffer */
379
299
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
380
300
  if(rc != GPG_ERR_NO_ERROR){
381
 
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
382
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
301
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
302
            gpgme_strsource(rc), gpgme_strerror(rc));
383
303
    plaintext_length = -1;
384
304
    if(debug){
385
305
      gpgme_decrypt_result_t result;
386
306
      result = gpgme_op_decrypt_result(mc.ctx);
387
307
      if(result == NULL){
388
 
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
 
308
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
389
309
      } else {
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);
 
310
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
311
                result->unsupported_algorithm);
 
312
        fprintf(stderr, "Wrong key usage: %u\n",
 
313
                result->wrong_key_usage);
394
314
        if(result->file_name != NULL){
395
 
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
 
315
          fprintf(stderr, "File name: %s\n", result->file_name);
396
316
        }
397
317
        gpgme_recipient_t recipient;
398
318
        recipient = result->recipients;
399
319
        while(recipient != NULL){
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");
 
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");
407
326
          recipient = recipient->next;
408
327
        }
409
328
      }
412
331
  }
413
332
  
414
333
  if(debug){
415
 
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
 
334
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
416
335
  }
417
336
  
418
337
  /* Seek back to the beginning of the GPGME plaintext data buffer */
419
338
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
420
 
    perror_plus("gpgme_data_seek");
 
339
    perror("gpgme_data_seek");
421
340
    plaintext_length = -1;
422
341
    goto decrypt_end;
423
342
  }
425
344
  *plaintext = NULL;
426
345
  while(true){
427
346
    plaintext_capacity = incbuffer(plaintext,
428
 
                                   (size_t)plaintext_length,
429
 
                                   plaintext_capacity);
 
347
                                      (size_t)plaintext_length,
 
348
                                      plaintext_capacity);
430
349
    if(plaintext_capacity == 0){
431
 
      perror_plus("incbuffer");
432
 
      plaintext_length = -1;
433
 
      goto decrypt_end;
 
350
        perror("incbuffer");
 
351
        plaintext_length = -1;
 
352
        goto decrypt_end;
434
353
    }
435
354
    
436
355
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
441
360
      break;
442
361
    }
443
362
    if(ret < 0){
444
 
      perror_plus("gpgme_data_read");
 
363
      perror("gpgme_data_read");
445
364
      plaintext_length = -1;
446
365
      goto decrypt_end;
447
366
    }
449
368
  }
450
369
  
451
370
  if(debug){
452
 
    fprintf_plus(stderr, "Decrypted password is: ");
 
371
    fprintf(stderr, "Decrypted password is: ");
453
372
    for(ssize_t i = 0; i < plaintext_length; i++){
454
373
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
455
374
    }
477
396
/* GnuTLS log function callback */
478
397
static void debuggnutls(__attribute__((unused)) int level,
479
398
                        const char* string){
480
 
  fprintf_plus(stderr, "GnuTLS: %s", string);
 
399
  fprintf(stderr, "GnuTLS: %s", string);
481
400
}
482
401
 
483
402
static int init_gnutls_global(const char *pubkeyfilename,
485
404
  int ret;
486
405
  
487
406
  if(debug){
488
 
    fprintf_plus(stderr, "Initializing GnuTLS\n");
 
407
    fprintf(stderr, "Initializing GnuTLS\n");
489
408
  }
490
409
  
491
410
  ret = gnutls_global_init();
492
411
  if(ret != GNUTLS_E_SUCCESS){
493
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
494
 
                 safer_gnutls_strerror(ret));
 
412
    fprintf(stderr, "GnuTLS global_init: %s\n",
 
413
            safer_gnutls_strerror(ret));
495
414
    return -1;
496
415
  }
497
416
  
504
423
  }
505
424
  
506
425
  /* OpenPGP credentials */
507
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
426
  gnutls_certificate_allocate_credentials(&mc.cred);
508
427
  if(ret != GNUTLS_E_SUCCESS){
509
 
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
510
 
                 safer_gnutls_strerror(ret));
 
428
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
 
429
                                                    from
 
430
                                                    -Wunreachable-code
 
431
                                                 */
 
432
            safer_gnutls_strerror(ret));
511
433
    gnutls_global_deinit();
512
434
    return -1;
513
435
  }
514
436
  
515
437
  if(debug){
516
 
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
517
 
                 " secret key %s as GnuTLS credentials\n",
518
 
                 pubkeyfilename,
519
 
                 seckeyfilename);
 
438
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
439
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
 
440
            seckeyfilename);
520
441
  }
521
442
  
522
443
  ret = gnutls_certificate_set_openpgp_key_file
523
444
    (mc.cred, pubkeyfilename, seckeyfilename,
524
445
     GNUTLS_OPENPGP_FMT_BASE64);
525
446
  if(ret != GNUTLS_E_SUCCESS){
526
 
    fprintf_plus(stderr,
527
 
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
528
 
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
529
 
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
530
 
                 safer_gnutls_strerror(ret));
 
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));
531
452
    goto globalfail;
532
453
  }
533
454
  
534
455
  /* GnuTLS server initialization */
535
456
  ret = gnutls_dh_params_init(&mc.dh_params);
536
457
  if(ret != GNUTLS_E_SUCCESS){
537
 
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
538
 
                 " initialization: %s\n",
539
 
                 safer_gnutls_strerror(ret));
 
458
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
459
            " %s\n", safer_gnutls_strerror(ret));
540
460
    goto globalfail;
541
461
  }
542
462
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
543
463
  if(ret != GNUTLS_E_SUCCESS){
544
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
545
 
                 safer_gnutls_strerror(ret));
 
464
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
465
            safer_gnutls_strerror(ret));
546
466
    goto globalfail;
547
467
  }
548
468
  
568
488
    }
569
489
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
570
490
  if(ret != GNUTLS_E_SUCCESS){
571
 
    fprintf_plus(stderr,
572
 
                 "Error in GnuTLS session initialization: %s\n",
573
 
                 safer_gnutls_strerror(ret));
 
491
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
492
            safer_gnutls_strerror(ret));
574
493
  }
575
494
  
576
495
  {
583
502
      }
584
503
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
585
504
    if(ret != GNUTLS_E_SUCCESS){
586
 
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
587
 
      fprintf_plus(stderr, "GnuTLS error: %s\n",
588
 
                   safer_gnutls_strerror(ret));
 
505
      fprintf(stderr, "Syntax error at: %s\n", err);
 
506
      fprintf(stderr, "GnuTLS error: %s\n",
 
507
              safer_gnutls_strerror(ret));
589
508
      gnutls_deinit(*session);
590
509
      return -1;
591
510
    }
600
519
    }
601
520
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
602
521
  if(ret != GNUTLS_E_SUCCESS){
603
 
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
604
 
                 safer_gnutls_strerror(ret));
 
522
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
523
            safer_gnutls_strerror(ret));
605
524
    gnutls_deinit(*session);
606
525
    return -1;
607
526
  }
652
571
    pf = PF_INET;
653
572
    break;
654
573
  default:
655
 
    fprintf_plus(stderr, "Bad address family: %d\n", af);
 
574
    fprintf(stderr, "Bad address family: %d\n", af);
656
575
    errno = EINVAL;
657
576
    return -1;
658
577
  }
663
582
  }
664
583
  
665
584
  if(debug){
666
 
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
667
 
                 PRIu16 "\n", ip, port);
 
585
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
586
            "\n", ip, port);
668
587
  }
669
588
  
670
589
  tcp_sd = socket(pf, SOCK_STREAM, 0);
671
590
  if(tcp_sd < 0){
672
591
    int e = errno;
673
 
    perror_plus("socket");
 
592
    perror("socket");
674
593
    errno = e;
675
594
    goto mandos_end;
676
595
  }
690
609
  }
691
610
  if(ret < 0 ){
692
611
    int e = errno;
693
 
    perror_plus("inet_pton");
 
612
    perror("inet_pton");
694
613
    errno = e;
695
614
    goto mandos_end;
696
615
  }
697
616
  if(ret == 0){
698
617
    int e = errno;
699
 
    fprintf_plus(stderr, "Bad address: %s\n", ip);
 
618
    fprintf(stderr, "Bad address: %s\n", ip);
700
619
    errno = e;
701
620
    goto mandos_end;
702
621
  }
707
626
    
708
627
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
709
628
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
710
 
                                -Wunreachable-code*/
 
629
                              -Wunreachable-code*/
711
630
      if(if_index == AVAHI_IF_UNSPEC){
712
 
        fprintf_plus(stderr, "An IPv6 link-local address is"
713
 
                     " incomplete without a network interface\n");
 
631
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
632
                " without a network interface\n");
714
633
        errno = EINVAL;
715
634
        goto mandos_end;
716
635
      }
732
651
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
733
652
      char interface[IF_NAMESIZE];
734
653
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
735
 
        perror_plus("if_indextoname");
 
654
        perror("if_indextoname");
736
655
      } else {
737
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
738
 
                     "\n", ip, interface, port);
 
656
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
657
                ip, interface, port);
739
658
      }
740
659
    } else {
741
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
742
 
                   ip, port);
 
660
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
661
              port);
743
662
    }
744
663
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
745
664
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
752
671
                        sizeof(addrstr));
753
672
    }
754
673
    if(pcret == NULL){
755
 
      perror_plus("inet_ntop");
 
674
      perror("inet_ntop");
756
675
    } else {
757
676
      if(strcmp(addrstr, ip) != 0){
758
 
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
677
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
759
678
      }
760
679
    }
761
680
  }
773
692
  if(ret < 0){
774
693
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
775
694
      int e = errno;
776
 
      perror_plus("connect");
 
695
      perror("connect");
777
696
      errno = e;
778
697
    }
779
698
    goto mandos_end;
789
708
  while(true){
790
709
    size_t out_size = strlen(out);
791
710
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
792
 
                                        out_size - written));
 
711
                                   out_size - written));
793
712
    if(ret == -1){
794
713
      int e = errno;
795
 
      perror_plus("write");
 
714
      perror("write");
796
715
      errno = e;
797
716
      goto mandos_end;
798
717
    }
815
734
  }
816
735
  
817
736
  if(debug){
818
 
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
 
737
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
819
738
  }
820
739
  
821
740
  if(quit_now){
823
742
    goto mandos_end;
824
743
  }
825
744
  
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);
 
745
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
831
746
  
832
747
  if(quit_now){
833
748
    errno = EINTR;
844
759
  
845
760
  if(ret != GNUTLS_E_SUCCESS){
846
761
    if(debug){
847
 
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
 
762
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
848
763
      gnutls_perror(ret);
849
764
    }
850
765
    errno = EPROTO;
854
769
  /* Read OpenPGP packet that contains the wanted password */
855
770
  
856
771
  if(debug){
857
 
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
858
 
                 " %s\n", ip);
 
772
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
773
            ip);
859
774
  }
860
775
  
861
776
  while(true){
866
781
    }
867
782
    
868
783
    buffer_capacity = incbuffer(&buffer, buffer_length,
869
 
                                buffer_capacity);
 
784
                                   buffer_capacity);
870
785
    if(buffer_capacity == 0){
871
786
      int e = errno;
872
 
      perror_plus("incbuffer");
 
787
      perror("incbuffer");
873
788
      errno = e;
874
789
      goto mandos_end;
875
790
    }
899
814
          }
900
815
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
901
816
        if(ret < 0){
902
 
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
903
 
                       "***\n");
 
817
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
904
818
          gnutls_perror(ret);
905
819
          errno = EPROTO;
906
820
          goto mandos_end;
907
821
        }
908
822
        break;
909
823
      default:
910
 
        fprintf_plus(stderr, "Unknown error while reading data from"
911
 
                     " encrypted session with Mandos server\n");
 
824
        fprintf(stderr, "Unknown error while reading data from"
 
825
                " encrypted session with Mandos server\n");
912
826
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
913
827
        errno = EIO;
914
828
        goto mandos_end;
919
833
  }
920
834
  
921
835
  if(debug){
922
 
    fprintf_plus(stderr, "Closing TLS session\n");
 
836
    fprintf(stderr, "Closing TLS session\n");
923
837
  }
924
838
  
925
839
  if(quit_now){
937
851
  
938
852
  if(buffer_length > 0){
939
853
    ssize_t decrypted_buffer_size;
940
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
 
854
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
855
                                               buffer_length,
941
856
                                               &decrypted_buffer);
942
857
    if(decrypted_buffer_size >= 0){
943
858
      
954
869
        if(ret == 0 and ferror(stdout)){
955
870
          int e = errno;
956
871
          if(debug){
957
 
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
958
 
                         strerror(errno));
 
872
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
873
                    strerror(errno));
959
874
          }
960
875
          errno = e;
961
876
          goto mandos_end;
980
895
      if(e == 0){
981
896
        e = errno;
982
897
      }
983
 
      perror_plus("close");
 
898
      perror("close");
984
899
    }
985
900
    gnutls_deinit(session);
986
 
    errno = e;
987
901
    if(quit_now){
988
 
      errno = EINTR;
 
902
      e = EINTR;
989
903
      retval = -1;
990
904
    }
 
905
    errno = e;
991
906
  }
992
907
  return retval;
993
908
}
1018
933
  switch(event){
1019
934
  default:
1020
935
  case AVAHI_RESOLVER_FAILURE:
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)));
 
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)));
1025
939
    break;
1026
940
    
1027
941
  case AVAHI_RESOLVER_FOUND:
1029
943
      char ip[AVAHI_ADDRESS_STR_MAX];
1030
944
      avahi_address_snprint(ip, sizeof(ip), address);
1031
945
      if(debug){
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);
 
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);
1035
949
      }
1036
950
      int ret = start_mandos_communication(ip, port, interface,
1037
951
                                           avahi_proto_to_af(proto));
1038
952
      if(ret == 0){
1039
953
        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
 
        }
1046
954
      }
1047
955
    }
1048
956
  }
1072
980
  default:
1073
981
  case AVAHI_BROWSER_FAILURE:
1074
982
    
1075
 
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1076
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
983
    fprintf(stderr, "(Avahi browser) %s\n",
 
984
            avahi_strerror(avahi_server_errno(mc.server)));
1077
985
    avahi_simple_poll_quit(mc.simple_poll);
1078
986
    return;
1079
987
    
1086
994
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1087
995
                                    name, type, domain, protocol, 0,
1088
996
                                    resolve_callback, NULL) == NULL)
1089
 
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1090
 
                   " %s\n", name,
1091
 
                   avahi_strerror(avahi_server_errno(mc.server)));
 
997
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
998
              name, avahi_strerror(avahi_server_errno(mc.server)));
1092
999
    break;
1093
1000
    
1094
1001
  case AVAHI_BROWSER_REMOVE:
1097
1004
  case AVAHI_BROWSER_ALL_FOR_NOW:
1098
1005
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1099
1006
    if(debug){
1100
 
      fprintf_plus(stderr, "No Mandos server found, still"
1101
 
                   " searching...\n");
 
1007
      fprintf(stderr, "No Mandos server found, still searching...\n");
1102
1008
    }
1103
1009
    break;
1104
1010
  }
1105
1011
}
1106
1012
 
1107
 
/* Signal handler that stops main loop after SIGTERM */
 
1013
/* stop main loop after sigterm has been called */
1108
1014
static void handle_sigterm(int sig){
1109
1015
  if(quit_now){
1110
1016
    return;
1112
1018
  quit_now = 1;
1113
1019
  signal_received = sig;
1114
1020
  int old_errno = errno;
1115
 
  /* set main loop to exit */
1116
1021
  if(mc.simple_poll != NULL){
1117
1022
    avahi_simple_poll_quit(mc.simple_poll);
1118
1023
  }
1119
1024
  errno = old_errno;
1120
1025
}
1121
1026
 
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){
 
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){
1133
1081
    if(debug){
1134
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1082
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1083
              flagstring, if_entry->d_name);
1135
1084
    }
1136
 
    return false;
 
1085
    free(flagstring);
 
1086
    return 0;
1137
1087
  }
1138
 
  return true;
1139
 
}
1140
 
 
1141
 
bool good_flags(const char *ifname, const struct ifreq *ifr){
1142
 
  
 
1088
  free(flagstring);
 
1089
  ifreq_flags flags = (ifreq_flags)tmpmax;
1143
1090
  /* Reject the loopback device */
1144
 
  if(ifr->ifr_flags & IFF_LOOPBACK){
 
1091
  if(flags & IFF_LOOPBACK){
1145
1092
    if(debug){
1146
 
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1147
 
                   ifname);
 
1093
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1094
              if_entry->d_name);
1148
1095
    }
1149
 
    return false;
 
1096
    return 0;
1150
1097
  }
1151
1098
  /* Accept point-to-point devices only if connect_to is specified */
1152
 
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
 
1099
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1153
1100
    if(debug){
1154
 
      fprintf_plus(stderr, "Accepting point-to-point interface"
1155
 
                   " \"%s\"\n", ifname);
 
1101
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1102
              if_entry->d_name);
1156
1103
    }
1157
 
    return true;
 
1104
    return 1;
1158
1105
  }
1159
1106
  /* Otherwise, reject non-broadcast-capable devices */
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
 
  
 
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
  }
1176
1114
  /* Accept this device */
1177
1115
  if(debug){
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;
 
1116
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1117
            if_entry->d_name);
 
1118
  }
 
1119
  return 1;
1682
1120
}
1683
1121
 
1684
1122
int main(int argc, char *argv[]){
1692
1130
  struct ifreq network;
1693
1131
  int sd = -1;
1694
1132
  bool take_down_interface = false;
 
1133
  uid_t uid;
 
1134
  gid_t gid;
1695
1135
  char tempdir[] = "/tmp/mandosXXXXXX";
1696
1136
  bool tempdir_created = false;
1697
1137
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1701
1141
  bool gnutls_initialized = false;
1702
1142
  bool gpgme_initialized = false;
1703
1143
  float delay = 2.5f;
1704
 
  double retry_interval = 10; /* 10s between trying a server and
1705
 
                                 retrying the same server again */
1706
1144
  
1707
1145
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1708
1146
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1714
1152
  errno = 0;
1715
1153
  ret = setgid(gid);
1716
1154
  if(ret == -1){
1717
 
    perror_plus("setgid");
 
1155
    perror("setgid");
1718
1156
  }
1719
1157
  
1720
1158
  /* Lower user privileges (temporarily) */
1721
1159
  errno = 0;
1722
1160
  ret = seteuid(uid);
1723
1161
  if(ret == -1){
1724
 
    perror_plus("seteuid");
 
1162
    perror("seteuid");
1725
1163
  }
1726
1164
  
1727
1165
  if(quit_now){
1762
1200
        .arg = "SECONDS",
1763
1201
        .doc = "Maximum delay to wait for interface startup",
1764
1202
        .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 },
1773
1203
      /*
1774
1204
       * These reproduce what we would get without ARGP_NO_HELP
1775
1205
       */
1819
1249
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1820
1250
          argp_error(state, "Bad delay");
1821
1251
        }
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;
1833
1252
        break;
1834
1253
        /*
1835
1254
         * These reproduce what we would get without ARGP_NO_HELP
1842
1261
        argp_state_help(state, state->out_stream,
1843
1262
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1844
1263
      case 'V':                 /* --version */
1845
 
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
 
1264
        fprintf(state->out_stream, "%s\n", argp_program_version);
1846
1265
        exit(argp_err_exit_status);
1847
1266
        break;
1848
1267
      default:
1863
1282
    case ENOMEM:
1864
1283
    default:
1865
1284
      errno = ret;
1866
 
      perror_plus("argp_parse");
 
1285
      perror("argp_parse");
1867
1286
      exitcode = EX_OSERR;
1868
1287
      goto end;
1869
1288
    case EINVAL:
1871
1290
      goto end;
1872
1291
    }
1873
1292
  }
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
 
  }
1938
1293
  
1939
1294
  if(not debug){
1940
1295
    avahi_set_log_function(empty_log);
1941
1296
  }
1942
 
  
 
1297
 
1943
1298
  if(interface[0] == '\0'){
1944
1299
    struct dirent **direntries;
1945
 
    /* First look for interfaces that are up */
1946
 
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1300
    ret = scandir(sys_class_net, &direntries, good_interface,
1947
1301
                  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
 
    }
1954
1302
    if(ret >= 1){
1955
 
      /* Pick the first interface returned */
 
1303
      /* Pick the first good interface */
1956
1304
      interface = strdup(direntries[0]->d_name);
1957
1305
      if(debug){
1958
 
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
 
1306
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1959
1307
      }
1960
1308
      if(interface == NULL){
1961
 
        perror_plus("malloc");
 
1309
        perror("malloc");
1962
1310
        free(direntries);
1963
1311
        exitcode = EXIT_FAILURE;
1964
1312
        goto end;
1966
1314
      free(direntries);
1967
1315
    } else {
1968
1316
      free(direntries);
1969
 
      fprintf_plus(stderr, "Could not find a network interface\n");
 
1317
      fprintf(stderr, "Could not find a network interface\n");
1970
1318
      exitcode = EXIT_FAILURE;
1971
1319
      goto end;
1972
1320
    }
1978
1326
  srand((unsigned int) time(NULL));
1979
1327
  mc.simple_poll = avahi_simple_poll_new();
1980
1328
  if(mc.simple_poll == NULL){
1981
 
    fprintf_plus(stderr,
1982
 
                 "Avahi: Failed to create simple poll object.\n");
 
1329
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1983
1330
    exitcode = EX_UNAVAILABLE;
1984
1331
    goto end;
1985
1332
  }
1987
1334
  sigemptyset(&sigterm_action.sa_mask);
1988
1335
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1989
1336
  if(ret == -1){
1990
 
    perror_plus("sigaddset");
 
1337
    perror("sigaddset");
1991
1338
    exitcode = EX_OSERR;
1992
1339
    goto end;
1993
1340
  }
1994
1341
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1995
1342
  if(ret == -1){
1996
 
    perror_plus("sigaddset");
 
1343
    perror("sigaddset");
1997
1344
    exitcode = EX_OSERR;
1998
1345
    goto end;
1999
1346
  }
2000
1347
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
2001
1348
  if(ret == -1){
2002
 
    perror_plus("sigaddset");
 
1349
    perror("sigaddset");
2003
1350
    exitcode = EX_OSERR;
2004
1351
    goto end;
2005
1352
  }
2009
1356
  */
2010
1357
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
2011
1358
  if(ret == -1){
2012
 
    perror_plus("sigaction");
 
1359
    perror("sigaction");
2013
1360
    return EX_OSERR;
2014
1361
  }
2015
1362
  if(old_sigterm_action.sa_handler != SIG_IGN){
2016
1363
    ret = sigaction(SIGINT, &sigterm_action, NULL);
2017
1364
    if(ret == -1){
2018
 
      perror_plus("sigaction");
 
1365
      perror("sigaction");
2019
1366
      exitcode = EX_OSERR;
2020
1367
      goto end;
2021
1368
    }
2022
1369
  }
2023
1370
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
2024
1371
  if(ret == -1){
2025
 
    perror_plus("sigaction");
 
1372
    perror("sigaction");
2026
1373
    return EX_OSERR;
2027
1374
  }
2028
1375
  if(old_sigterm_action.sa_handler != SIG_IGN){
2029
1376
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
2030
1377
    if(ret == -1){
2031
 
      perror_plus("sigaction");
 
1378
      perror("sigaction");
2032
1379
      exitcode = EX_OSERR;
2033
1380
      goto end;
2034
1381
    }
2035
1382
  }
2036
1383
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
2037
1384
  if(ret == -1){
2038
 
    perror_plus("sigaction");
 
1385
    perror("sigaction");
2039
1386
    return EX_OSERR;
2040
1387
  }
2041
1388
  if(old_sigterm_action.sa_handler != SIG_IGN){
2042
1389
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
2043
1390
    if(ret == -1){
2044
 
      perror_plus("sigaction");
 
1391
      perror("sigaction");
2045
1392
      exitcode = EX_OSERR;
2046
1393
      goto end;
2047
1394
    }
2048
1395
  }
2049
1396
  
2050
1397
  /* If the interface is down, bring it up */
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");
 
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
      }
2056
1538
    }
2057
1539
  }
2058
1540
  
2062
1544
  
2063
1545
  ret = init_gnutls_global(pubkey, seckey);
2064
1546
  if(ret == -1){
2065
 
    fprintf_plus(stderr, "init_gnutls_global failed\n");
 
1547
    fprintf(stderr, "init_gnutls_global failed\n");
2066
1548
    exitcode = EX_UNAVAILABLE;
2067
1549
    goto end;
2068
1550
  } else {
2073
1555
    goto end;
2074
1556
  }
2075
1557
  
 
1558
  tempdir_created = true;
2076
1559
  if(mkdtemp(tempdir) == NULL){
2077
 
    perror_plus("mkdtemp");
 
1560
    tempdir_created = false;
 
1561
    perror("mkdtemp");
2078
1562
    goto end;
2079
1563
  }
2080
 
  tempdir_created = true;
2081
1564
  
2082
1565
  if(quit_now){
2083
1566
    goto end;
2084
1567
  }
2085
1568
  
2086
1569
  if(not init_gpgme(pubkey, seckey, tempdir)){
2087
 
    fprintf_plus(stderr, "init_gpgme failed\n");
 
1570
    fprintf(stderr, "init_gpgme failed\n");
2088
1571
    exitcode = EX_UNAVAILABLE;
2089
1572
    goto end;
2090
1573
  } else {
2099
1582
    /* Connect directly, do not use Zeroconf */
2100
1583
    /* (Mainly meant for debugging) */
2101
1584
    char *address = strrchr(connect_to, ':');
2102
 
    
2103
1585
    if(address == NULL){
2104
 
      fprintf_plus(stderr, "No colon in address\n");
 
1586
      fprintf(stderr, "No colon in address\n");
2105
1587
      exitcode = EX_USAGE;
2106
1588
      goto end;
2107
1589
    }
2115
1597
    tmpmax = strtoimax(address+1, &tmp, 10);
2116
1598
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2117
1599
       or tmpmax != (uint16_t)tmpmax){
2118
 
      fprintf_plus(stderr, "Bad port number\n");
 
1600
      fprintf(stderr, "Bad port number\n");
2119
1601
      exitcode = EX_USAGE;
2120
1602
      goto end;
2121
1603
    }
2126
1608
    
2127
1609
    port = (uint16_t)tmpmax;
2128
1610
    *address = '\0';
 
1611
    address = connect_to;
2129
1612
    /* Colon in address indicates IPv6 */
2130
1613
    int af;
2131
 
    if(strchr(connect_to, ':') != NULL){
 
1614
    if(strchr(address, ':') != NULL){
2132
1615
      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
 
        }
2139
1616
    } else {
2140
1617
      af = AF_INET;
2141
1618
    }
2142
 
    address = connect_to;
2143
1619
    
2144
1620
    if(quit_now){
2145
1621
      goto end;
2146
1622
    }
2147
 
    
 
1623
 
2148
1624
    while(not quit_now){
2149
1625
      ret = start_mandos_communication(address, port, if_index, af);
2150
1626
      if(quit_now or ret == 0){
2151
1627
        break;
2152
1628
      }
2153
 
      if(debug){
2154
 
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2155
 
                     (int)retry_interval);
2156
 
      }
2157
 
      sleep((int)retry_interval);
2158
 
    }
2159
 
    
 
1629
      sleep(15);
 
1630
    };
 
1631
 
2160
1632
    if (not quit_now){
2161
1633
      exitcode = EXIT_SUCCESS;
2162
1634
    }
2163
 
    
 
1635
 
2164
1636
    goto end;
2165
1637
  }
2166
1638
  
2188
1660
  
2189
1661
  /* Check if creating the Avahi server object succeeded */
2190
1662
  if(mc.server == NULL){
2191
 
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2192
 
                 avahi_strerror(error));
 
1663
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
1664
            avahi_strerror(error));
2193
1665
    exitcode = EX_UNAVAILABLE;
2194
1666
    goto end;
2195
1667
  }
2203
1675
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2204
1676
                                   NULL, 0, browse_callback, NULL);
2205
1677
  if(sb == NULL){
2206
 
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2207
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1678
    fprintf(stderr, "Failed to create service browser: %s\n",
 
1679
            avahi_strerror(avahi_server_errno(mc.server)));
2208
1680
    exitcode = EX_UNAVAILABLE;
2209
1681
    goto end;
2210
1682
  }
2216
1688
  /* Run the main loop */
2217
1689
  
2218
1690
  if(debug){
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
 
  }
 
1691
    fprintf(stderr, "Starting Avahi loop search\n");
 
1692
  }
 
1693
  
 
1694
  avahi_simple_poll_loop(mc.simple_poll);
2228
1695
  
2229
1696
 end:
2230
1697
  
2231
1698
  if(debug){
2232
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
1699
    fprintf(stderr, "%s exiting\n", argv[0]);
2233
1700
  }
2234
1701
  
2235
1702
  /* Cleanup things */
2252
1719
    gpgme_release(mc.ctx);
2253
1720
  }
2254
1721
  
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;
 
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");
2263
1729
    }
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){
 
1730
    if(geteuid() == 0){
2275
1731
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2276
1732
      if(ret == -1){
2277
 
        perror_plus("ioctl SIOCGIFFLAGS");
2278
 
      } else if(network.ifr_flags & IFF_UP){
 
1733
        perror("ioctl SIOCGIFFLAGS");
 
1734
      } else if(network.ifr_flags & IFF_UP) {
2279
1735
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2280
1736
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2281
1737
        if(ret == -1){
2282
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1738
          perror("ioctl SIOCSIFFLAGS -IFF_UP");
2283
1739
        }
2284
1740
      }
2285
1741
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2286
1742
      if(ret == -1){
2287
 
        perror_plus("close");
 
1743
        perror("close");
 
1744
      }
 
1745
      /* Lower privileges permanently */
 
1746
      errno = 0;
 
1747
      ret = setuid(uid);
 
1748
      if(ret == -1){
 
1749
        perror("setuid");
2288
1750
      }
2289
1751
    }
2290
1752
  }
2291
 
  /* Lower privileges permanently */
2292
 
  errno = 0;
2293
 
  ret = setuid(uid);
2294
 
  if(ret == -1){
2295
 
    perror_plus("setuid");
2296
 
  }
2297
1753
  
2298
 
  /* Removes the GPGME temp directory and all files inside */
 
1754
  /* Removes the temp directory used by GPGME */
2299
1755
  if(tempdir_created){
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];
 
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
        }
2307
1776
        char *fullname = NULL;
2308
1777
        ret = asprintf(&fullname, "%s/%s", tempdir,
2309
1778
                       direntry->d_name);
2310
1779
        if(ret < 0){
2311
 
          perror_plus("asprintf");
 
1780
          perror("asprintf");
2312
1781
          continue;
2313
1782
        }
2314
1783
        ret = remove(fullname);
2315
1784
        if(ret == -1){
2316
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2317
 
                       strerror(errno));
 
1785
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
1786
                  strerror(errno));
2318
1787
        }
2319
1788
        free(fullname);
2320
1789
      }
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");
 
1790
      closedir(d);
2327
1791
    }
2328
1792
    ret = rmdir(tempdir);
2329
1793
    if(ret == -1 and errno != ENOENT){
2330
 
      perror_plus("rmdir");
 
1794
      perror("rmdir");
2331
1795
    }
2332
1796
  }
2333
1797
  
2338
1802
                                            &old_sigterm_action,
2339
1803
                                            NULL));
2340
1804
    if(ret == -1){
2341
 
      perror_plus("sigaction");
 
1805
      perror("sigaction");
2342
1806
    }
2343
1807
    do {
2344
1808
      ret = raise(signal_received);
2345
1809
    } while(ret != 0 and errno == EINTR);
2346
1810
    if(ret != 0){
2347
 
      perror_plus("raise");
 
1811
      perror("raise");
2348
1812
      abort();
2349
1813
    }
2350
1814
    TEMP_FAILURE_RETRY(pause());