/mandos/trunk

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

« back to all changes in this revision

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

Added manual pages for:
      clients.conf
      mandos.conf
      mandos
      mandos-client
      password-prompt
      password-request

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 © 2007-2008 Teddy Hogeborn & Björn Påhlsson
14
13
 * 
15
14
 * This program is free software: you can redistribute it and/or
16
15
 * modify it under the terms of the GNU General Public License as
33
32
#define _LARGEFILE_SOURCE
34
33
#define _FILE_OFFSET_BITS 64
35
34
 
36
 
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
 
35
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY() */
37
36
 
38
 
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
39
 
                                   stdout, ferror(), sscanf(),
40
 
                                   remove() */
41
 
#include <stdint.h>             /* uint16_t, uint32_t */
42
 
#include <stddef.h>             /* NULL, size_t, ssize_t */
43
 
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
44
 
                                   srand() */
45
 
#include <stdbool.h>            /* bool, true */
46
 
#include <string.h>             /* memset(), strcmp(), strlen(),
47
 
                                   strerror(), asprintf(), strcpy() */
48
 
#include <sys/ioctl.h>          /* ioctl */
49
 
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
50
 
                                   sockaddr_in6, PF_INET6,
51
 
                                   SOCK_STREAM, INET6_ADDRSTRLEN,
52
 
                                   uid_t, gid_t, open(), opendir(),
53
 
                                   DIR */
54
 
#include <sys/stat.h>           /* open() */
55
 
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
56
 
                                   struct in6_addr, inet_pton(),
57
 
                                   connect() */
58
 
#include <fcntl.h>              /* open() */
59
 
#include <dirent.h>             /* opendir(), struct dirent, readdir()
60
 
                                 */
61
 
#include <inttypes.h>           /* PRIu16, intmax_t, SCNdMAX */
62
 
#include <assert.h>             /* assert() */
63
 
#include <errno.h>              /* perror(), errno */
64
 
#include <time.h>               /* nanosleep(), time() */
 
37
#include <stdio.h>
 
38
#include <assert.h>
 
39
#include <stdlib.h>
 
40
#include <time.h>
 
41
#include <net/if.h>             /* if_nametoindex */
 
42
#include <sys/ioctl.h>          /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
 
43
                                   SIOCSIFFLAGS */
65
44
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
66
 
                                   SIOCSIFFLAGS, if_indextoname(),
67
 
                                   if_nametoindex(), IF_NAMESIZE */
68
 
#include <netinet/in.h>
69
 
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
70
 
                                   getuid(), getgid(), setuid(),
71
 
                                   setgid() */
72
 
#include <arpa/inet.h>          /* inet_pton(), htons */
73
 
#include <iso646.h>             /* not, and, or */
74
 
#include <argp.h>               /* struct argp_option, error_t, struct
75
 
                                   argp_state, struct argp,
76
 
                                   argp_parse(), ARGP_KEY_ARG,
77
 
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
78
 
#include <sys/klog.h>           /* klogctl() */
 
45
                                   SIOCSIFFLAGS */
79
46
 
80
 
/* Avahi */
81
 
/* All Avahi types, constants and functions
82
 
 Avahi*, avahi_*,
83
 
 AVAHI_* */
84
47
#include <avahi-core/core.h>
85
48
#include <avahi-core/lookup.h>
86
49
#include <avahi-core/log.h>
88
51
#include <avahi-common/malloc.h>
89
52
#include <avahi-common/error.h>
90
53
 
91
 
/* GnuTLS */
92
 
#include <gnutls/gnutls.h>      /* All GnuTLS types, constants and
93
 
                                   functions:
94
 
                                   gnutls_*
95
 
                                   init_gnutls_session(),
96
 
                                   GNUTLS_* */
97
 
#include <gnutls/openpgp.h>
98
 
                          /* gnutls_certificate_set_openpgp_key_file(),
99
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
 
54
/* Mandos client part */
 
55
#include <sys/types.h>          /* socket(), inet_pton() */
 
56
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
 
57
                                   struct in6_addr, inet_pton() */
 
58
#include <gnutls/gnutls.h>      /* All GnuTLS stuff */
 
59
#include <gnutls/openpgp.h>     /* GnuTLS with openpgp stuff */
100
60
 
 
61
#include <unistd.h>             /* close() */
 
62
#include <netinet/in.h>
 
63
#include <stdbool.h>            /* true */
 
64
#include <string.h>             /* memset */
 
65
#include <arpa/inet.h>          /* inet_pton() */
 
66
#include <iso646.h>             /* not */
 
67
#include <net/if.h>             /* IF_NAMESIZE */
 
68
#include <argp.h>               /* struct argp_option,
 
69
                                   struct argp_state, struct argp,
 
70
                                   argp_parse() */
101
71
/* GPGME */
102
 
#include <gpgme.h>              /* All GPGME types, constants and
103
 
                                   functions:
104
 
                                   gpgme_*
105
 
                                   GPGME_PROTOCOL_OpenPGP,
106
 
                                   GPG_ERR_NO_* */
 
72
#include <errno.h>              /* perror() */
 
73
#include <gpgme.h>
107
74
 
108
75
#define BUFFER_SIZE 256
109
76
 
110
 
#define PATHDIR "/conf/conf.d/mandos"
111
 
#define SECKEY "seckey.txt"
112
 
#define PUBKEY "pubkey.txt"
113
 
 
114
77
bool debug = false;
 
78
static const char *keydir = "/conf/conf.d/mandos";
115
79
static const char mandos_protocol_version[] = "1";
116
 
const char *argp_program_version = "mandos-client " VERSION;
 
80
const char *argp_program_version = "mandosclient 0.9";
117
81
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
118
82
 
119
83
/* Used for passing in values through the Avahi callback functions */
124
88
  unsigned int dh_bits;
125
89
  gnutls_dh_params_t dh_params;
126
90
  const char *priority;
127
 
  gpgme_ctx_t ctx;
128
91
} mandos_context;
129
92
 
130
93
/*
134
97
 */
135
98
size_t adjustbuffer(char **buffer, size_t buffer_length,
136
99
                  size_t buffer_capacity){
137
 
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
 
100
  if (buffer_length + BUFFER_SIZE > buffer_capacity){
138
101
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
139
 
    if(buffer == NULL){
 
102
    if (buffer == NULL){
140
103
      return 0;
141
104
    }
142
105
    buffer_capacity += BUFFER_SIZE;
145
108
}
146
109
 
147
110
/* 
148
 
 * Initialize GPGME.
 
111
 * Decrypt OpenPGP data using keyrings in HOMEDIR.
 
112
 * Returns -1 on error
149
113
 */
150
 
static bool init_gpgme(mandos_context *mc, const char *seckey,
151
 
                       const char *pubkey, const char *tempdir){
152
 
  int ret;
 
114
static ssize_t pgp_packet_decrypt (const char *cryptotext,
 
115
                                   size_t crypto_size,
 
116
                                   char **plaintext,
 
117
                                   const char *homedir){
 
118
  gpgme_data_t dh_crypto, dh_plain;
 
119
  gpgme_ctx_t ctx;
153
120
  gpgme_error_t rc;
 
121
  ssize_t ret;
 
122
  size_t plaintext_capacity = 0;
 
123
  ssize_t plaintext_length = 0;
154
124
  gpgme_engine_info_t engine_info;
155
125
  
156
 
  
157
 
  /*
158
 
   * Helper function to insert pub and seckey to the engine keyring.
159
 
   */
160
 
  bool import_key(const char *filename){
161
 
    int fd;
162
 
    gpgme_data_t pgp_data;
163
 
    
164
 
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
165
 
    if(fd == -1){
166
 
      perror("open");
167
 
      return false;
168
 
    }
169
 
    
170
 
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
171
 
    if(rc != GPG_ERR_NO_ERROR){
172
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
173
 
              gpgme_strsource(rc), gpgme_strerror(rc));
174
 
      return false;
175
 
    }
176
 
    
177
 
    rc = gpgme_op_import(mc->ctx, pgp_data);
178
 
    if(rc != GPG_ERR_NO_ERROR){
179
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
180
 
              gpgme_strsource(rc), gpgme_strerror(rc));
181
 
      return false;
182
 
    }
183
 
    
184
 
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
185
 
    if(ret == -1){
186
 
      perror("close");
187
 
    }
188
 
    gpgme_data_release(pgp_data);
189
 
    return true;
190
 
  }
191
 
  
192
 
  if(debug){
193
 
    fprintf(stderr, "Initialize gpgme\n");
 
126
  if (debug){
 
127
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
194
128
  }
195
129
  
196
130
  /* Init GPGME */
197
131
  gpgme_check_version(NULL);
198
132
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
199
 
  if(rc != GPG_ERR_NO_ERROR){
 
133
  if (rc != GPG_ERR_NO_ERROR){
200
134
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
201
135
            gpgme_strsource(rc), gpgme_strerror(rc));
202
 
    return false;
 
136
    return -1;
203
137
  }
204
138
  
205
 
    /* Set GPGME home directory for the OpenPGP engine only */
206
 
  rc = gpgme_get_engine_info(&engine_info);
207
 
  if(rc != GPG_ERR_NO_ERROR){
 
139
  /* Set GPGME home directory for the OpenPGP engine only */
 
140
  rc = gpgme_get_engine_info (&engine_info);
 
141
  if (rc != GPG_ERR_NO_ERROR){
208
142
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
209
143
            gpgme_strsource(rc), gpgme_strerror(rc));
210
 
    return false;
 
144
    return -1;
211
145
  }
212
146
  while(engine_info != NULL){
213
147
    if(engine_info->protocol == GPGME_PROTOCOL_OpenPGP){
214
148
      gpgme_set_engine_info(GPGME_PROTOCOL_OpenPGP,
215
 
                            engine_info->file_name, tempdir);
 
149
                            engine_info->file_name, homedir);
216
150
      break;
217
151
    }
218
152
    engine_info = engine_info->next;
219
153
  }
220
154
  if(engine_info == NULL){
221
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
222
 
    return false;
223
 
  }
224
 
  
225
 
  /* Create new GPGME "context" */
226
 
  rc = gpgme_new(&(mc->ctx));
227
 
  if(rc != GPG_ERR_NO_ERROR){
228
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
229
 
            gpgme_strsource(rc), gpgme_strerror(rc));
230
 
    return false;
231
 
  }
232
 
  
233
 
  if(not import_key(pubkey) or not import_key(seckey)){
234
 
    return false;
235
 
  }
236
 
  
237
 
  return true; 
238
 
}
239
 
 
240
 
/* 
241
 
 * Decrypt OpenPGP data.
242
 
 * Returns -1 on error
243
 
 */
244
 
static ssize_t pgp_packet_decrypt(const mandos_context *mc,
245
 
                                  const char *cryptotext,
246
 
                                  size_t crypto_size,
247
 
                                  char **plaintext){
248
 
  gpgme_data_t dh_crypto, dh_plain;
249
 
  gpgme_error_t rc;
250
 
  ssize_t ret;
251
 
  size_t plaintext_capacity = 0;
252
 
  ssize_t plaintext_length = 0;
253
 
  
254
 
  if(debug){
255
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
155
    fprintf(stderr, "Could not set GPGME home dir to %s\n", homedir);
 
156
    return -1;
256
157
  }
257
158
  
258
159
  /* Create new GPGME data buffer from memory cryptotext */
259
160
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
260
161
                               0);
261
 
  if(rc != GPG_ERR_NO_ERROR){
 
162
  if (rc != GPG_ERR_NO_ERROR){
262
163
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
263
164
            gpgme_strsource(rc), gpgme_strerror(rc));
264
165
    return -1;
266
167
  
267
168
  /* Create new empty GPGME data buffer for the plaintext */
268
169
  rc = gpgme_data_new(&dh_plain);
269
 
  if(rc != GPG_ERR_NO_ERROR){
 
170
  if (rc != GPG_ERR_NO_ERROR){
270
171
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
271
172
            gpgme_strsource(rc), gpgme_strerror(rc));
272
173
    gpgme_data_release(dh_crypto);
273
174
    return -1;
274
175
  }
275
176
  
 
177
  /* Create new GPGME "context" */
 
178
  rc = gpgme_new(&ctx);
 
179
  if (rc != GPG_ERR_NO_ERROR){
 
180
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
181
            gpgme_strsource(rc), gpgme_strerror(rc));
 
182
    plaintext_length = -1;
 
183
    goto decrypt_end;
 
184
  }
 
185
  
276
186
  /* Decrypt data from the cryptotext data buffer to the plaintext
277
187
     data buffer */
278
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
279
 
  if(rc != GPG_ERR_NO_ERROR){
 
188
  rc = gpgme_op_decrypt(ctx, dh_crypto, dh_plain);
 
189
  if (rc != GPG_ERR_NO_ERROR){
280
190
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
281
191
            gpgme_strsource(rc), gpgme_strerror(rc));
282
192
    plaintext_length = -1;
283
 
    if(debug){
284
 
      gpgme_decrypt_result_t result;
285
 
      result = gpgme_op_decrypt_result(mc->ctx);
286
 
      if(result == NULL){
287
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
288
 
      } else {
289
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
290
 
                result->unsupported_algorithm);
291
 
        fprintf(stderr, "Wrong key usage: %u\n",
292
 
                result->wrong_key_usage);
293
 
        if(result->file_name != NULL){
294
 
          fprintf(stderr, "File name: %s\n", result->file_name);
295
 
        }
296
 
        gpgme_recipient_t recipient;
297
 
        recipient = result->recipients;
298
 
        if(recipient){
299
 
          while(recipient != NULL){
300
 
            fprintf(stderr, "Public key algorithm: %s\n",
301
 
                    gpgme_pubkey_algo_name(recipient->pubkey_algo));
302
 
            fprintf(stderr, "Key ID: %s\n", recipient->keyid);
303
 
            fprintf(stderr, "Secret key available: %s\n",
304
 
                    recipient->status == GPG_ERR_NO_SECKEY
305
 
                    ? "No" : "Yes");
306
 
            recipient = recipient->next;
307
 
          }
308
 
        }
309
 
      }
310
 
    }
311
193
    goto decrypt_end;
312
194
  }
313
195
  
315
197
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
316
198
  }
317
199
  
 
200
  if (debug){
 
201
    gpgme_decrypt_result_t result;
 
202
    result = gpgme_op_decrypt_result(ctx);
 
203
    if (result == NULL){
 
204
      fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
205
    } else {
 
206
      fprintf(stderr, "Unsupported algorithm: %s\n",
 
207
              result->unsupported_algorithm);
 
208
      fprintf(stderr, "Wrong key usage: %d\n",
 
209
              result->wrong_key_usage);
 
210
      if(result->file_name != NULL){
 
211
        fprintf(stderr, "File name: %s\n", result->file_name);
 
212
      }
 
213
      gpgme_recipient_t recipient;
 
214
      recipient = result->recipients;
 
215
      if(recipient){
 
216
        while(recipient != NULL){
 
217
          fprintf(stderr, "Public key algorithm: %s\n",
 
218
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
219
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
220
          fprintf(stderr, "Secret key available: %s\n",
 
221
                  recipient->status == GPG_ERR_NO_SECKEY
 
222
                  ? "No" : "Yes");
 
223
          recipient = recipient->next;
 
224
        }
 
225
      }
 
226
    }
 
227
  }
 
228
  
318
229
  /* Seek back to the beginning of the GPGME plaintext data buffer */
319
 
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
320
 
    perror("gpgme_data_seek");
 
230
  if (gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET) == -1){
 
231
    perror("pgpme_data_seek");
321
232
    plaintext_length = -1;
322
233
    goto decrypt_end;
323
234
  }
327
238
    plaintext_capacity = adjustbuffer(plaintext,
328
239
                                      (size_t)plaintext_length,
329
240
                                      plaintext_capacity);
330
 
    if(plaintext_capacity == 0){
 
241
    if (plaintext_capacity == 0){
331
242
        perror("adjustbuffer");
332
243
        plaintext_length = -1;
333
244
        goto decrypt_end;
336
247
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
337
248
                          BUFFER_SIZE);
338
249
    /* Print the data, if any */
339
 
    if(ret == 0){
 
250
    if (ret == 0){
340
251
      /* EOF */
341
252
      break;
342
253
    }
347
258
    }
348
259
    plaintext_length += ret;
349
260
  }
350
 
  
 
261
 
351
262
  if(debug){
352
263
    fprintf(stderr, "Decrypted password is: ");
353
264
    for(ssize_t i = 0; i < plaintext_length; i++){
366
277
  return plaintext_length;
367
278
}
368
279
 
369
 
static const char * safer_gnutls_strerror(int value) {
370
 
  const char *ret = gnutls_strerror(value); /* Spurious warning from
371
 
                                               -Wunreachable-code */
372
 
  if(ret == NULL)
 
280
static const char * safer_gnutls_strerror (int value) {
 
281
  const char *ret = gnutls_strerror (value);
 
282
  if (ret == NULL)
373
283
    ret = "(unknown)";
374
284
  return ret;
375
285
}
381
291
}
382
292
 
383
293
static int init_gnutls_global(mandos_context *mc,
384
 
                              const char *pubkeyfilename,
385
 
                              const char *seckeyfilename){
 
294
                              const char *pubkeyfile,
 
295
                              const char *seckeyfile){
386
296
  int ret;
387
297
  
388
298
  if(debug){
389
299
    fprintf(stderr, "Initializing GnuTLS\n");
390
300
  }
391
 
  
392
 
  ret = gnutls_global_init();
393
 
  if(ret != GNUTLS_E_SUCCESS) {
394
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
395
 
            safer_gnutls_strerror(ret));
 
301
 
 
302
  if ((ret = gnutls_global_init ())
 
303
      != GNUTLS_E_SUCCESS) {
 
304
    fprintf (stderr, "GnuTLS global_init: %s\n",
 
305
             safer_gnutls_strerror(ret));
396
306
    return -1;
397
307
  }
398
308
  
399
 
  if(debug){
 
309
  if (debug){
400
310
    /* "Use a log level over 10 to enable all debugging options."
401
311
     * - GnuTLS manual
402
312
     */
405
315
  }
406
316
  
407
317
  /* OpenPGP credentials */
408
 
  gnutls_certificate_allocate_credentials(&mc->cred);
409
 
  if(ret != GNUTLS_E_SUCCESS){
410
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
411
 
                                                  * from
412
 
                                                  * -Wunreachable-code
413
 
                                                  */
414
 
            safer_gnutls_strerror(ret));
415
 
    gnutls_global_deinit();
 
318
  if ((ret = gnutls_certificate_allocate_credentials (&mc->cred))
 
319
      != GNUTLS_E_SUCCESS) {
 
320
    fprintf (stderr, "GnuTLS memory error: %s\n",
 
321
             safer_gnutls_strerror(ret));
 
322
    gnutls_global_deinit ();
416
323
    return -1;
417
324
  }
418
325
  
419
326
  if(debug){
420
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
421
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
422
 
            seckeyfilename);
 
327
    fprintf(stderr, "Attempting to use OpenPGP certificate %s"
 
328
            " and keyfile %s as GnuTLS credentials\n", pubkeyfile,
 
329
            seckeyfile);
423
330
  }
424
331
  
425
332
  ret = gnutls_certificate_set_openpgp_key_file
426
 
    (mc->cred, pubkeyfilename, seckeyfilename,
427
 
     GNUTLS_OPENPGP_FMT_BASE64);
428
 
  if(ret != GNUTLS_E_SUCCESS) {
 
333
    (mc->cred, pubkeyfile, seckeyfile, GNUTLS_OPENPGP_FMT_BASE64);
 
334
  if (ret != GNUTLS_E_SUCCESS) {
429
335
    fprintf(stderr,
430
336
            "Error[%d] while reading the OpenPGP key pair ('%s',"
431
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
432
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
 
337
            " '%s')\n", ret, pubkeyfile, seckeyfile);
 
338
    fprintf(stdout, "The GnuTLS error is: %s\n",
433
339
            safer_gnutls_strerror(ret));
434
340
    goto globalfail;
435
341
  }
436
342
  
437
343
  /* GnuTLS server initialization */
438
344
  ret = gnutls_dh_params_init(&mc->dh_params);
439
 
  if(ret != GNUTLS_E_SUCCESS) {
440
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
441
 
            " %s\n", safer_gnutls_strerror(ret));
 
345
  if (ret != GNUTLS_E_SUCCESS) {
 
346
    fprintf (stderr, "Error in GnuTLS DH parameter initialization:"
 
347
             " %s\n", safer_gnutls_strerror(ret));
442
348
    goto globalfail;
443
349
  }
444
350
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
445
 
  if(ret != GNUTLS_E_SUCCESS) {
446
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
447
 
            safer_gnutls_strerror(ret));
 
351
  if (ret != GNUTLS_E_SUCCESS) {
 
352
    fprintf (stderr, "Error in GnuTLS prime generation: %s\n",
 
353
             safer_gnutls_strerror(ret));
448
354
    goto globalfail;
449
355
  }
450
356
  
451
357
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
452
 
  
 
358
 
453
359
  return 0;
454
 
  
 
360
 
455
361
 globalfail:
456
 
  
457
 
  gnutls_certificate_free_credentials(mc->cred);
458
 
  gnutls_global_deinit();
459
 
  gnutls_dh_params_deinit(mc->dh_params);
 
362
 
 
363
  gnutls_certificate_free_credentials (mc->cred);
 
364
  gnutls_global_deinit ();
460
365
  return -1;
 
366
 
461
367
}
462
368
 
463
369
static int init_gnutls_session(mandos_context *mc,
465
371
  int ret;
466
372
  /* GnuTLS session creation */
467
373
  ret = gnutls_init(session, GNUTLS_SERVER);
468
 
  if(ret != GNUTLS_E_SUCCESS){
 
374
  if (ret != GNUTLS_E_SUCCESS){
469
375
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
470
376
            safer_gnutls_strerror(ret));
471
377
  }
473
379
  {
474
380
    const char *err;
475
381
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
476
 
    if(ret != GNUTLS_E_SUCCESS) {
 
382
    if (ret != GNUTLS_E_SUCCESS) {
477
383
      fprintf(stderr, "Syntax error at: %s\n", err);
478
384
      fprintf(stderr, "GnuTLS error: %s\n",
479
385
              safer_gnutls_strerror(ret));
480
 
      gnutls_deinit(*session);
 
386
      gnutls_deinit (*session);
481
387
      return -1;
482
388
    }
483
389
  }
484
390
  
485
391
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
486
392
                               mc->cred);
487
 
  if(ret != GNUTLS_E_SUCCESS) {
 
393
  if (ret != GNUTLS_E_SUCCESS) {
488
394
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
489
395
            safer_gnutls_strerror(ret));
490
 
    gnutls_deinit(*session);
 
396
    gnutls_deinit (*session);
491
397
    return -1;
492
398
  }
493
399
  
494
400
  /* ignore client certificate if any. */
495
 
  gnutls_certificate_server_set_request(*session,
496
 
                                        GNUTLS_CERT_IGNORE);
 
401
  gnutls_certificate_server_set_request (*session,
 
402
                                         GNUTLS_CERT_IGNORE);
497
403
  
498
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
404
  gnutls_dh_set_prime_bits (*session, mc->dh_bits);
499
405
  
500
406
  return 0;
501
407
}
509
415
                                      AvahiIfIndex if_index,
510
416
                                      mandos_context *mc){
511
417
  int ret, tcp_sd;
512
 
  ssize_t sret;
513
418
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
514
419
  char *buffer = NULL;
515
420
  char *decrypted_buffer;
521
426
  char interface[IF_NAMESIZE];
522
427
  gnutls_session_t session;
523
428
  
524
 
  ret = init_gnutls_session(mc, &session);
525
 
  if(ret != 0){
 
429
  ret = init_gnutls_session (mc, &session);
 
430
  if (ret != 0){
526
431
    return -1;
527
432
  }
528
433
  
529
434
  if(debug){
530
 
    fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
531
 
            "\n", ip, port);
 
435
    fprintf(stderr, "Setting up a tcp connection to %s, port %d\n",
 
436
            ip, port);
532
437
  }
533
438
  
534
439
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
536
441
    perror("socket");
537
442
    return -1;
538
443
  }
539
 
  
 
444
 
540
445
  if(debug){
541
446
    if(if_indextoname((unsigned int)if_index, interface) == NULL){
542
447
      perror("if_indextoname");
545
450
    fprintf(stderr, "Binding to interface %s\n", interface);
546
451
  }
547
452
  
548
 
  memset(&to, 0, sizeof(to));
 
453
  memset(&to,0,sizeof(to));     /* Spurious warning */
549
454
  to.in6.sin6_family = AF_INET6;
550
455
  /* It would be nice to have a way to detect if we were passed an
551
456
     IPv4 address here.   Now we assume an IPv6 address. */
552
457
  ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
553
 
  if(ret < 0 ){
 
458
  if (ret < 0 ){
554
459
    perror("inet_pton");
555
460
    return -1;
556
461
  }
558
463
    fprintf(stderr, "Bad address: %s\n", ip);
559
464
    return -1;
560
465
  }
561
 
  to.in6.sin6_port = htons(port); /* Spurious warnings from
562
 
                                     -Wconversion and
563
 
                                     -Wunreachable-code */
 
466
  to.in6.sin6_port = htons(port);       /* Spurious warning */
564
467
  
565
468
  to.in6.sin6_scope_id = (uint32_t)if_index;
566
469
  
567
470
  if(debug){
568
 
    fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
569
 
            port);
 
471
    fprintf(stderr, "Connection to: %s, port %d\n", ip, port);
570
472
    char addrstr[INET6_ADDRSTRLEN] = "";
571
473
    if(inet_ntop(to.in6.sin6_family, &(to.in6.sin6_addr), addrstr,
572
474
                 sizeof(addrstr)) == NULL){
579
481
  }
580
482
  
581
483
  ret = connect(tcp_sd, &to.in, sizeof(to));
582
 
  if(ret < 0){
 
484
  if (ret < 0){
583
485
    perror("connect");
584
486
    return -1;
585
487
  }
586
 
  
 
488
 
587
489
  const char *out = mandos_protocol_version;
588
490
  written = 0;
589
 
  while(true){
 
491
  while (true){
590
492
    size_t out_size = strlen(out);
591
 
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
 
493
    ret = TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
592
494
                                   out_size - written));
593
 
    if(ret == -1){
 
495
    if (ret == -1){
594
496
      perror("write");
595
497
      retval = -1;
596
498
      goto mandos_end;
599
501
    if(written < out_size){
600
502
      continue;
601
503
    } else {
602
 
      if(out == mandos_protocol_version){
 
504
      if (out == mandos_protocol_version){
603
505
        written = 0;
604
506
        out = "\r\n";
605
507
      } else {
607
509
      }
608
510
    }
609
511
  }
610
 
  
 
512
 
611
513
  if(debug){
612
514
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
613
515
  }
614
516
  
615
 
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
616
 
  
617
 
  do{
618
 
    ret = gnutls_handshake(session);
619
 
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
620
 
  
621
 
  if(ret != GNUTLS_E_SUCCESS){
 
517
  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) tcp_sd);
 
518
  
 
519
  ret = gnutls_handshake (session);
 
520
  
 
521
  if (ret != GNUTLS_E_SUCCESS){
622
522
    if(debug){
623
523
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
624
 
      gnutls_perror(ret);
 
524
      gnutls_perror (ret);
625
525
    }
626
526
    retval = -1;
627
527
    goto mandos_end;
633
533
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
634
534
            ip);
635
535
  }
636
 
  
 
536
 
637
537
  while(true){
638
538
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
639
539
                                   buffer_capacity);
640
 
    if(buffer_capacity == 0){
 
540
    if (buffer_capacity == 0){
641
541
      perror("adjustbuffer");
642
542
      retval = -1;
643
543
      goto mandos_end;
644
544
    }
645
545
    
646
 
    sret = gnutls_record_recv(session, buffer+buffer_length,
647
 
                              BUFFER_SIZE);
648
 
    if(sret == 0){
 
546
    ret = gnutls_record_recv(session, buffer+buffer_length,
 
547
                             BUFFER_SIZE);
 
548
    if (ret == 0){
649
549
      break;
650
550
    }
651
 
    if(sret < 0){
652
 
      switch(sret){
 
551
    if (ret < 0){
 
552
      switch(ret){
653
553
      case GNUTLS_E_INTERRUPTED:
654
554
      case GNUTLS_E_AGAIN:
655
555
        break;
656
556
      case GNUTLS_E_REHANDSHAKE:
657
 
        do{
658
 
          ret = gnutls_handshake(session);
659
 
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
660
 
        if(ret < 0){
 
557
        ret = gnutls_handshake (session);
 
558
        if (ret < 0){
661
559
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
662
 
          gnutls_perror(ret);
 
560
          gnutls_perror (ret);
663
561
          retval = -1;
664
562
          goto mandos_end;
665
563
        }
668
566
        fprintf(stderr, "Unknown error while reading data from"
669
567
                " encrypted session with Mandos server\n");
670
568
        retval = -1;
671
 
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
569
        gnutls_bye (session, GNUTLS_SHUT_RDWR);
672
570
        goto mandos_end;
673
571
      }
674
572
    } else {
675
 
      buffer_length += (size_t) sret;
 
573
      buffer_length += (size_t) ret;
676
574
    }
677
575
  }
678
576
  
680
578
    fprintf(stderr, "Closing TLS session\n");
681
579
  }
682
580
  
683
 
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
581
  gnutls_bye (session, GNUTLS_SHUT_RDWR);
684
582
  
685
 
  if(buffer_length > 0){
686
 
    decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
 
583
  if (buffer_length > 0){
 
584
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
687
585
                                               buffer_length,
688
 
                                               &decrypted_buffer);
689
 
    if(decrypted_buffer_size >= 0){
 
586
                                               &decrypted_buffer,
 
587
                                               keydir);
 
588
    if (decrypted_buffer_size >= 0){
690
589
      written = 0;
691
590
      while(written < (size_t) decrypted_buffer_size){
692
 
        ret = (int)fwrite(decrypted_buffer + written, 1,
693
 
                          (size_t)decrypted_buffer_size - written,
694
 
                          stdout);
 
591
        ret = (int)fwrite (decrypted_buffer + written, 1,
 
592
                           (size_t)decrypted_buffer_size - written,
 
593
                           stdout);
695
594
        if(ret == 0 and ferror(stdout)){
696
595
          if(debug){
697
596
            fprintf(stderr, "Error writing encrypted data: %s\n",
706
605
    } else {
707
606
      retval = -1;
708
607
    }
709
 
  } else {
710
 
    retval = -1;
711
608
  }
712
609
  
713
610
  /* Shutdown procedure */
714
611
  
715
612
 mandos_end:
716
613
  free(buffer);
717
 
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
718
 
  if(ret == -1){
719
 
    perror("close");
720
 
  }
721
 
  gnutls_deinit(session);
 
614
  close(tcp_sd);
 
615
  gnutls_deinit (session);
722
616
  return retval;
723
617
}
724
618
 
737
631
                             flags,
738
632
                             void* userdata) {
739
633
  mandos_context *mc = userdata;
740
 
  assert(r);
 
634
  assert(r);                    /* Spurious warning */
741
635
  
742
636
  /* Called whenever a service has been resolved successfully or
743
637
     timed out */
744
638
  
745
 
  switch(event) {
 
639
  switch (event) {
746
640
  default:
747
641
  case AVAHI_RESOLVER_FAILURE:
748
642
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
755
649
      char ip[AVAHI_ADDRESS_STR_MAX];
756
650
      avahi_address_snprint(ip, sizeof(ip), address);
757
651
      if(debug){
758
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
759
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
760
 
                ip, (intmax_t)interface, port);
 
652
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %d) on"
 
653
                " port %d\n", name, host_name, ip, interface, port);
761
654
      }
762
655
      int ret = start_mandos_communication(ip, port, interface, mc);
763
 
      if(ret == 0){
764
 
        avahi_simple_poll_quit(mc->simple_poll);
 
656
      if (ret == 0){
 
657
        exit(EXIT_SUCCESS);
765
658
      }
766
659
    }
767
660
  }
779
672
                             flags,
780
673
                             void* userdata) {
781
674
  mandos_context *mc = userdata;
782
 
  assert(b);
 
675
  assert(b);                    /* Spurious warning */
783
676
  
784
677
  /* Called whenever a new services becomes available on the LAN or
785
678
     is removed from the LAN */
786
679
  
787
 
  switch(event) {
 
680
  switch (event) {
788
681
  default:
789
682
  case AVAHI_BROWSER_FAILURE:
790
683
    
799
692
       the callback function is called the Avahi server will free the
800
693
       resolver for us. */
801
694
    
802
 
    if(!(avahi_s_service_resolver_new(mc->server, interface,
 
695
    if (!(avahi_s_service_resolver_new(mc->server, interface,
803
696
                                       protocol, name, type, domain,
804
697
                                       AVAHI_PROTO_INET6, 0,
805
698
                                       resolve_callback, mc)))
819
712
  }
820
713
}
821
714
 
 
715
/* Combines file name and path and returns the malloced new
 
716
   string. some sane checks could/should be added */
 
717
static const char *combinepath(const char *first, const char *second){
 
718
  size_t f_len = strlen(first);
 
719
  size_t s_len = strlen(second);
 
720
  char *tmp = malloc(f_len + s_len + 2);
 
721
  if (tmp == NULL){
 
722
    return NULL;
 
723
  }
 
724
  if(f_len > 0){
 
725
    memcpy(tmp, first, f_len);  /* Spurious warning */
 
726
  }
 
727
  tmp[f_len] = '/';
 
728
  if(s_len > 0){
 
729
    memcpy(tmp + f_len + 1, second, s_len); /* Spurious warning */
 
730
  }
 
731
  tmp[f_len + 1 + s_len] = '\0';
 
732
  return tmp;
 
733
}
 
734
 
 
735
 
822
736
int main(int argc, char *argv[]){
823
737
    AvahiSServiceBrowser *sb = NULL;
824
738
    int error;
825
739
    int ret;
826
 
    intmax_t tmpmax;
827
 
    int numchars;
828
740
    int exitcode = EXIT_SUCCESS;
829
741
    const char *interface = "eth0";
830
742
    struct ifreq network;
832
744
    uid_t uid;
833
745
    gid_t gid;
834
746
    char *connect_to = NULL;
835
 
    char tempdir[] = "/tmp/mandosXXXXXX";
836
 
    bool tempdir_created = false;
837
747
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
838
 
    const char *seckey = PATHDIR "/" SECKEY;
839
 
    const char *pubkey = PATHDIR "/" PUBKEY;
840
 
    
 
748
    const char *pubkeyfile = "pubkey.txt";
 
749
    const char *seckeyfile = "seckey.txt";
841
750
    mandos_context mc = { .simple_poll = NULL, .server = NULL,
842
 
                          .dh_bits = 1024, .priority = "SECURE256"
843
 
                          ":!CTYPE-X.509:+CTYPE-OPENPGP" };
844
 
    bool gnutls_initialized = false;
845
 
    bool gpgme_initialized = false;
846
 
    double delay = 2.5;
 
751
                          .dh_bits = 1024, .priority = "SECURE256"};
 
752
    bool gnutls_initalized = false;
847
753
    
848
754
    {
849
755
      struct argp_option options[] = {
850
756
        { .name = "debug", .key = 128,
851
757
          .doc = "Debug mode", .group = 3 },
852
758
        { .name = "connect", .key = 'c',
853
 
          .arg = "ADDRESS:PORT",
854
 
          .doc = "Connect directly to a specific Mandos server",
 
759
          .arg = "IP",
 
760
          .doc = "Connect directly to a sepcified mandos server",
855
761
          .group = 1 },
856
762
        { .name = "interface", .key = 'i',
857
 
          .arg = "NAME",
858
 
          .doc = "Interface that will be used to search for Mandos"
859
 
          " servers",
 
763
          .arg = "INTERFACE",
 
764
          .doc = "Interface that Avahi will conntect through",
 
765
          .group = 1 },
 
766
        { .name = "keydir", .key = 'd',
 
767
          .arg = "KEYDIR",
 
768
          .doc = "Directory where the openpgp keyring is",
860
769
          .group = 1 },
861
770
        { .name = "seckey", .key = 's',
862
 
          .arg = "FILE",
863
 
          .doc = "OpenPGP secret key file base name",
 
771
          .arg = "SECKEY",
 
772
          .doc = "Secret openpgp key for gnutls authentication",
864
773
          .group = 1 },
865
774
        { .name = "pubkey", .key = 'p',
866
 
          .arg = "FILE",
867
 
          .doc = "OpenPGP public key file base name",
 
775
          .arg = "PUBKEY",
 
776
          .doc = "Public openpgp key for gnutls authentication",
868
777
          .group = 2 },
869
778
        { .name = "dh-bits", .key = 129,
870
779
          .arg = "BITS",
871
 
          .doc = "Bit length of the prime number used in the"
872
 
          " Diffie-Hellman key exchange",
 
780
          .doc = "dh-bits to use in gnutls communication",
873
781
          .group = 2 },
874
782
        { .name = "priority", .key = 130,
875
 
          .arg = "STRING",
876
 
          .doc = "GnuTLS priority string for the TLS handshake",
877
 
          .group = 1 },
878
 
        { .name = "delay", .key = 131,
879
 
          .arg = "SECONDS",
880
 
          .doc = "Maximum delay to wait for interface startup",
881
 
          .group = 2 },
 
783
          .arg = "PRIORITY",
 
784
          .doc = "GNUTLS priority", .group = 1 },
882
785
        { .name = NULL }
883
786
      };
 
787
 
884
788
      
885
 
      error_t parse_opt(int key, char *arg,
886
 
                        struct argp_state *state) {
887
 
        switch(key) {
888
 
        case 128:               /* --debug */
 
789
      error_t parse_opt (int key, char *arg,
 
790
                         struct argp_state *state) {
 
791
        /* Get the INPUT argument from `argp_parse', which we know is
 
792
           a pointer to our plugin list pointer. */
 
793
        switch (key) {
 
794
        case 128:
889
795
          debug = true;
890
796
          break;
891
 
        case 'c':               /* --connect */
 
797
        case 'c':
892
798
          connect_to = arg;
893
799
          break;
894
 
        case 'i':               /* --interface */
 
800
        case 'i':
895
801
          interface = arg;
896
802
          break;
897
 
        case 's':               /* --seckey */
898
 
          seckey = arg;
899
 
          break;
900
 
        case 'p':               /* --pubkey */
901
 
          pubkey = arg;
902
 
          break;
903
 
        case 129:               /* --dh-bits */
904
 
          ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
905
 
          if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
906
 
             or arg[numchars] != '\0'){
907
 
            fprintf(stderr, "Bad number of DH bits\n");
 
803
        case 'd':
 
804
          keydir = arg;
 
805
          break;
 
806
        case 's':
 
807
          seckeyfile = arg;
 
808
          break;
 
809
        case 'p':
 
810
          pubkeyfile = arg;
 
811
          break;
 
812
        case 129:
 
813
          errno = 0;
 
814
          mc.dh_bits = (unsigned int) strtol(arg, NULL, 10);
 
815
          if (errno){
 
816
            perror("strtol");
908
817
            exit(EXIT_FAILURE);
909
818
          }
910
 
          mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
911
819
          break;
912
 
        case 130:               /* --priority */
 
820
        case 130:
913
821
          mc.priority = arg;
914
822
          break;
915
 
        case 131:               /* --delay */
916
 
          ret = sscanf(arg, "%lf%n", &delay, &numchars);
917
 
          if(ret < 1 or arg[numchars] != '\0'){
918
 
            fprintf(stderr, "Bad delay\n");
919
 
            exit(EXIT_FAILURE);
920
 
          }
921
 
          break;
922
823
        case ARGP_KEY_ARG:
923
 
          argp_usage(state);
924
 
        case ARGP_KEY_END:
 
824
          argp_usage (state);
925
825
          break;
 
826
          case ARGP_KEY_END:
 
827
            break;
926
828
        default:
927
829
          return ARGP_ERR_UNKNOWN;
928
830
        }
929
831
        return 0;
930
832
      }
931
 
      
 
833
 
932
834
      struct argp argp = { .options = options, .parser = parse_opt,
933
835
                           .args_doc = "",
934
836
                           .doc = "Mandos client -- Get and decrypt"
935
 
                           " passwords from a Mandos server" };
936
 
      ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
937
 
      if(ret == ARGP_ERR_UNKNOWN){
938
 
        fprintf(stderr, "Unknown error while parsing arguments\n");
939
 
        exitcode = EXIT_FAILURE;
940
 
        goto end;
941
 
      }
 
837
                           " passwords from mandos server" };
 
838
      argp_parse (&argp, argc, argv, 0, 0, NULL);
942
839
    }
943
 
    
944
 
    /* If the interface is down, bring it up */
945
 
    {
946
 
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
947
 
         messages to mess up the prompt */
948
 
      ret = klogctl(8, NULL, 5);
949
 
      if(ret == -1){
950
 
        perror("klogctl");
951
 
      }
952
840
      
953
 
      sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
954
 
      if(sd < 0) {
955
 
        perror("socket");
956
 
        exitcode = EXIT_FAILURE;
957
 
        ret = klogctl(7, NULL, 0);
958
 
        if(ret == -1){
959
 
          perror("klogctl");
960
 
        }
961
 
        goto end;
962
 
      }
963
 
      strcpy(network.ifr_name, interface);
964
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
965
 
      if(ret == -1){
966
 
        perror("ioctl SIOCGIFFLAGS");
967
 
        ret = klogctl(7, NULL, 0);
968
 
        if(ret == -1){
969
 
          perror("klogctl");
970
 
        }
971
 
        exitcode = EXIT_FAILURE;
972
 
        goto end;
973
 
      }
974
 
      if((network.ifr_flags & IFF_UP) == 0){
975
 
        network.ifr_flags |= IFF_UP;
976
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
977
 
        if(ret == -1){
978
 
          perror("ioctl SIOCSIFFLAGS");
979
 
          exitcode = EXIT_FAILURE;
980
 
          ret = klogctl(7, NULL, 0);
981
 
          if(ret == -1){
982
 
            perror("klogctl");
983
 
          }
984
 
          goto end;
985
 
        }
986
 
      }
987
 
      /* sleep checking until interface is running */
988
 
      for(int i=0; i < delay * 4; i++){
989
 
        ret = ioctl(sd, SIOCGIFFLAGS, &network);
990
 
        if(ret == -1){
991
 
          perror("ioctl SIOCGIFFLAGS");
992
 
        } else if(network.ifr_flags & IFF_RUNNING){
993
 
          break;
994
 
        }
995
 
        struct timespec sleeptime = { .tv_nsec = 250000000 };
996
 
        nanosleep(&sleeptime, NULL);
997
 
      }
998
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
999
 
      if(ret == -1){
1000
 
        perror("close");
1001
 
      }
1002
 
      /* Restores kernel loglevel to default */
1003
 
      ret = klogctl(7, NULL, 0);
1004
 
      if(ret == -1){
1005
 
        perror("klogctl");
1006
 
      }
 
841
    pubkeyfile = combinepath(keydir, pubkeyfile);
 
842
    if (pubkeyfile == NULL){
 
843
      perror("combinepath");
 
844
      exitcode = EXIT_FAILURE;
 
845
      goto end;
1007
846
    }
1008
847
    
 
848
    seckeyfile = combinepath(keydir, seckeyfile);
 
849
    if (seckeyfile == NULL){
 
850
      perror("combinepath");
 
851
      goto end;
 
852
    }
 
853
 
 
854
    ret = init_gnutls_global(&mc, pubkeyfile, seckeyfile);
 
855
    if (ret == -1){
 
856
      fprintf(stderr, "init_gnutls_global\n");
 
857
      goto end;
 
858
    } else {
 
859
      gnutls_initalized = true;
 
860
    }
 
861
 
1009
862
    uid = getuid();
1010
863
    gid = getgid();
 
864
 
 
865
    ret = setuid(uid);
 
866
    if (ret == -1){
 
867
      perror("setuid");
 
868
    }
1011
869
    
1012
870
    setgid(gid);
1013
 
    if(ret == -1){
 
871
    if (ret == -1){
1014
872
      perror("setgid");
1015
873
    }
1016
874
    
1017
 
    ret = setuid(uid);
1018
 
    if(ret == -1){
1019
 
      perror("setuid");
1020
 
    }
1021
 
    
1022
 
    ret = init_gnutls_global(&mc, pubkey, seckey);
1023
 
    if(ret == -1){
1024
 
      fprintf(stderr, "init_gnutls_global failed\n");
1025
 
      exitcode = EXIT_FAILURE;
1026
 
      goto end;
1027
 
    } else {
1028
 
      gnutls_initialized = true;
1029
 
    }
1030
 
    
1031
 
    if(mkdtemp(tempdir) == NULL){
1032
 
      perror("mkdtemp");
1033
 
      goto end;
1034
 
    }
1035
 
    tempdir_created = true;
1036
 
    
1037
 
    if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
1038
 
      fprintf(stderr, "init_gpgme failed\n");
1039
 
      exitcode = EXIT_FAILURE;
1040
 
      goto end;
1041
 
    } else {
1042
 
      gpgme_initialized = true;
1043
 
    }
1044
 
    
1045
875
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1046
876
    if(if_index == 0){
1047
877
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1048
 
      exitcode = EXIT_FAILURE;
1049
 
      goto end;
 
878
      exit(EXIT_FAILURE);
1050
879
    }
1051
880
    
1052
881
    if(connect_to != NULL){
1058
887
        exitcode = EXIT_FAILURE;
1059
888
        goto end;
1060
889
      }
1061
 
      uint16_t port;
1062
 
      ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
1063
 
      if(ret < 1 or tmpmax != (uint16_t)tmpmax
1064
 
         or address[numchars+1] != '\0'){
1065
 
        fprintf(stderr, "Bad port number\n");
 
890
      errno = 0;
 
891
      uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
 
892
      if(errno){
 
893
        perror("Bad port number");
1066
894
        exitcode = EXIT_FAILURE;
1067
895
        goto end;
1068
896
      }
1069
 
      port = (uint16_t)tmpmax;
1070
897
      *address = '\0';
1071
898
      address = connect_to;
1072
899
      ret = start_mandos_communication(address, port, if_index, &mc);
1078
905
      goto end;
1079
906
    }
1080
907
    
1081
 
    if(not debug){
 
908
    /* If the interface is down, bring it up */
 
909
    {
 
910
      sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
911
      if(sd < 0) {
 
912
        perror("socket");
 
913
        exitcode = EXIT_FAILURE;
 
914
        goto end;
 
915
      }
 
916
      strcpy(network.ifr_name, interface); /* Spurious warning */
 
917
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
918
      if(ret == -1){
 
919
        perror("ioctl SIOCGIFFLAGS");
 
920
        exitcode = EXIT_FAILURE;
 
921
        goto end;
 
922
      }
 
923
      if((network.ifr_flags & IFF_UP) == 0){
 
924
        network.ifr_flags |= IFF_UP;
 
925
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
926
        if(ret == -1){
 
927
          perror("ioctl SIOCSIFFLAGS");
 
928
          exitcode = EXIT_FAILURE;
 
929
          goto end;
 
930
        }
 
931
      }
 
932
      close(sd);
 
933
    }
 
934
    
 
935
    if (not debug){
1082
936
      avahi_set_log_function(empty_log);
1083
937
    }
1084
938
    
1087
941
    
1088
942
    /* Allocate main Avahi loop object */
1089
943
    mc.simple_poll = avahi_simple_poll_new();
1090
 
    if(mc.simple_poll == NULL) {
 
944
    if (mc.simple_poll == NULL) {
1091
945
        fprintf(stderr, "Avahi: Failed to create simple poll"
1092
946
                " object.\n");
1093
947
        exitcode = EXIT_FAILURE;
1094
948
        goto end;
1095
949
    }
1096
 
    
 
950
 
1097
951
    {
1098
952
      AvahiServerConfig config;
1099
953
      /* Do not publish any local Zeroconf records */
1102
956
      config.publish_addresses = 0;
1103
957
      config.publish_workstation = 0;
1104
958
      config.publish_domain = 0;
1105
 
      
 
959
 
1106
960
      /* Allocate a new server */
1107
961
      mc.server = avahi_server_new(avahi_simple_poll_get
1108
962
                                   (mc.simple_poll), &config, NULL,
1109
963
                                   NULL, &error);
1110
 
      
 
964
    
1111
965
      /* Free the Avahi configuration data */
1112
966
      avahi_server_config_free(&config);
1113
967
    }
1114
968
    
1115
969
    /* Check if creating the Avahi server object succeeded */
1116
 
    if(mc.server == NULL) {
 
970
    if (mc.server == NULL) {
1117
971
        fprintf(stderr, "Failed to create Avahi server: %s\n",
1118
972
                avahi_strerror(error));
1119
973
        exitcode = EXIT_FAILURE;
1125
979
                                     AVAHI_PROTO_INET6,
1126
980
                                     "_mandos._tcp", NULL, 0,
1127
981
                                     browse_callback, &mc);
1128
 
    if(sb == NULL) {
 
982
    if (sb == NULL) {
1129
983
        fprintf(stderr, "Failed to create service browser: %s\n",
1130
984
                avahi_strerror(avahi_server_errno(mc.server)));
1131
985
        exitcode = EXIT_FAILURE;
1133
987
    }
1134
988
    
1135
989
    /* Run the main loop */
1136
 
    
1137
 
    if(debug){
 
990
 
 
991
    if (debug){
1138
992
      fprintf(stderr, "Starting Avahi loop search\n");
1139
993
    }
1140
 
 
 
994
    
1141
995
    avahi_simple_poll_loop(mc.simple_poll);
1142
996
    
1143
997
 end:
1144
 
    
1145
 
    if(debug){
 
998
 
 
999
    if (debug){
1146
1000
      fprintf(stderr, "%s exiting\n", argv[0]);
1147
1001
    }
1148
1002
    
1149
1003
    /* Cleanup things */
1150
 
    if(sb != NULL)
 
1004
    if (sb != NULL)
1151
1005
        avahi_s_service_browser_free(sb);
1152
1006
    
1153
 
    if(mc.server != NULL)
 
1007
    if (mc.server != NULL)
1154
1008
        avahi_server_free(mc.server);
1155
 
    
1156
 
    if(mc.simple_poll != NULL)
 
1009
 
 
1010
    if (mc.simple_poll != NULL)
1157
1011
        avahi_simple_poll_free(mc.simple_poll);
1158
 
    
1159
 
    if(gnutls_initialized){
1160
 
      gnutls_certificate_free_credentials(mc.cred);
1161
 
      gnutls_global_deinit();
1162
 
      gnutls_dh_params_deinit(mc.dh_params);
1163
 
    }
1164
 
    
1165
 
    if(gpgme_initialized){
1166
 
      gpgme_release(mc.ctx);
1167
 
    }
1168
 
    
1169
 
    /* Removes the temp directory used by GPGME */
1170
 
    if(tempdir_created){
1171
 
      DIR *d;
1172
 
      struct dirent *direntry;
1173
 
      d = opendir(tempdir);
1174
 
      if(d == NULL){
1175
 
        if(errno != ENOENT){
1176
 
          perror("opendir");
1177
 
        }
1178
 
      } else {
1179
 
        while(true){
1180
 
          direntry = readdir(d);
1181
 
          if(direntry == NULL){
1182
 
            break;
1183
 
          }
1184
 
          /* Skip "." and ".." */
1185
 
          if(direntry->d_name[0] == '.'
1186
 
             and (direntry->d_name[1] == '\0'
1187
 
                  or (direntry->d_name[1] == '.'
1188
 
                      and direntry->d_name[2] == '\0'))){
1189
 
            continue;
1190
 
          }
1191
 
          char *fullname = NULL;
1192
 
          ret = asprintf(&fullname, "%s/%s", tempdir,
1193
 
                         direntry->d_name);
1194
 
          if(ret < 0){
1195
 
            perror("asprintf");
1196
 
            continue;
1197
 
          }
1198
 
          ret = remove(fullname);
1199
 
          if(ret == -1){
1200
 
            fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1201
 
                    strerror(errno));
1202
 
          }
1203
 
          free(fullname);
1204
 
        }
1205
 
        closedir(d);
1206
 
      }
1207
 
      ret = rmdir(tempdir);
1208
 
      if(ret == -1 and errno != ENOENT){
1209
 
        perror("rmdir");
1210
 
      }
 
1012
    free(pubkeyfile);
 
1013
    free(seckeyfile);
 
1014
 
 
1015
    if (gnutls_initalized){
 
1016
      gnutls_certificate_free_credentials (mc.cred);
 
1017
      gnutls_global_deinit ();
1211
1018
    }
1212
1019
    
1213
1020
    return exitcode;