/mandos/release

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

« back to all changes in this revision

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

* plugins.d/mandos-client.c (SYNOPSIS, OPTIONS): Document
                                                 "--network-hook-dir"
                                                 option.

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