/mandos/release

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

« back to all changes in this revision

Viewing changes to plugins.d/password-request.c

  • Committer: Teddy Hogeborn
  • Date: 2008-08-29 05:53:59 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080829055359-wkdasnyxtylmnxus
* mandos.xml (EXAMPLE): Replaced all occurences of command name with
                        "&COMMANDNAME;".

* plugins.d/password-prompt.c (main): Improved some documentation
                                      strings.  Do perror() of
                                      tcgetattr() fails.  Add debug
                                      output if interrupted by signal.
                                      Loop over write() instead of
                                      using fwrite() when outputting
                                      password.  Add debug output if
                                      getline() returns 0, unless it
                                      was caused by a signal.  Add
                                      exit status code to debug
                                      output.

* plugins.d/password-prompt.xml: Changed all single quotes to double
                                 quotes for consistency.  Removed
                                 <?xml-stylesheet>.
  (ENTITY TIMESTAMP): New.  Automatically updated by Emacs time-stamp
                      by using Emacs local variables.
  (/refentry/refentryinfo/title): Changed to "Mandos Manual".
  (/refentry/refentryinfo/productname): Changed to "Mandos".
  (/refentry/refentryinfo/date): New; set to "&TIMESTAMP;".
  (/refentry/refentryinfo/copyright): Split copyright holders.
  (/refentry/refnamediv/refpurpose): Improved wording.
  (SYNOPSIS): Fix to use correct markup.  Add short options.
  (DESCRIPTION, OPTIONS): Improved wording.
  (OPTIONS): Improved wording.  Use more correct markup.  Document
             short options.
  (EXIT STATUS): Add text.
  (ENVIRONMENT): Document use of "cryptsource" and "crypttarget".
  (FILES): REMOVED.
  (BUGS): Add text.
  (EXAMPLE): Added some examples.
  (SECURITY): Added text.
  (SEE ALSO): Remove reference to mandos(8).  Add reference to
              crypttab(5).

Show diffs side-by-side

added added

removed removed

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