/mandos/trunk

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

« back to all changes in this revision

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

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

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

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

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

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/*  -*- coding: utf-8 -*- */
2
2
/*
3
 
 * Mandos-client - get and decrypt data from a Mandos server
 
3
 * Mandos client - get and decrypt data from a Mandos server
4
4
 *
5
5
 * This program is partly derived from an example program for an Avahi
6
6
 * service browser, downloaded from
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008,2009 Teddy Hogeborn
13
 
 * Copyright © 2008,2009 Björn Påhlsson
 
12
 * Copyright © 2008 Teddy Hogeborn
 
13
 * Copyright © 2008 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
36
36
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
37
37
 
38
38
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
39
 
                                   stdout, ferror(), sscanf(),
40
 
                                   remove() */
 
39
                                   stdout, ferror() */
41
40
#include <stdint.h>             /* uint16_t, uint32_t */
42
41
#include <stddef.h>             /* NULL, size_t, ssize_t */
43
42
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
44
43
                                   srand() */
45
 
#include <stdbool.h>            /* bool, false, true */
 
44
#include <stdbool.h>            /* bool, true */
46
45
#include <string.h>             /* memset(), strcmp(), strlen(),
47
46
                                   strerror(), asprintf(), strcpy() */
48
 
#include <sys/ioctl.h>          /* ioctl */
 
47
#include <sys/ioctl.h>          /* ioctl */
49
48
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
50
49
                                   sockaddr_in6, PF_INET6,
51
 
                                   SOCK_STREAM, uid_t, gid_t, open(),
52
 
                                   opendir(), DIR */
 
50
                                   SOCK_STREAM, INET6_ADDRSTRLEN,
 
51
                                   uid_t, gid_t, open(), opendir(), DIR */
53
52
#include <sys/stat.h>           /* open() */
54
53
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
55
 
                                   inet_pton(), connect() */
 
54
                                   struct in6_addr, inet_pton(),
 
55
                                   connect() */
56
56
#include <fcntl.h>              /* open() */
57
 
#include <dirent.h>             /* opendir(), struct dirent, readdir()
58
 
                                 */
59
 
#include <inttypes.h>           /* PRIu16, intmax_t, SCNdMAX */
 
57
#include <dirent.h>             /* opendir(), struct dirent, readdir() */
 
58
#include <inttypes.h>           /* PRIu16 */
60
59
#include <assert.h>             /* assert() */
61
60
#include <errno.h>              /* perror(), errno */
62
 
#include <time.h>               /* nanosleep(), time() */
 
61
#include <time.h>               /* time() */
63
62
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
64
63
                                   SIOCSIFFLAGS, if_indextoname(),
65
64
                                   if_nametoindex(), IF_NAMESIZE */
66
 
#include <netinet/in.h>         /* IN6_IS_ADDR_LINKLOCAL,
67
 
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
68
 
                                */
 
65
#include <netinet/in.h>
69
66
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
70
67
                                   getuid(), getgid(), setuid(),
71
68
                                   setgid() */
72
69
#include <arpa/inet.h>          /* inet_pton(), htons */
73
 
#include <iso646.h>             /* not, or, and */
 
70
#include <iso646.h>             /* not, and */
74
71
#include <argp.h>               /* struct argp_option, error_t, struct
75
72
                                   argp_state, struct argp,
76
73
                                   argp_parse(), ARGP_KEY_ARG,
77
74
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
78
 
#include <signal.h>             /* sigemptyset(), sigaddset(),
79
 
                                   sigaction(), SIGTERM, sigaction,
80
 
                                   sig_atomic_t */
81
 
 
82
 
#ifdef __linux__
83
 
#include <sys/klog.h>           /* klogctl() */
84
 
#endif  /* __linux__ */
85
75
 
86
76
/* Avahi */
87
77
/* All Avahi types, constants and functions
100
90
                                   gnutls_*
101
91
                                   init_gnutls_session(),
102
92
                                   GNUTLS_* */
103
 
#include <gnutls/openpgp.h>
104
 
                          /* gnutls_certificate_set_openpgp_key_file(),
 
93
#include <gnutls/openpgp.h>     /* gnutls_certificate_set_openpgp_key_file(),
105
94
                                   GNUTLS_OPENPGP_FMT_BASE64 */
106
95
 
107
96
/* GPGME */
133
122
  gpgme_ctx_t ctx;
134
123
} mandos_context;
135
124
 
136
 
/* global context so signal handler can reach it*/
137
 
mandos_context mc;
138
 
 
139
125
/*
140
 
 * Make additional room in "buffer" for at least BUFFER_SIZE more
141
 
 * bytes. "buffer_capacity" is how much is currently allocated,
 
126
 * Make room in "buffer" for at least BUFFER_SIZE additional bytes.
 
127
 * "buffer_capacity" is how much is currently allocated,
142
128
 * "buffer_length" is how much is already used.
143
129
 */
144
 
size_t incbuffer(char **buffer, size_t buffer_length,
 
130
size_t adjustbuffer(char **buffer, size_t buffer_length,
145
131
                  size_t buffer_capacity){
146
 
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
 
132
  if (buffer_length + BUFFER_SIZE > buffer_capacity){
147
133
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
148
 
    if(buffer == NULL){
 
134
    if (buffer == NULL){
149
135
      return 0;
150
136
    }
151
137
    buffer_capacity += BUFFER_SIZE;
156
142
/* 
157
143
 * Initialize GPGME.
158
144
 */
159
 
static bool init_gpgme(const char *seckey,
 
145
static bool init_gpgme(mandos_context *mc, const char *seckey,
160
146
                       const char *pubkey, const char *tempdir){
161
147
  int ret;
162
148
  gpgme_error_t rc;
164
150
  
165
151
  
166
152
  /*
167
 
   * Helper function to insert pub and seckey to the engine keyring.
 
153
   * Helper function to insert pub and seckey to the enigne keyring.
168
154
   */
169
155
  bool import_key(const char *filename){
170
156
    int fd;
171
157
    gpgme_data_t pgp_data;
172
158
    
173
 
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
 
159
    fd = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
174
160
    if(fd == -1){
175
161
      perror("open");
176
162
      return false;
177
163
    }
178
164
    
179
165
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
180
 
    if(rc != GPG_ERR_NO_ERROR){
 
166
    if (rc != GPG_ERR_NO_ERROR){
181
167
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
182
168
              gpgme_strsource(rc), gpgme_strerror(rc));
183
169
      return false;
184
170
    }
185
171
    
186
 
    rc = gpgme_op_import(mc.ctx, pgp_data);
187
 
    if(rc != GPG_ERR_NO_ERROR){
 
172
    rc = gpgme_op_import(mc->ctx, pgp_data);
 
173
    if (rc != GPG_ERR_NO_ERROR){
188
174
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
189
175
              gpgme_strsource(rc), gpgme_strerror(rc));
190
176
      return false;
191
177
    }
192
178
    
193
 
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
 
179
    ret = TEMP_FAILURE_RETRY(close(fd));
194
180
    if(ret == -1){
195
181
      perror("close");
196
182
    }
198
184
    return true;
199
185
  }
200
186
  
201
 
  if(debug){
202
 
    fprintf(stderr, "Initializing GPGME\n");
 
187
  if (debug){
 
188
    fprintf(stderr, "Initialize gpgme\n");
203
189
  }
204
190
  
205
191
  /* Init GPGME */
206
192
  gpgme_check_version(NULL);
207
193
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
208
 
  if(rc != GPG_ERR_NO_ERROR){
 
194
  if (rc != GPG_ERR_NO_ERROR){
209
195
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
210
196
            gpgme_strsource(rc), gpgme_strerror(rc));
211
197
    return false;
212
198
  }
213
199
  
214
200
    /* Set GPGME home directory for the OpenPGP engine only */
215
 
  rc = gpgme_get_engine_info(&engine_info);
216
 
  if(rc != GPG_ERR_NO_ERROR){
 
201
  rc = gpgme_get_engine_info (&engine_info);
 
202
  if (rc != GPG_ERR_NO_ERROR){
217
203
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
218
204
            gpgme_strsource(rc), gpgme_strerror(rc));
219
205
    return false;
232
218
  }
233
219
  
234
220
  /* Create new GPGME "context" */
235
 
  rc = gpgme_new(&(mc.ctx));
236
 
  if(rc != GPG_ERR_NO_ERROR){
 
221
  rc = gpgme_new(&(mc->ctx));
 
222
  if (rc != GPG_ERR_NO_ERROR){
237
223
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
238
224
            gpgme_strsource(rc), gpgme_strerror(rc));
239
225
    return false;
240
226
  }
241
227
  
242
 
  if(not import_key(pubkey) or not import_key(seckey)){
 
228
  if (not import_key(pubkey) or not import_key(seckey)){
243
229
    return false;
244
230
  }
245
231
  
250
236
 * Decrypt OpenPGP data.
251
237
 * Returns -1 on error
252
238
 */
253
 
static ssize_t pgp_packet_decrypt(const char *cryptotext,
254
 
                                  size_t crypto_size,
255
 
                                  char **plaintext){
 
239
static ssize_t pgp_packet_decrypt (const mandos_context *mc,
 
240
                                   const char *cryptotext,
 
241
                                   size_t crypto_size,
 
242
                                   char **plaintext){
256
243
  gpgme_data_t dh_crypto, dh_plain;
257
244
  gpgme_error_t rc;
258
245
  ssize_t ret;
259
246
  size_t plaintext_capacity = 0;
260
247
  ssize_t plaintext_length = 0;
261
248
  
262
 
  if(debug){
 
249
  if (debug){
263
250
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
264
251
  }
265
252
  
266
253
  /* Create new GPGME data buffer from memory cryptotext */
267
254
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
268
255
                               0);
269
 
  if(rc != GPG_ERR_NO_ERROR){
 
256
  if (rc != GPG_ERR_NO_ERROR){
270
257
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
271
258
            gpgme_strsource(rc), gpgme_strerror(rc));
272
259
    return -1;
274
261
  
275
262
  /* Create new empty GPGME data buffer for the plaintext */
276
263
  rc = gpgme_data_new(&dh_plain);
277
 
  if(rc != GPG_ERR_NO_ERROR){
 
264
  if (rc != GPG_ERR_NO_ERROR){
278
265
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
279
266
            gpgme_strsource(rc), gpgme_strerror(rc));
280
267
    gpgme_data_release(dh_crypto);
283
270
  
284
271
  /* Decrypt data from the cryptotext data buffer to the plaintext
285
272
     data buffer */
286
 
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
287
 
  if(rc != GPG_ERR_NO_ERROR){
 
273
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
 
274
  if (rc != GPG_ERR_NO_ERROR){
288
275
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
289
276
            gpgme_strsource(rc), gpgme_strerror(rc));
290
277
    plaintext_length = -1;
291
 
    if(debug){
 
278
    if (debug){
292
279
      gpgme_decrypt_result_t result;
293
 
      result = gpgme_op_decrypt_result(mc.ctx);
294
 
      if(result == NULL){
 
280
      result = gpgme_op_decrypt_result(mc->ctx);
 
281
      if (result == NULL){
295
282
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
296
283
      } else {
297
284
        fprintf(stderr, "Unsupported algorithm: %s\n",
324
311
  }
325
312
  
326
313
  /* Seek back to the beginning of the GPGME plaintext data buffer */
327
 
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
 
314
  if (gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET) == -1){
328
315
    perror("gpgme_data_seek");
329
316
    plaintext_length = -1;
330
317
    goto decrypt_end;
332
319
  
333
320
  *plaintext = NULL;
334
321
  while(true){
335
 
    plaintext_capacity = incbuffer(plaintext,
 
322
    plaintext_capacity = adjustbuffer(plaintext,
336
323
                                      (size_t)plaintext_length,
337
324
                                      plaintext_capacity);
338
 
    if(plaintext_capacity == 0){
339
 
        perror("incbuffer");
 
325
    if (plaintext_capacity == 0){
 
326
        perror("adjustbuffer");
340
327
        plaintext_length = -1;
341
328
        goto decrypt_end;
342
329
    }
344
331
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
345
332
                          BUFFER_SIZE);
346
333
    /* Print the data, if any */
347
 
    if(ret == 0){
 
334
    if (ret == 0){
348
335
      /* EOF */
349
336
      break;
350
337
    }
374
361
  return plaintext_length;
375
362
}
376
363
 
377
 
static const char * safer_gnutls_strerror(int value){
378
 
  const char *ret = gnutls_strerror(value); /* Spurious warning from
379
 
                                               -Wunreachable-code */
380
 
  if(ret == NULL)
 
364
static const char * safer_gnutls_strerror (int value) {
 
365
  const char *ret = gnutls_strerror (value); /* Spurious warning */
 
366
  if (ret == NULL)
381
367
    ret = "(unknown)";
382
368
  return ret;
383
369
}
388
374
  fprintf(stderr, "GnuTLS: %s", string);
389
375
}
390
376
 
391
 
static int init_gnutls_global(const char *pubkeyfilename,
 
377
static int init_gnutls_global(mandos_context *mc,
 
378
                              const char *pubkeyfilename,
392
379
                              const char *seckeyfilename){
393
380
  int ret;
394
381
  
397
384
  }
398
385
  
399
386
  ret = gnutls_global_init();
400
 
  if(ret != GNUTLS_E_SUCCESS){
401
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
402
 
            safer_gnutls_strerror(ret));
 
387
  if (ret != GNUTLS_E_SUCCESS) {
 
388
    fprintf (stderr, "GnuTLS global_init: %s\n",
 
389
             safer_gnutls_strerror(ret));
403
390
    return -1;
404
391
  }
405
392
  
406
 
  if(debug){
 
393
  if (debug){
407
394
    /* "Use a log level over 10 to enable all debugging options."
408
395
     * - GnuTLS manual
409
396
     */
412
399
  }
413
400
  
414
401
  /* OpenPGP credentials */
415
 
  gnutls_certificate_allocate_credentials(&mc.cred);
416
 
  if(ret != GNUTLS_E_SUCCESS){
417
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
418
 
                                                    from
419
 
                                                    -Wunreachable-code
420
 
                                                 */
421
 
            safer_gnutls_strerror(ret));
422
 
    gnutls_global_deinit();
 
402
  gnutls_certificate_allocate_credentials(&mc->cred);
 
403
  if (ret != GNUTLS_E_SUCCESS){
 
404
    fprintf (stderr, "GnuTLS memory error: %s\n", /* Spurious
 
405
                                                     warning */
 
406
             safer_gnutls_strerror(ret));
 
407
    gnutls_global_deinit ();
423
408
    return -1;
424
409
  }
425
410
  
430
415
  }
431
416
  
432
417
  ret = gnutls_certificate_set_openpgp_key_file
433
 
    (mc.cred, pubkeyfilename, seckeyfilename,
 
418
    (mc->cred, pubkeyfilename, seckeyfilename,
434
419
     GNUTLS_OPENPGP_FMT_BASE64);
435
 
  if(ret != GNUTLS_E_SUCCESS){
 
420
  if (ret != GNUTLS_E_SUCCESS) {
436
421
    fprintf(stderr,
437
422
            "Error[%d] while reading the OpenPGP key pair ('%s',"
438
423
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
442
427
  }
443
428
  
444
429
  /* GnuTLS server initialization */
445
 
  ret = gnutls_dh_params_init(&mc.dh_params);
446
 
  if(ret != GNUTLS_E_SUCCESS){
447
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
448
 
            " %s\n", safer_gnutls_strerror(ret));
 
430
  ret = gnutls_dh_params_init(&mc->dh_params);
 
431
  if (ret != GNUTLS_E_SUCCESS) {
 
432
    fprintf (stderr, "Error in GnuTLS DH parameter initialization:"
 
433
             " %s\n", safer_gnutls_strerror(ret));
449
434
    goto globalfail;
450
435
  }
451
 
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
452
 
  if(ret != GNUTLS_E_SUCCESS){
453
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
454
 
            safer_gnutls_strerror(ret));
 
436
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
437
  if (ret != GNUTLS_E_SUCCESS) {
 
438
    fprintf (stderr, "Error in GnuTLS prime generation: %s\n",
 
439
             safer_gnutls_strerror(ret));
455
440
    goto globalfail;
456
441
  }
457
442
  
458
 
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
 
443
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
459
444
  
460
445
  return 0;
461
446
  
462
447
 globalfail:
463
448
  
464
 
  gnutls_certificate_free_credentials(mc.cred);
 
449
  gnutls_certificate_free_credentials(mc->cred);
465
450
  gnutls_global_deinit();
466
 
  gnutls_dh_params_deinit(mc.dh_params);
 
451
  gnutls_dh_params_deinit(mc->dh_params);
467
452
  return -1;
468
453
}
469
454
 
470
 
static int init_gnutls_session(gnutls_session_t *session){
 
455
static int init_gnutls_session(mandos_context *mc,
 
456
                               gnutls_session_t *session){
471
457
  int ret;
472
458
  /* GnuTLS session creation */
473
459
  ret = gnutls_init(session, GNUTLS_SERVER);
474
 
  if(ret != GNUTLS_E_SUCCESS){
 
460
  if (ret != GNUTLS_E_SUCCESS){
475
461
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
476
462
            safer_gnutls_strerror(ret));
477
463
  }
478
464
  
479
465
  {
480
466
    const char *err;
481
 
    ret = gnutls_priority_set_direct(*session, mc.priority, &err);
482
 
    if(ret != GNUTLS_E_SUCCESS){
 
467
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
 
468
    if (ret != GNUTLS_E_SUCCESS) {
483
469
      fprintf(stderr, "Syntax error at: %s\n", err);
484
470
      fprintf(stderr, "GnuTLS error: %s\n",
485
471
              safer_gnutls_strerror(ret));
486
 
      gnutls_deinit(*session);
 
472
      gnutls_deinit (*session);
487
473
      return -1;
488
474
    }
489
475
  }
490
476
  
491
477
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
492
 
                               mc.cred);
493
 
  if(ret != GNUTLS_E_SUCCESS){
 
478
                               mc->cred);
 
479
  if (ret != GNUTLS_E_SUCCESS) {
494
480
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
495
481
            safer_gnutls_strerror(ret));
496
 
    gnutls_deinit(*session);
 
482
    gnutls_deinit (*session);
497
483
    return -1;
498
484
  }
499
485
  
500
486
  /* ignore client certificate if any. */
501
 
  gnutls_certificate_server_set_request(*session,
502
 
                                        GNUTLS_CERT_IGNORE);
 
487
  gnutls_certificate_server_set_request (*session,
 
488
                                         GNUTLS_CERT_IGNORE);
503
489
  
504
 
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
490
  gnutls_dh_set_prime_bits (*session, mc->dh_bits);
505
491
  
506
492
  return 0;
507
493
}
513
499
/* Called when a Mandos server is found */
514
500
static int start_mandos_communication(const char *ip, uint16_t port,
515
501
                                      AvahiIfIndex if_index,
516
 
                                      int af){
 
502
                                      mandos_context *mc){
517
503
  int ret, tcp_sd;
518
 
  ssize_t sret;
519
 
  union {
520
 
    struct sockaddr_in in;
521
 
    struct sockaddr_in6 in6;
522
 
  } to;
 
504
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
523
505
  char *buffer = NULL;
524
506
  char *decrypted_buffer;
525
507
  size_t buffer_length = 0;
527
509
  ssize_t decrypted_buffer_size;
528
510
  size_t written;
529
511
  int retval = 0;
 
512
  char interface[IF_NAMESIZE];
530
513
  gnutls_session_t session;
531
 
  int pf;                       /* Protocol family */
532
 
  
533
 
  switch(af){
534
 
  case AF_INET6:
535
 
    pf = PF_INET6;
536
 
    break;
537
 
  case AF_INET:
538
 
    pf = PF_INET;
539
 
    break;
540
 
  default:
541
 
    fprintf(stderr, "Bad address family: %d\n", af);
542
 
    return -1;
543
 
  }
544
 
  
545
 
  ret = init_gnutls_session(&session);
546
 
  if(ret != 0){
 
514
  
 
515
  ret = init_gnutls_session (mc, &session);
 
516
  if (ret != 0){
547
517
    return -1;
548
518
  }
549
519
  
550
520
  if(debug){
551
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
521
    fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
552
522
            "\n", ip, port);
553
523
  }
554
524
  
555
 
  tcp_sd = socket(pf, SOCK_STREAM, 0);
556
 
  if(tcp_sd < 0){
 
525
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
 
526
  if(tcp_sd < 0) {
557
527
    perror("socket");
558
528
    return -1;
559
529
  }
560
530
  
 
531
  if(debug){
 
532
    if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
533
      perror("if_indextoname");
 
534
      return -1;
 
535
    }
 
536
    fprintf(stderr, "Binding to interface %s\n", interface);
 
537
  }
 
538
  
561
539
  memset(&to, 0, sizeof(to));
562
 
  if(af == AF_INET6){
563
 
    to.in6.sin6_family = (uint16_t)af;
564
 
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
565
 
  } else {                      /* IPv4 */
566
 
    to.in.sin_family = (sa_family_t)af;
567
 
    ret = inet_pton(af, ip, &to.in.sin_addr);
568
 
  }
569
 
  if(ret < 0 ){
 
540
  to.in6.sin6_family = AF_INET6;
 
541
  /* It would be nice to have a way to detect if we were passed an
 
542
     IPv4 address here.   Now we assume an IPv6 address. */
 
543
  ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
 
544
  if (ret < 0 ){
570
545
    perror("inet_pton");
571
546
    return -1;
572
547
  }
574
549
    fprintf(stderr, "Bad address: %s\n", ip);
575
550
    return -1;
576
551
  }
577
 
  if(af == AF_INET6){
578
 
    to.in6.sin6_port = htons(port); /* Spurious warnings from
579
 
                                       -Wconversion and
580
 
                                       -Wunreachable-code */
581
 
    
582
 
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
583
 
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
584
 
                              -Wunreachable-code*/
585
 
      if(if_index == AVAHI_IF_UNSPEC){
586
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
587
 
                " without a network interface\n");
588
 
        return -1;
589
 
      }
590
 
      /* Set the network interface number as scope */
591
 
      to.in6.sin6_scope_id = (uint32_t)if_index;
592
 
    }
593
 
  } else {
594
 
    to.in.sin_port = htons(port); /* Spurious warnings from
595
 
                                     -Wconversion and
596
 
                                     -Wunreachable-code */
597
 
  }
 
552
  to.in6.sin6_port = htons(port); /* Spurious warning */
 
553
  
 
554
  to.in6.sin6_scope_id = (uint32_t)if_index;
598
555
  
599
556
  if(debug){
600
 
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
601
 
      char interface[IF_NAMESIZE];
602
 
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
603
 
        perror("if_indextoname");
604
 
      } else {
605
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
606
 
                ip, interface, port);
607
 
      }
608
 
    } else {
609
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
610
 
              port);
611
 
    }
612
 
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
613
 
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
614
 
    const char *pcret;
615
 
    if(af == AF_INET6){
616
 
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
617
 
                        sizeof(addrstr));
618
 
    } else {
619
 
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
620
 
                        sizeof(addrstr));
621
 
    }
622
 
    if(pcret == NULL){
 
557
    fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
558
            port);
 
559
    char addrstr[INET6_ADDRSTRLEN] = "";
 
560
    if(inet_ntop(to.in6.sin6_family, &(to.in6.sin6_addr), addrstr,
 
561
                 sizeof(addrstr)) == NULL){
623
562
      perror("inet_ntop");
624
563
    } else {
625
564
      if(strcmp(addrstr, ip) != 0){
628
567
    }
629
568
  }
630
569
  
631
 
  if(af == AF_INET6){
632
 
    ret = connect(tcp_sd, &to.in6, sizeof(to));
633
 
  } else {
634
 
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
635
 
  }
636
 
  if(ret < 0){
 
570
  ret = connect(tcp_sd, &to.in, sizeof(to));
 
571
  if (ret < 0){
637
572
    perror("connect");
638
573
    return -1;
639
574
  }
640
575
  
641
576
  const char *out = mandos_protocol_version;
642
577
  written = 0;
643
 
  while(true){
 
578
  while (true){
644
579
    size_t out_size = strlen(out);
645
 
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
 
580
    ret = TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
646
581
                                   out_size - written));
647
 
    if(ret == -1){
 
582
    if (ret == -1){
648
583
      perror("write");
649
584
      retval = -1;
650
585
      goto mandos_end;
653
588
    if(written < out_size){
654
589
      continue;
655
590
    } else {
656
 
      if(out == mandos_protocol_version){
 
591
      if (out == mandos_protocol_version){
657
592
        written = 0;
658
593
        out = "\r\n";
659
594
      } else {
666
601
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
667
602
  }
668
603
  
669
 
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
 
604
  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) tcp_sd);
670
605
  
671
606
  do{
672
 
    ret = gnutls_handshake(session);
 
607
    ret = gnutls_handshake (session);
673
608
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
674
609
  
675
 
  if(ret != GNUTLS_E_SUCCESS){
 
610
  if (ret != GNUTLS_E_SUCCESS){
676
611
    if(debug){
677
612
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
678
 
      gnutls_perror(ret);
 
613
      gnutls_perror (ret);
679
614
    }
680
615
    retval = -1;
681
616
    goto mandos_end;
684
619
  /* Read OpenPGP packet that contains the wanted password */
685
620
  
686
621
  if(debug){
687
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
622
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
688
623
            ip);
689
624
  }
690
625
  
691
626
  while(true){
692
 
    buffer_capacity = incbuffer(&buffer, buffer_length,
 
627
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
693
628
                                   buffer_capacity);
694
 
    if(buffer_capacity == 0){
695
 
      perror("incbuffer");
 
629
    if (buffer_capacity == 0){
 
630
      perror("adjustbuffer");
696
631
      retval = -1;
697
632
      goto mandos_end;
698
633
    }
699
634
    
700
 
    sret = gnutls_record_recv(session, buffer+buffer_length,
701
 
                              BUFFER_SIZE);
702
 
    if(sret == 0){
 
635
    ret = gnutls_record_recv(session, buffer+buffer_length,
 
636
                             BUFFER_SIZE);
 
637
    if (ret == 0){
703
638
      break;
704
639
    }
705
 
    if(sret < 0){
706
 
      switch(sret){
 
640
    if (ret < 0){
 
641
      switch(ret){
707
642
      case GNUTLS_E_INTERRUPTED:
708
643
      case GNUTLS_E_AGAIN:
709
644
        break;
710
645
      case GNUTLS_E_REHANDSHAKE:
711
646
        do{
712
 
          ret = gnutls_handshake(session);
 
647
          ret = gnutls_handshake (session);
713
648
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
714
 
        if(ret < 0){
 
649
        if (ret < 0){
715
650
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
716
 
          gnutls_perror(ret);
 
651
          gnutls_perror (ret);
717
652
          retval = -1;
718
653
          goto mandos_end;
719
654
        }
722
657
        fprintf(stderr, "Unknown error while reading data from"
723
658
                " encrypted session with Mandos server\n");
724
659
        retval = -1;
725
 
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
660
        gnutls_bye (session, GNUTLS_SHUT_RDWR);
726
661
        goto mandos_end;
727
662
      }
728
663
    } else {
729
 
      buffer_length += (size_t) sret;
 
664
      buffer_length += (size_t) ret;
730
665
    }
731
666
  }
732
667
  
734
669
    fprintf(stderr, "Closing TLS session\n");
735
670
  }
736
671
  
737
 
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
672
  gnutls_bye (session, GNUTLS_SHUT_RDWR);
738
673
  
739
 
  if(buffer_length > 0){
740
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
674
  if (buffer_length > 0){
 
675
    decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
741
676
                                               buffer_length,
742
677
                                               &decrypted_buffer);
743
 
    if(decrypted_buffer_size >= 0){
 
678
    if (decrypted_buffer_size >= 0){
744
679
      written = 0;
745
680
      while(written < (size_t) decrypted_buffer_size){
746
 
        ret = (int)fwrite(decrypted_buffer + written, 1,
747
 
                          (size_t)decrypted_buffer_size - written,
748
 
                          stdout);
 
681
        ret = (int)fwrite (decrypted_buffer + written, 1,
 
682
                           (size_t)decrypted_buffer_size - written,
 
683
                           stdout);
749
684
        if(ret == 0 and ferror(stdout)){
750
685
          if(debug){
751
686
            fprintf(stderr, "Error writing encrypted data: %s\n",
768
703
  
769
704
 mandos_end:
770
705
  free(buffer);
771
 
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
706
  ret = TEMP_FAILURE_RETRY(close(tcp_sd));
772
707
  if(ret == -1){
773
708
    perror("close");
774
709
  }
775
 
  gnutls_deinit(session);
 
710
  gnutls_deinit (session);
776
711
  return retval;
777
712
}
778
713
 
779
714
static void resolve_callback(AvahiSServiceResolver *r,
780
715
                             AvahiIfIndex interface,
781
 
                             AvahiProtocol proto,
 
716
                             AVAHI_GCC_UNUSED AvahiProtocol protocol,
782
717
                             AvahiResolverEvent event,
783
718
                             const char *name,
784
719
                             const char *type,
789
724
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
790
725
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
791
726
                             flags,
792
 
                             AVAHI_GCC_UNUSED void* userdata){
 
727
                             void* userdata) {
 
728
  mandos_context *mc = userdata;
793
729
  assert(r);
794
730
  
795
731
  /* Called whenever a service has been resolved successfully or
796
732
     timed out */
797
733
  
798
 
  switch(event){
 
734
  switch (event) {
799
735
  default:
800
736
  case AVAHI_RESOLVER_FAILURE:
801
737
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
802
738
            " of type '%s' in domain '%s': %s\n", name, type, domain,
803
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
739
            avahi_strerror(avahi_server_errno(mc->server)));
804
740
    break;
805
741
    
806
742
  case AVAHI_RESOLVER_FOUND:
809
745
      avahi_address_snprint(ip, sizeof(ip), address);
810
746
      if(debug){
811
747
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
812
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
813
 
                ip, (intmax_t)interface, port);
 
748
                PRIu16 ") on port %d\n", name, host_name, ip,
 
749
                interface, port);
814
750
      }
815
 
      int ret = start_mandos_communication(ip, port, interface,
816
 
                                           avahi_proto_to_af(proto));
817
 
      if(ret == 0){
818
 
        avahi_simple_poll_quit(mc.simple_poll);
 
751
      int ret = start_mandos_communication(ip, port, interface, mc);
 
752
      if (ret == 0){
 
753
        avahi_simple_poll_quit(mc->simple_poll);
819
754
      }
820
755
    }
821
756
  }
822
757
  avahi_s_service_resolver_free(r);
823
758
}
824
759
 
825
 
static void browse_callback(AvahiSServiceBrowser *b,
826
 
                            AvahiIfIndex interface,
827
 
                            AvahiProtocol protocol,
828
 
                            AvahiBrowserEvent event,
829
 
                            const char *name,
830
 
                            const char *type,
831
 
                            const char *domain,
832
 
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
833
 
                            flags,
834
 
                            AVAHI_GCC_UNUSED void* userdata){
 
760
static void browse_callback( AvahiSServiceBrowser *b,
 
761
                             AvahiIfIndex interface,
 
762
                             AvahiProtocol protocol,
 
763
                             AvahiBrowserEvent event,
 
764
                             const char *name,
 
765
                             const char *type,
 
766
                             const char *domain,
 
767
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
 
768
                             flags,
 
769
                             void* userdata) {
 
770
  mandos_context *mc = userdata;
835
771
  assert(b);
836
772
  
837
773
  /* Called whenever a new services becomes available on the LAN or
838
774
     is removed from the LAN */
839
775
  
840
 
  switch(event){
 
776
  switch (event) {
841
777
  default:
842
778
  case AVAHI_BROWSER_FAILURE:
843
779
    
844
780
    fprintf(stderr, "(Avahi browser) %s\n",
845
 
            avahi_strerror(avahi_server_errno(mc.server)));
846
 
    avahi_simple_poll_quit(mc.simple_poll);
 
781
            avahi_strerror(avahi_server_errno(mc->server)));
 
782
    avahi_simple_poll_quit(mc->simple_poll);
847
783
    return;
848
784
    
849
785
  case AVAHI_BROWSER_NEW:
852
788
       the callback function is called the Avahi server will free the
853
789
       resolver for us. */
854
790
    
855
 
    if(!(avahi_s_service_resolver_new(mc.server, interface,
 
791
    if (!(avahi_s_service_resolver_new(mc->server, interface,
856
792
                                       protocol, name, type, domain,
857
793
                                       AVAHI_PROTO_INET6, 0,
858
 
                                       resolve_callback, NULL)))
 
794
                                       resolve_callback, mc)))
859
795
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
860
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
796
              name, avahi_strerror(avahi_server_errno(mc->server)));
861
797
    break;
862
798
    
863
799
  case AVAHI_BROWSER_REMOVE:
872
808
  }
873
809
}
874
810
 
875
 
sig_atomic_t quit_now = 0;
876
 
 
877
 
static void handle_sigterm(__attribute__((unused)) int sig){
878
 
  if(quit_now){
879
 
    return;
880
 
  }
881
 
  quit_now = 1;
882
 
  int old_errno = errno;
883
 
  if(mc.simple_poll != NULL){
884
 
    avahi_simple_poll_quit(mc.simple_poll);
885
 
  }
886
 
  errno = old_errno;
887
 
}
888
 
 
889
811
int main(int argc, char *argv[]){
890
 
  AvahiSServiceBrowser *sb = NULL;
891
 
  int error;
892
 
  int ret;
893
 
  intmax_t tmpmax;
894
 
  int numchars;
895
 
  int exitcode = EXIT_SUCCESS;
896
 
  const char *interface = "eth0";
897
 
  struct ifreq network;
898
 
  int sd;
899
 
  uid_t uid;
900
 
  gid_t gid;
901
 
  char *connect_to = NULL;
902
 
  char tempdir[] = "/tmp/mandosXXXXXX";
903
 
  bool tempdir_created = false;
904
 
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
905
 
  const char *seckey = PATHDIR "/" SECKEY;
906
 
  const char *pubkey = PATHDIR "/" PUBKEY;
907
 
  
908
 
  /* Initialize Mandos context */
909
 
  mc = (mandos_context){ .simple_poll = NULL, .server = NULL,
910
 
                         .dh_bits = 1024, .priority = "SECURE256"
911
 
                         ":!CTYPE-X.509:+CTYPE-OPENPGP" };
912
 
  bool gnutls_initialized = false;
913
 
  bool gpgme_initialized = false;
914
 
  double delay = 2.5;
915
 
 
916
 
  struct sigaction old_sigterm_action;
917
 
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
918
 
  
919
 
  {
920
 
    struct argp_option options[] = {
921
 
      { .name = "debug", .key = 128,
922
 
        .doc = "Debug mode", .group = 3 },
923
 
      { .name = "connect", .key = 'c',
924
 
        .arg = "ADDRESS:PORT",
925
 
        .doc = "Connect directly to a specific Mandos server",
926
 
        .group = 1 },
927
 
      { .name = "interface", .key = 'i',
928
 
        .arg = "NAME",
929
 
        .doc = "Network interface that will be used to search for"
930
 
        " Mandos servers",
931
 
        .group = 1 },
932
 
      { .name = "seckey", .key = 's',
933
 
        .arg = "FILE",
934
 
        .doc = "OpenPGP secret key file base name",
935
 
        .group = 1 },
936
 
      { .name = "pubkey", .key = 'p',
937
 
        .arg = "FILE",
938
 
        .doc = "OpenPGP public key file base name",
939
 
        .group = 2 },
940
 
      { .name = "dh-bits", .key = 129,
941
 
        .arg = "BITS",
942
 
        .doc = "Bit length of the prime number used in the"
943
 
        " Diffie-Hellman key exchange",
944
 
        .group = 2 },
945
 
      { .name = "priority", .key = 130,
946
 
        .arg = "STRING",
947
 
        .doc = "GnuTLS priority string for the TLS handshake",
948
 
        .group = 1 },
949
 
      { .name = "delay", .key = 131,
950
 
        .arg = "SECONDS",
951
 
        .doc = "Maximum delay to wait for interface startup",
952
 
        .group = 2 },
953
 
      { .name = NULL }
954
 
    };
955
 
    
956
 
    error_t parse_opt(int key, char *arg,
957
 
                      struct argp_state *state){
958
 
      switch(key){
959
 
      case 128:                 /* --debug */
960
 
        debug = true;
961
 
        break;
962
 
      case 'c':                 /* --connect */
963
 
        connect_to = arg;
964
 
        break;
965
 
      case 'i':                 /* --interface */
966
 
        interface = arg;
967
 
        break;
968
 
      case 's':                 /* --seckey */
969
 
        seckey = arg;
970
 
        break;
971
 
      case 'p':                 /* --pubkey */
972
 
        pubkey = arg;
973
 
        break;
974
 
      case 129:                 /* --dh-bits */
975
 
        ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
976
 
        if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
977
 
           or arg[numchars] != '\0'){
978
 
          fprintf(stderr, "Bad number of DH bits\n");
979
 
          exit(EXIT_FAILURE);
980
 
        }
981
 
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
982
 
        break;
983
 
      case 130:                 /* --priority */
984
 
        mc.priority = arg;
985
 
        break;
986
 
      case 131:                 /* --delay */
987
 
        ret = sscanf(arg, "%lf%n", &delay, &numchars);
988
 
        if(ret < 1 or arg[numchars] != '\0'){
989
 
          fprintf(stderr, "Bad delay\n");
990
 
          exit(EXIT_FAILURE);
991
 
        }
992
 
        break;
993
 
      case ARGP_KEY_ARG:
994
 
        argp_usage(state);
995
 
      case ARGP_KEY_END:
996
 
        break;
997
 
      default:
998
 
        return ARGP_ERR_UNKNOWN;
999
 
      }
1000
 
      return 0;
1001
 
    }
1002
 
    
1003
 
    struct argp argp = { .options = options, .parser = parse_opt,
1004
 
                         .args_doc = "",
1005
 
                         .doc = "Mandos client -- Get and decrypt"
1006
 
                         " passwords from a Mandos server" };
1007
 
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
1008
 
    if(ret == ARGP_ERR_UNKNOWN){
1009
 
      fprintf(stderr, "Unknown error while parsing arguments\n");
1010
 
      exitcode = EXIT_FAILURE;
1011
 
      goto end;
1012
 
    }
1013
 
  }
1014
 
  
1015
 
  /* If the interface is down, bring it up */
1016
 
  if(interface[0] != '\0'){
1017
 
#ifdef __linux__
1018
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1019
 
       messages to mess up the prompt */
1020
 
    ret = klogctl(8, NULL, 5);
1021
 
    bool restore_loglevel = true;
1022
 
    if(ret == -1){
1023
 
      restore_loglevel = false;
1024
 
      perror("klogctl");
1025
 
    }
1026
 
#endif  /* __linux__ */
1027
 
    
1028
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1029
 
    if(sd < 0){
1030
 
      perror("socket");
1031
 
      exitcode = EXIT_FAILURE;
1032
 
#ifdef __linux__
1033
 
      if(restore_loglevel){
1034
 
        ret = klogctl(7, NULL, 0);
1035
 
        if(ret == -1){
1036
 
          perror("klogctl");
1037
 
        }
1038
 
      }
1039
 
#endif  /* __linux__ */
1040
 
      goto end;
1041
 
    }
1042
 
    strcpy(network.ifr_name, interface);
1043
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1044
 
    if(ret == -1){
1045
 
      perror("ioctl SIOCGIFFLAGS");
1046
 
#ifdef __linux__
1047
 
      if(restore_loglevel){
1048
 
        ret = klogctl(7, NULL, 0);
1049
 
        if(ret == -1){
1050
 
          perror("klogctl");
1051
 
        }
1052
 
      }
1053
 
#endif  /* __linux__ */
1054
 
      exitcode = EXIT_FAILURE;
1055
 
      goto end;
1056
 
    }
1057
 
    if((network.ifr_flags & IFF_UP) == 0){
1058
 
      network.ifr_flags |= IFF_UP;
1059
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1060
 
      if(ret == -1){
1061
 
        perror("ioctl SIOCSIFFLAGS");
1062
 
        exitcode = EXIT_FAILURE;
1063
 
#ifdef __linux__
1064
 
        if(restore_loglevel){
1065
 
          ret = klogctl(7, NULL, 0);
1066
 
          if(ret == -1){
1067
 
            perror("klogctl");
 
812
    AvahiSServiceBrowser *sb = NULL;
 
813
    int error;
 
814
    int ret;
 
815
    int exitcode = EXIT_SUCCESS;
 
816
    const char *interface = "eth0";
 
817
    struct ifreq network;
 
818
    int sd;
 
819
    uid_t uid;
 
820
    gid_t gid;
 
821
    char *connect_to = NULL;
 
822
    char tempdir[] = "/tmp/mandosXXXXXX";
 
823
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
 
824
    const char *seckey = PATHDIR "/" SECKEY;
 
825
    const char *pubkey = PATHDIR "/" PUBKEY;
 
826
    
 
827
    mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
828
                          .dh_bits = 1024, .priority = "SECURE256"
 
829
                          ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
830
    bool gnutls_initalized = false;
 
831
    bool gpgme_initalized = false;
 
832
    
 
833
    {
 
834
      struct argp_option options[] = {
 
835
        { .name = "debug", .key = 128,
 
836
          .doc = "Debug mode", .group = 3 },
 
837
        { .name = "connect", .key = 'c',
 
838
          .arg = "ADDRESS:PORT",
 
839
          .doc = "Connect directly to a specific Mandos server",
 
840
          .group = 1 },
 
841
        { .name = "interface", .key = 'i',
 
842
          .arg = "NAME",
 
843
          .doc = "Interface that will be used to search for Mandos"
 
844
          " servers",
 
845
          .group = 1 },
 
846
        { .name = "seckey", .key = 's',
 
847
          .arg = "FILE",
 
848
          .doc = "OpenPGP secret key file base name",
 
849
          .group = 1 },
 
850
        { .name = "pubkey", .key = 'p',
 
851
          .arg = "FILE",
 
852
          .doc = "OpenPGP public key file base name",
 
853
          .group = 2 },
 
854
        { .name = "dh-bits", .key = 129,
 
855
          .arg = "BITS",
 
856
          .doc = "Bit length of the prime number used in the"
 
857
          " Diffie-Hellman key exchange",
 
858
          .group = 2 },
 
859
        { .name = "priority", .key = 130,
 
860
          .arg = "STRING",
 
861
          .doc = "GnuTLS priority string for the TLS handshake",
 
862
          .group = 1 },
 
863
        { .name = NULL }
 
864
      };
 
865
      
 
866
      error_t parse_opt (int key, char *arg,
 
867
                         struct argp_state *state) {
 
868
        /* Get the INPUT argument from `argp_parse', which we know is
 
869
           a pointer to our plugin list pointer. */
 
870
        switch (key) {
 
871
        case 128:               /* --debug */
 
872
          debug = true;
 
873
          break;
 
874
        case 'c':               /* --connect */
 
875
          connect_to = arg;
 
876
          break;
 
877
        case 'i':               /* --interface */
 
878
          interface = arg;
 
879
          break;
 
880
        case 's':               /* --seckey */
 
881
          seckey = arg;
 
882
          break;
 
883
        case 'p':               /* --pubkey */
 
884
          pubkey = arg;
 
885
          break;
 
886
        case 129:               /* --dh-bits */
 
887
          errno = 0;
 
888
          mc.dh_bits = (unsigned int) strtol(arg, NULL, 10);
 
889
          if (errno){
 
890
            perror("strtol");
 
891
            exit(EXIT_FAILURE);
1068
892
          }
 
893
          break;
 
894
        case 130:               /* --priority */
 
895
          mc.priority = arg;
 
896
          break;
 
897
        case ARGP_KEY_ARG:
 
898
          argp_usage (state);
 
899
        case ARGP_KEY_END:
 
900
          break;
 
901
        default:
 
902
          return ARGP_ERR_UNKNOWN;
1069
903
        }
1070
 
#endif  /* __linux__ */
 
904
        return 0;
 
905
      }
 
906
      
 
907
      struct argp argp = { .options = options, .parser = parse_opt,
 
908
                           .args_doc = "",
 
909
                           .doc = "Mandos client -- Get and decrypt"
 
910
                           " passwords from a Mandos server" };
 
911
      ret = argp_parse (&argp, argc, argv, 0, 0, NULL);
 
912
      if (ret == ARGP_ERR_UNKNOWN){
 
913
        fprintf(stderr, "Unknown error while parsing arguments\n");
 
914
        exitcode = EXIT_FAILURE;
1071
915
        goto end;
1072
916
      }
1073
917
    }
1074
 
    /* sleep checking until interface is running */
1075
 
    for(int i=0; i < delay * 4; i++){
 
918
    
 
919
    /* If the interface is down, bring it up */
 
920
    {
 
921
      sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
922
      if(sd < 0) {
 
923
        perror("socket");
 
924
        exitcode = EXIT_FAILURE;
 
925
        goto end;
 
926
      }
 
927
      strcpy(network.ifr_name, interface);
1076
928
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1077
929
      if(ret == -1){
1078
930
        perror("ioctl SIOCGIFFLAGS");
1079
 
      } else if(network.ifr_flags & IFF_RUNNING){
1080
 
        break;
1081
 
      }
1082
 
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1083
 
      ret = nanosleep(&sleeptime, NULL);
1084
 
      if(ret == -1 and errno != EINTR){
1085
 
        perror("nanosleep");
1086
 
      }
1087
 
    }
1088
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1089
 
    if(ret == -1){
1090
 
      perror("close");
1091
 
    }
1092
 
#ifdef __linux__
1093
 
    if(restore_loglevel){
1094
 
      /* Restores kernel loglevel to default */
1095
 
      ret = klogctl(7, NULL, 0);
 
931
        exitcode = EXIT_FAILURE;
 
932
        goto end;
 
933
      }
 
934
      if((network.ifr_flags & IFF_UP) == 0){
 
935
        network.ifr_flags |= IFF_UP;
 
936
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
937
        if(ret == -1){
 
938
          perror("ioctl SIOCSIFFLAGS");
 
939
          exitcode = EXIT_FAILURE;
 
940
          goto end;
 
941
        }
 
942
      }
 
943
      ret = TEMP_FAILURE_RETRY(close(sd));
1096
944
      if(ret == -1){
1097
 
        perror("klogctl");
 
945
        perror("close");
1098
946
      }
1099
947
    }
1100
 
#endif  /* __linux__ */
1101
 
  }
1102
 
  
1103
 
  uid = getuid();
1104
 
  gid = getgid();
1105
 
  
1106
 
  errno = 0;
1107
 
  setgid(gid);
1108
 
  if(ret == -1){
1109
 
    perror("setgid");
1110
 
  }
1111
 
  
1112
 
  ret = setuid(uid);
1113
 
  if(ret == -1){
1114
 
    perror("setuid");
1115
 
  }
1116
 
  
1117
 
  ret = init_gnutls_global(pubkey, seckey);
1118
 
  if(ret == -1){
1119
 
    fprintf(stderr, "init_gnutls_global failed\n");
1120
 
    exitcode = EXIT_FAILURE;
1121
 
    goto end;
1122
 
  } else {
1123
 
    gnutls_initialized = true;
1124
 
  }
1125
 
  
1126
 
  if(mkdtemp(tempdir) == NULL){
1127
 
    perror("mkdtemp");
1128
 
    goto end;
1129
 
  }
1130
 
  tempdir_created = true;
1131
 
  
1132
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
1133
 
    fprintf(stderr, "init_gpgme failed\n");
1134
 
    exitcode = EXIT_FAILURE;
1135
 
    goto end;
1136
 
  } else {
1137
 
    gpgme_initialized = true;
1138
 
  }
1139
 
  
1140
 
  if(interface[0] != '\0'){
 
948
    
 
949
    uid = getuid();
 
950
    gid = getgid();
 
951
    
 
952
    ret = setuid(uid);
 
953
    if (ret == -1){
 
954
      perror("setuid");
 
955
    }
 
956
    
 
957
    setgid(gid);
 
958
    if (ret == -1){
 
959
      perror("setgid");
 
960
    }
 
961
    
 
962
    ret = init_gnutls_global(&mc, pubkey, seckey);
 
963
    if (ret == -1){
 
964
      fprintf(stderr, "init_gnutls_global failed\n");
 
965
      exitcode = EXIT_FAILURE;
 
966
      goto end;
 
967
    } else {
 
968
      gnutls_initalized = true;
 
969
    }
 
970
    
 
971
    if(mkdtemp(tempdir) == NULL){
 
972
      perror("mkdtemp");
 
973
      tempdir[0] = '\0';
 
974
      goto end;
 
975
    }
 
976
    
 
977
    if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
 
978
      fprintf(stderr, "gpgme_initalized failed\n");
 
979
      exitcode = EXIT_FAILURE;
 
980
      goto end;
 
981
    } else {
 
982
      gpgme_initalized = true;
 
983
    }
 
984
    
1141
985
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1142
986
    if(if_index == 0){
1143
987
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1144
 
      exitcode = EXIT_FAILURE;
1145
 
      goto end;
1146
 
    }
1147
 
  }
1148
 
  
1149
 
  if(connect_to != NULL){
1150
 
    /* Connect directly, do not use Zeroconf */
1151
 
    /* (Mainly meant for debugging) */
1152
 
    char *address = strrchr(connect_to, ':');
1153
 
    if(address == NULL){
1154
 
      fprintf(stderr, "No colon in address\n");
1155
 
      exitcode = EXIT_FAILURE;
1156
 
      goto end;
1157
 
    }
1158
 
    uint16_t port;
1159
 
    ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
1160
 
    if(ret < 1 or tmpmax != (uint16_t)tmpmax
1161
 
       or address[numchars+1] != '\0'){
1162
 
      fprintf(stderr, "Bad port number\n");
1163
 
      exitcode = EXIT_FAILURE;
1164
 
      goto end;
1165
 
    }
1166
 
    port = (uint16_t)tmpmax;
1167
 
    *address = '\0';
1168
 
    address = connect_to;
1169
 
    /* Colon in address indicates IPv6 */
1170
 
    int af;
1171
 
    if(strchr(address, ':') != NULL){
1172
 
      af = AF_INET6;
1173
 
    } else {
1174
 
      af = AF_INET;
1175
 
    }
1176
 
    ret = start_mandos_communication(address, port, if_index, af);
1177
 
    if(ret < 0){
1178
 
      exitcode = EXIT_FAILURE;
1179
 
    } else {
1180
 
      exitcode = EXIT_SUCCESS;
1181
 
    }
1182
 
    goto end;
1183
 
  }
1184
 
  
1185
 
  if(not debug){
1186
 
    avahi_set_log_function(empty_log);
1187
 
  }
1188
 
  
1189
 
  /* Initialize the pseudo-RNG for Avahi */
1190
 
  srand((unsigned int) time(NULL));
1191
 
  
1192
 
  /* Allocate main Avahi loop object */
1193
 
  mc.simple_poll = avahi_simple_poll_new();
1194
 
  if(mc.simple_poll == NULL){
1195
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1196
 
    exitcode = EXIT_FAILURE;
1197
 
    goto end;
1198
 
  }
1199
 
  
1200
 
  {
1201
 
    AvahiServerConfig config;
1202
 
    /* Do not publish any local Zeroconf records */
1203
 
    avahi_server_config_init(&config);
1204
 
    config.publish_hinfo = 0;
1205
 
    config.publish_addresses = 0;
1206
 
    config.publish_workstation = 0;
1207
 
    config.publish_domain = 0;
1208
 
    
1209
 
    /* Allocate a new server */
1210
 
    mc.server = avahi_server_new(avahi_simple_poll_get
1211
 
                                 (mc.simple_poll), &config, NULL,
1212
 
                                 NULL, &error);
1213
 
    
1214
 
    /* Free the Avahi configuration data */
1215
 
    avahi_server_config_free(&config);
1216
 
  }
1217
 
  
1218
 
  /* Check if creating the Avahi server object succeeded */
1219
 
  if(mc.server == NULL){
1220
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1221
 
            avahi_strerror(error));
1222
 
    exitcode = EXIT_FAILURE;
1223
 
    goto end;
1224
 
  }
1225
 
  
1226
 
  /* Create the Avahi service browser */
1227
 
  sb = avahi_s_service_browser_new(mc.server, if_index,
1228
 
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
1229
 
                                   NULL, 0, browse_callback, NULL);
1230
 
  if(sb == NULL){
1231
 
    fprintf(stderr, "Failed to create service browser: %s\n",
1232
 
            avahi_strerror(avahi_server_errno(mc.server)));
1233
 
    exitcode = EXIT_FAILURE;
1234
 
    goto end;
1235
 
  }
1236
 
  
1237
 
  sigemptyset(&sigterm_action.sa_mask);
1238
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1239
 
  if(ret == -1){
1240
 
    perror("sigaddset");
1241
 
    exitcode = EXIT_FAILURE;
1242
 
    goto end;
1243
 
  }
1244
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1245
 
  if(ret == -1){
1246
 
    perror("sigaddset");
1247
 
    exitcode = EXIT_FAILURE;
1248
 
    goto end;
1249
 
  }
1250
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1251
 
  if(ret == -1){
1252
 
    perror("sigaddset");
1253
 
    exitcode = EXIT_FAILURE;
1254
 
    goto end;
1255
 
  }
1256
 
  ret = sigaction(SIGTERM, &sigterm_action, &old_sigterm_action);
1257
 
  if(ret == -1){
1258
 
    perror("sigaction");
1259
 
    exitcode = EXIT_FAILURE;
1260
 
    goto end;
1261
 
  }  
1262
 
  
1263
 
  /* Run the main loop */
1264
 
  
1265
 
  if(debug){
1266
 
    fprintf(stderr, "Starting Avahi loop search\n");
1267
 
  }
1268
 
  
1269
 
  avahi_simple_poll_loop(mc.simple_poll);
1270
 
  
 
988
      exit(EXIT_FAILURE);
 
989
    }
 
990
    
 
991
    if(connect_to != NULL){
 
992
      /* Connect directly, do not use Zeroconf */
 
993
      /* (Mainly meant for debugging) */
 
994
      char *address = strrchr(connect_to, ':');
 
995
      if(address == NULL){
 
996
        fprintf(stderr, "No colon in address\n");
 
997
        exitcode = EXIT_FAILURE;
 
998
        goto end;
 
999
      }
 
1000
      errno = 0;
 
1001
      uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
 
1002
      if(errno){
 
1003
        perror("Bad port number");
 
1004
        exitcode = EXIT_FAILURE;
 
1005
        goto end;
 
1006
      }
 
1007
      *address = '\0';
 
1008
      address = connect_to;
 
1009
      ret = start_mandos_communication(address, port, if_index, &mc);
 
1010
      if(ret < 0){
 
1011
        exitcode = EXIT_FAILURE;
 
1012
      } else {
 
1013
        exitcode = EXIT_SUCCESS;
 
1014
      }
 
1015
      goto end;
 
1016
    }
 
1017
    
 
1018
    if (not debug){
 
1019
      avahi_set_log_function(empty_log);
 
1020
    }
 
1021
    
 
1022
    /* Initialize the pseudo-RNG for Avahi */
 
1023
    srand((unsigned int) time(NULL));
 
1024
    
 
1025
    /* Allocate main Avahi loop object */
 
1026
    mc.simple_poll = avahi_simple_poll_new();
 
1027
    if (mc.simple_poll == NULL) {
 
1028
        fprintf(stderr, "Avahi: Failed to create simple poll"
 
1029
                " object.\n");
 
1030
        exitcode = EXIT_FAILURE;
 
1031
        goto end;
 
1032
    }
 
1033
    
 
1034
    {
 
1035
      AvahiServerConfig config;
 
1036
      /* Do not publish any local Zeroconf records */
 
1037
      avahi_server_config_init(&config);
 
1038
      config.publish_hinfo = 0;
 
1039
      config.publish_addresses = 0;
 
1040
      config.publish_workstation = 0;
 
1041
      config.publish_domain = 0;
 
1042
      
 
1043
      /* Allocate a new server */
 
1044
      mc.server = avahi_server_new(avahi_simple_poll_get
 
1045
                                   (mc.simple_poll), &config, NULL,
 
1046
                                   NULL, &error);
 
1047
      
 
1048
      /* Free the Avahi configuration data */
 
1049
      avahi_server_config_free(&config);
 
1050
    }
 
1051
    
 
1052
    /* Check if creating the Avahi server object succeeded */
 
1053
    if (mc.server == NULL) {
 
1054
        fprintf(stderr, "Failed to create Avahi server: %s\n",
 
1055
                avahi_strerror(error));
 
1056
        exitcode = EXIT_FAILURE;
 
1057
        goto end;
 
1058
    }
 
1059
    
 
1060
    /* Create the Avahi service browser */
 
1061
    sb = avahi_s_service_browser_new(mc.server, if_index,
 
1062
                                     AVAHI_PROTO_INET6,
 
1063
                                     "_mandos._tcp", NULL, 0,
 
1064
                                     browse_callback, &mc);
 
1065
    if (sb == NULL) {
 
1066
        fprintf(stderr, "Failed to create service browser: %s\n",
 
1067
                avahi_strerror(avahi_server_errno(mc.server)));
 
1068
        exitcode = EXIT_FAILURE;
 
1069
        goto end;
 
1070
    }
 
1071
    
 
1072
    /* Run the main loop */
 
1073
    
 
1074
    if (debug){
 
1075
      fprintf(stderr, "Starting Avahi loop search\n");
 
1076
    }
 
1077
    
 
1078
    avahi_simple_poll_loop(mc.simple_poll);
 
1079
    
1271
1080
 end:
1272
 
  
1273
 
  if(debug){
1274
 
    fprintf(stderr, "%s exiting\n", argv[0]);
1275
 
  }
1276
 
  
1277
 
  /* Cleanup things */
1278
 
  if(sb != NULL)
1279
 
    avahi_s_service_browser_free(sb);
1280
 
  
1281
 
  if(mc.server != NULL)
1282
 
    avahi_server_free(mc.server);
1283
 
  
1284
 
  if(mc.simple_poll != NULL)
1285
 
    avahi_simple_poll_free(mc.simple_poll);
1286
 
  
1287
 
  if(gnutls_initialized){
1288
 
    gnutls_certificate_free_credentials(mc.cred);
1289
 
    gnutls_global_deinit();
1290
 
    gnutls_dh_params_deinit(mc.dh_params);
1291
 
  }
1292
 
  
1293
 
  if(gpgme_initialized){
1294
 
    gpgme_release(mc.ctx);
1295
 
  }
1296
 
  
1297
 
  /* Removes the temp directory used by GPGME */
1298
 
  if(tempdir_created){
1299
 
    DIR *d;
1300
 
    struct dirent *direntry;
1301
 
    d = opendir(tempdir);
1302
 
    if(d == NULL){
1303
 
      if(errno != ENOENT){
 
1081
    
 
1082
    if (debug){
 
1083
      fprintf(stderr, "%s exiting\n", argv[0]);
 
1084
    }
 
1085
    
 
1086
    /* Cleanup things */
 
1087
    if (sb != NULL)
 
1088
        avahi_s_service_browser_free(sb);
 
1089
    
 
1090
    if (mc.server != NULL)
 
1091
        avahi_server_free(mc.server);
 
1092
    
 
1093
    if (mc.simple_poll != NULL)
 
1094
        avahi_simple_poll_free(mc.simple_poll);
 
1095
    
 
1096
    if (gnutls_initalized){
 
1097
      gnutls_certificate_free_credentials(mc.cred);
 
1098
      gnutls_global_deinit ();
 
1099
      gnutls_dh_params_deinit(mc.dh_params);
 
1100
    }
 
1101
    
 
1102
    if(gpgme_initalized){
 
1103
      gpgme_release(mc.ctx);
 
1104
    }
 
1105
    
 
1106
    /* Removes the temp directory used by GPGME */
 
1107
    if(tempdir[0] != '\0'){
 
1108
      DIR *d;
 
1109
      struct dirent *direntry;
 
1110
      d = opendir(tempdir);
 
1111
      if(d == NULL){
1304
1112
        perror("opendir");
1305
 
      }
1306
 
    } else {
1307
 
      while(true){
1308
 
        direntry = readdir(d);
1309
 
        if(direntry == NULL){
1310
 
          break;
1311
 
        }
1312
 
        /* Skip "." and ".." */
1313
 
        if(direntry->d_name[0] == '.'
1314
 
           and (direntry->d_name[1] == '\0'
1315
 
                or (direntry->d_name[1] == '.'
1316
 
                    and direntry->d_name[2] == '\0'))){
1317
 
          continue;
1318
 
        }
1319
 
        char *fullname = NULL;
1320
 
        ret = asprintf(&fullname, "%s/%s", tempdir,
1321
 
                       direntry->d_name);
1322
 
        if(ret < 0){
1323
 
          perror("asprintf");
1324
 
          continue;
1325
 
        }
1326
 
        ret = remove(fullname);
1327
 
        if(ret == -1){
1328
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1329
 
                  strerror(errno));
1330
 
        }
1331
 
        free(fullname);
1332
 
      }
1333
 
      closedir(d);
1334
 
    }
1335
 
    ret = rmdir(tempdir);
1336
 
    if(ret == -1 and errno != ENOENT){
1337
 
      perror("rmdir");
1338
 
    }
1339
 
  }
1340
 
  
1341
 
  return exitcode;
 
1113
      } else {
 
1114
        while(true){
 
1115
          direntry = readdir(d);
 
1116
          if(direntry == NULL){
 
1117
            break;
 
1118
          }
 
1119
          if (direntry->d_type == DT_REG){
 
1120
            char *fullname = NULL;
 
1121
            ret = asprintf(&fullname, "%s/%s", tempdir,
 
1122
                           direntry->d_name);
 
1123
            if(ret < 0){
 
1124
              perror("asprintf");
 
1125
              continue;
 
1126
            }
 
1127
            ret = unlink(fullname);
 
1128
            if(ret == -1){
 
1129
              fprintf(stderr, "unlink(\"%s\"): %s",
 
1130
                      fullname, strerror(errno));
 
1131
            }
 
1132
            free(fullname);
 
1133
          }
 
1134
        }
 
1135
        closedir(d);
 
1136
      }
 
1137
      ret = rmdir(tempdir);
 
1138
      if(ret == -1){
 
1139
        perror("rmdir");
 
1140
      }
 
1141
    }
 
1142
          
 
1143
    return exitcode;
1342
1144
}