/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2011-12-31 20:07:11 UTC
  • mfrom: (535.1.9 wireless-network-hook)
  • Revision ID: teddy@recompile.se-20111231200711-6dli3r8drftem57r
Merge new wireless network hook.  Fix bridge network hook to use
hardware addresses instead of interface names.  Implement and document
new "CONNECT" environment variable for network hooks.

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