/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-09-16 23:28:39 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090916232839-3o7i8qmcdcz5j1ya
* init.d-mandos (Required-Start, Required-Stop): Bug fix: Added
                 "$syslog", thanks to Petter Reinholdtsen
                 <pere@hungry.com> (Debian bug #546928).

* initramfs-tools-script: Removed erroneous comment.

* plugins.d/askpass-fifo.c: Removed TEMP_FAILURE_RETRY since it is
                            not needed.

* plugins.d/mandos-client.c (main): Bug fix: Initialize
                                    "old_sigterm_action".

* plugins.d/splashy.c (main): Bug fix: really check return value from
                              "sigaddset".  Fix some warnings on
                              64-bit systems.

* plugins.d/usplash.c (termination_handler, main): Save received
                                                   signal and
                                                   re-raise it on
                                                   exit.
  (usplash_write): Do not close FIFO, instead, take an additional file
                   descriptor pointer to it and open only when needed
                   (all callers changed).  Abort immediately on EINTR.
                   Bug fix:  Add NUL byte on single-word commands.
                   Ignore "interrupted_by_signal".
  (makeprompt, find_usplash): New; broken out from "main()".
  (find_usplash): Bug fix: close /proc/<pid>/cmdline FD on error.
  (main): Reorganized to jump to a new "failure" label on any error.
          Bug fix: check return values from sigaddset.
          New variable "usplash_accessed" to flag if usplash(8) needs
          to be killed and restarted.  Removed the "an_error_occured"
          variable.

Show diffs side-by-side

added added

removed removed

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