/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2011-03-08 19:09:03 UTC
  • Revision ID: teddy@fukt.bsnet.se-20110308190903-j499ebtb9bpk31ar
* INSTALL: Updated.

Show diffs side-by-side

added added

removed removed

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