/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/mandosclient.c

merge

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