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