/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Björn Påhlsson
  • Date: 2011-11-27 20:07:55 UTC
  • mfrom: (505.3.15 client-network-hooks)
  • mto: This revision was merged to the branch mainline in revision 525.
  • Revision ID: belorn@recompile.se-20111127200755-g5nxb5vjrtyavg86
merge

Show diffs side-by-side

added added

removed removed

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