/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: 2010-01-01 15:17:12 UTC
  • Revision ID: teddy@fukt.bsnet.se-20100101151712-x20p42nhuvf9lxol
Bug fix: mandos-client needs GnuPG but lacked a dependency on it.  The
Mandos server, on the other hand, did not need GnuPG but declared an
incorrect dependency on it.

* debian/control (Package: mandos/Depends): Removed "gnupg (< 2)".
  (Package: mandos-client/Depends): Added "gnupg (<< 2)".

Show diffs side-by-side

added added

removed removed

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