/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2009-02-07 03:38:17 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090207033817-aotdjeibhz3sa4lr
* plugin-runner.c (main): If debugging, print name of failed plugins.

Show diffs side-by-side

added added

removed removed

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