/mandos/release

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

« back to all changes in this revision

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

* plugins.d/password-prompt.c: Use environment variables and prompt
                               text from cryptsetup 1.1.
* plugins.d/password-prompt.xml (ENVIRONMENT): Document change in
                                               environment variables
                                               used.

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