/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/password-request.c

  • Committer: Teddy Hogeborn
  • Date: 2008-08-16 03:29:08 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080816032908-ihw7c05r2mnyk389
Add feature to specify custom environment variables for plugins.

* plugin-runner.c (plugin): New members "environ" and "envc" to
                            contain possible custom environment.
  (getplugin): Return NULL on failure instead of doing exit(); all
               callers changed.
  (add_to_char_array): New helper function for "add_argument" and
                       "add_environment".
  (addargument): Renamed to "add_argument".  Return bool.  Call
                 "add_to_char_array" to actually do things.
  (add_environment): New; analogous to "add_argument".
  (addcustomargument): Renamed to "add_to_argv" to avoid confusion
                       with "add_argument".
  (main): New options "--global-envs" and "--envs-for" to specify
          custom environment for plugins.  Print environment for
          plugins in debug mode.  Use asprintf instead of strcpy and
          strcat.  Use execve() for plugins with custom environments.
          Free environment for plugin when freeing plugin list.

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