/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: 2008-12-10 01:26:02 UTC
  • mfrom: (237.1.2 mandos)
  • Revision ID: teddy@fukt.bsnet.se-20081210012602-vhz3h75xkj24t340
First version of a somewhat complete D-Bus server interface.  Also
change user/group name to "_mandos".

* debian/mandos.postinst: Rename old "mandos" user and group to
                          "_mandos"; create "_mandos" user and group
                          if none exist.
* debian/mandos-client.postinst: - '' -

* initramfs-tools-hook: Try "_mandos" before "mandos" as user and
                        group name.

* mandos (_datetime_to_dbus_struct): New; was previously local.
  (Client.started): Renamed to "last_started".  All users changed.
  (Client.started): New; boolean.
  (Client.dbus_object_path): New.
  (Client.check_command): Renamed to "checker_command".  All users
                          changed.
  (Client.__init__): Set and use "self.dbus_object_path".  Set
                     "self.started".
  (Client.start): Update "self.started".  Emit "self.PropertyChanged"
                  signals for both "started" and "last_started".
  (Client.stop): Update "self.started".  Emit "self.PropertyChanged"
                 signal for "started".
  (Client.checker_callback): Take additional "command" argument.  All
                             callers changed. Emit
                             "self.PropertyChanged" signal.
  (Client.bump_timeout): Emit "self.PropertyChanged" signal for
                         "last_checked_ok".
  (Client.start_checker): Emit "self.PropertyChanged" signal for
                          "checker_running".
  (Client.stop_checker): Emit "self.PropertyChanged" signal for
                         "checker_running".
  (Client.still_valid): Bug fix: use "getattr(self, started, False)"
                        instead of "self.started" in case this client
                        object is so new that the "started" attribute
                        has not been created yet.
  (Client.IntervalChanged, Client.CheckerIsRunning, Client.GetChecker,
  Client.GetCreated, Client.GetFingerprint, Client.GetHost,
  Client.GetInterval, Client.GetName, Client.GetStarted,
  Client.GetTimeout, Client.StateChanged, Client.TimeoutChanged):
  Removed; all callers changed.
  (Client.CheckerCompleted): Add "condition" and "command" arguments.
                             All callers changed.
  (Client.GetAllProperties, Client.PropertyChanged): New.
  (Client.StillValid): Renamed to "IsStillValid".
  (Client.StartChecker): Changed to its own function to avoid the
                         return value from "Client.start_checker()".
  (Client.Stop): Changed to its own function to avoid the return value
                 from "Client.stop()".
  (main): Try "_mandos" before "mandos" as user and group name.
          Removed inner function "remove_from_clients".  New inner
          class "MandosServer".

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