/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

  • Committer: Teddy Hogeborn
  • Date: 2008-08-03 21:45:14 UTC
  • mfrom: (24.1.13 mandos)
  • Revision ID: teddy@fukt.bsnet.se-20080803214514-plvvkrpoitwsrxeg
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
 
                                   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 */
 
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 */
100
68
 
101
69
/* GPGME */
102
 
#include <gpgme.h>              /* All GPGME types, constants and
103
 
                                   functions:
104
 
                                   gpgme_*
105
 
                                   GPGME_PROTOCOL_OpenPGP,
106
 
                                   GPG_ERR_NO_* */
 
70
#include <errno.h>              /* perror() */
 
71
#include <gpgme.h>
 
72
 
 
73
/* getopt_long */
 
74
#include <getopt.h>
107
75
 
108
76
#define BUFFER_SIZE 256
109
77
 
110
 
#define PATHDIR "/conf/conf.d/mandos"
111
 
#define SECKEY "seckey.txt"
112
 
#define PUBKEY "pubkey.txt"
 
78
static const char *keydir = "/conf/conf.d/mandos";
 
79
static const char *pubkeyfile = "pubkey.txt";
 
80
static const char *seckeyfile = "seckey.txt";
113
81
 
114
82
bool debug = false;
115
 
static const char mandos_protocol_version[] = "1";
116
 
const char *argp_program_version = "mandos-client " VERSION;
117
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
118
 
 
119
 
/* Used for passing in values through the Avahi callback functions */
 
83
 
 
84
const char mandos_protocol_version[] = "1";
 
85
 
 
86
/* Used for passing in values through all the callback functions */
120
87
typedef struct {
121
88
  AvahiSimplePoll *simple_poll;
122
89
  AvahiServer *server;
124
91
  unsigned int dh_bits;
125
92
  gnutls_dh_params_t dh_params;
126
93
  const char *priority;
127
 
  gpgme_ctx_t ctx;
128
94
} mandos_context;
129
95
 
130
 
/*
131
 
 * Make room in "buffer" for at least BUFFER_SIZE additional bytes.
132
 
 * "buffer_capacity" is how much is currently allocated,
133
 
 * "buffer_length" is how much is already used.
134
 
 */
135
96
size_t adjustbuffer(char **buffer, size_t buffer_length,
136
97
                  size_t buffer_capacity){
137
 
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
 
98
  if (buffer_length + BUFFER_SIZE > buffer_capacity){
138
99
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
139
 
    if(buffer == NULL){
 
100
    if (buffer == NULL){
140
101
      return 0;
141
102
    }
142
103
    buffer_capacity += BUFFER_SIZE;
145
106
}
146
107
 
147
108
/* 
148
 
 * Initialize GPGME.
 
109
 * Decrypt OpenPGP data using keyrings in HOMEDIR.
 
110
 * Returns -1 on error
149
111
 */
150
 
static bool init_gpgme(mandos_context *mc, const char *seckey,
151
 
                       const char *pubkey, const char *tempdir){
152
 
  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;
153
118
  gpgme_error_t rc;
 
119
  ssize_t ret;
 
120
  size_t plaintext_capacity = 0;
 
121
  ssize_t plaintext_length = 0;
154
122
  gpgme_engine_info_t engine_info;
155
123
  
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");
 
124
  if (debug){
 
125
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
194
126
  }
195
127
  
196
128
  /* Init GPGME */
197
129
  gpgme_check_version(NULL);
198
130
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
199
 
  if(rc != GPG_ERR_NO_ERROR){
 
131
  if (rc != GPG_ERR_NO_ERROR){
200
132
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
201
133
            gpgme_strsource(rc), gpgme_strerror(rc));
202
 
    return false;
 
134
    return -1;
203
135
  }
204
136
  
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){
 
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){
208
140
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
209
141
            gpgme_strsource(rc), gpgme_strerror(rc));
210
 
    return false;
 
142
    return -1;
211
143
  }
212
144
  while(engine_info != NULL){
213
145
    if(engine_info->protocol == GPGME_PROTOCOL_OpenPGP){
214
146
      gpgme_set_engine_info(GPGME_PROTOCOL_OpenPGP,
215
 
                            engine_info->file_name, tempdir);
 
147
                            engine_info->file_name, homedir);
216
148
      break;
217
149
    }
218
150
    engine_info = engine_info->next;
219
151
  }
220
152
  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");
 
153
    fprintf(stderr, "Could not set GPGME home dir to %s\n", homedir);
 
154
    return -1;
256
155
  }
257
156
  
258
157
  /* Create new GPGME data buffer from memory cryptotext */
259
158
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
260
159
                               0);
261
 
  if(rc != GPG_ERR_NO_ERROR){
 
160
  if (rc != GPG_ERR_NO_ERROR){
262
161
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
263
162
            gpgme_strsource(rc), gpgme_strerror(rc));
264
163
    return -1;
266
165
  
267
166
  /* Create new empty GPGME data buffer for the plaintext */
268
167
  rc = gpgme_data_new(&dh_plain);
269
 
  if(rc != GPG_ERR_NO_ERROR){
 
168
  if (rc != GPG_ERR_NO_ERROR){
270
169
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
271
170
            gpgme_strsource(rc), gpgme_strerror(rc));
272
171
    gpgme_data_release(dh_crypto);
273
172
    return -1;
274
173
  }
275
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
  
276
184
  /* Decrypt data from the cryptotext data buffer to the plaintext
277
185
     data buffer */
278
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
279
 
  if(rc != GPG_ERR_NO_ERROR){
 
186
  rc = gpgme_op_decrypt(ctx, dh_crypto, dh_plain);
 
187
  if (rc != GPG_ERR_NO_ERROR){
280
188
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
281
189
            gpgme_strsource(rc), gpgme_strerror(rc));
282
190
    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
191
    goto decrypt_end;
312
192
  }
313
193
  
315
195
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
316
196
  }
317
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
  
318
227
  /* 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");
 
228
  if (gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET) == -1){
 
229
    perror("pgpme_data_seek");
321
230
    plaintext_length = -1;
322
231
    goto decrypt_end;
323
232
  }
324
233
  
325
234
  *plaintext = NULL;
326
235
  while(true){
327
 
    plaintext_capacity = adjustbuffer(plaintext,
328
 
                                      (size_t)plaintext_length,
 
236
    plaintext_capacity = adjustbuffer(plaintext, (size_t)plaintext_length,
329
237
                                      plaintext_capacity);
330
 
    if(plaintext_capacity == 0){
 
238
    if (plaintext_capacity == 0){
331
239
        perror("adjustbuffer");
332
240
        plaintext_length = -1;
333
241
        goto decrypt_end;
336
244
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
337
245
                          BUFFER_SIZE);
338
246
    /* Print the data, if any */
339
 
    if(ret == 0){
 
247
    if (ret == 0){
340
248
      /* EOF */
341
249
      break;
342
250
    }
347
255
    }
348
256
    plaintext_length += ret;
349
257
  }
350
 
  
 
258
 
351
259
  if(debug){
352
260
    fprintf(stderr, "Decrypted password is: ");
353
261
    for(ssize_t i = 0; i < plaintext_length; i++){
366
274
  return plaintext_length;
367
275
}
368
276
 
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)
 
277
static const char * safer_gnutls_strerror (int value) {
 
278
  const char *ret = gnutls_strerror (value);
 
279
  if (ret == NULL)
373
280
    ret = "(unknown)";
374
281
  return ret;
375
282
}
380
287
  fprintf(stderr, "GnuTLS: %s", string);
381
288
}
382
289
 
383
 
static int init_gnutls_global(mandos_context *mc,
384
 
                              const char *pubkeyfilename,
385
 
                              const char *seckeyfilename){
 
290
static int init_gnutls_global(mandos_context *mc){
386
291
  int ret;
387
292
  
388
293
  if(debug){
389
294
    fprintf(stderr, "Initializing GnuTLS\n");
390
295
  }
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));
 
296
 
 
297
  if ((ret = gnutls_global_init ())
 
298
      != GNUTLS_E_SUCCESS) {
 
299
    fprintf (stderr, "GnuTLS global_init: %s\n",
 
300
             safer_gnutls_strerror(ret));
396
301
    return -1;
397
302
  }
398
303
  
399
 
  if(debug){
 
304
  if (debug){
400
305
    /* "Use a log level over 10 to enable all debugging options."
401
306
     * - GnuTLS manual
402
307
     */
405
310
  }
406
311
  
407
312
  /* 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();
 
313
  if ((ret = gnutls_certificate_allocate_credentials (&mc->cred))
 
314
      != GNUTLS_E_SUCCESS) {
 
315
    fprintf (stderr, "GnuTLS memory error: %s\n",
 
316
             safer_gnutls_strerror(ret));
416
317
    return -1;
417
318
  }
418
319
  
419
320
  if(debug){
420
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
421
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
422
 
            seckeyfilename);
 
321
    fprintf(stderr, "Attempting to use OpenPGP certificate %s"
 
322
            " and keyfile %s as GnuTLS credentials\n", pubkeyfile,
 
323
            seckeyfile);
423
324
  }
424
325
  
425
326
  ret = gnutls_certificate_set_openpgp_key_file
426
 
    (mc->cred, pubkeyfilename, seckeyfilename,
427
 
     GNUTLS_OPENPGP_FMT_BASE64);
428
 
  if(ret != GNUTLS_E_SUCCESS) {
 
327
    (mc->cred, pubkeyfile, seckeyfile, GNUTLS_OPENPGP_FMT_BASE64);
 
328
  if (ret != GNUTLS_E_SUCCESS) {
429
329
    fprintf(stderr,
430
330
            "Error[%d] while reading the OpenPGP key pair ('%s',"
431
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
432
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
 
331
            " '%s')\n", ret, pubkeyfile, seckeyfile);
 
332
    fprintf(stdout, "The GnuTLS error is: %s\n",
433
333
            safer_gnutls_strerror(ret));
434
 
    goto globalfail;
 
334
    return -1;
435
335
  }
436
336
  
437
337
  /* GnuTLS server initialization */
438
338
  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));
442
 
    goto globalfail;
 
339
  if (ret != GNUTLS_E_SUCCESS) {
 
340
    fprintf (stderr, "Error in GnuTLS DH parameter initialization:"
 
341
             " %s\n", safer_gnutls_strerror(ret));
 
342
    return -1;
443
343
  }
444
344
  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));
448
 
    goto globalfail;
 
345
  if (ret != GNUTLS_E_SUCCESS) {
 
346
    fprintf (stderr, "Error in GnuTLS prime generation: %s\n",
 
347
             safer_gnutls_strerror(ret));
 
348
    return -1;
449
349
  }
450
350
  
451
351
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
452
 
  
 
352
 
453
353
  return 0;
454
 
  
455
 
 globalfail:
456
 
  
457
 
  gnutls_certificate_free_credentials(mc->cred);
458
 
  gnutls_global_deinit();
459
 
  gnutls_dh_params_deinit(mc->dh_params);
460
 
  return -1;
461
354
}
462
355
 
463
 
static int init_gnutls_session(mandos_context *mc,
464
 
                               gnutls_session_t *session){
 
356
static int init_gnutls_session(mandos_context *mc, gnutls_session_t *session){
465
357
  int ret;
466
358
  /* GnuTLS session creation */
467
359
  ret = gnutls_init(session, GNUTLS_SERVER);
468
 
  if(ret != GNUTLS_E_SUCCESS){
 
360
  if (ret != GNUTLS_E_SUCCESS){
469
361
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
470
362
            safer_gnutls_strerror(ret));
471
363
  }
473
365
  {
474
366
    const char *err;
475
367
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
476
 
    if(ret != GNUTLS_E_SUCCESS) {
 
368
    if (ret != GNUTLS_E_SUCCESS) {
477
369
      fprintf(stderr, "Syntax error at: %s\n", err);
478
370
      fprintf(stderr, "GnuTLS error: %s\n",
479
371
              safer_gnutls_strerror(ret));
480
 
      gnutls_deinit(*session);
481
372
      return -1;
482
373
    }
483
374
  }
484
375
  
485
376
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
486
377
                               mc->cred);
487
 
  if(ret != GNUTLS_E_SUCCESS) {
 
378
  if (ret != GNUTLS_E_SUCCESS) {
488
379
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
489
380
            safer_gnutls_strerror(ret));
490
 
    gnutls_deinit(*session);
491
381
    return -1;
492
382
  }
493
383
  
494
384
  /* ignore client certificate if any. */
495
 
  gnutls_certificate_server_set_request(*session,
496
 
                                        GNUTLS_CERT_IGNORE);
 
385
  gnutls_certificate_server_set_request (*session,
 
386
                                         GNUTLS_CERT_IGNORE);
497
387
  
498
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
388
  gnutls_dh_set_prime_bits (*session, mc->dh_bits);
499
389
  
500
390
  return 0;
501
391
}
509
399
                                      AvahiIfIndex if_index,
510
400
                                      mandos_context *mc){
511
401
  int ret, tcp_sd;
512
 
  ssize_t sret;
513
 
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
 
402
  struct sockaddr_in6 to;
514
403
  char *buffer = NULL;
515
404
  char *decrypted_buffer;
516
405
  size_t buffer_length = 0;
520
409
  int retval = 0;
521
410
  char interface[IF_NAMESIZE];
522
411
  gnutls_session_t session;
 
412
  gnutls_dh_params_t dh_params;
523
413
  
524
 
  ret = init_gnutls_session(mc, &session);
525
 
  if(ret != 0){
 
414
  ret = init_gnutls_session (mc, &session);
 
415
  if (ret != 0){
526
416
    return -1;
527
417
  }
528
418
  
529
419
  if(debug){
530
 
    fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
531
 
            "\n", ip, port);
 
420
    fprintf(stderr, "Setting up a tcp connection to %s, port %d\n",
 
421
            ip, port);
532
422
  }
533
423
  
534
424
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
536
426
    perror("socket");
537
427
    return -1;
538
428
  }
539
 
  
 
429
 
540
430
  if(debug){
541
431
    if(if_indextoname((unsigned int)if_index, interface) == NULL){
542
432
      perror("if_indextoname");
545
435
    fprintf(stderr, "Binding to interface %s\n", interface);
546
436
  }
547
437
  
548
 
  memset(&to, 0, sizeof(to));
549
 
  to.in6.sin6_family = AF_INET6;
 
438
  memset(&to,0,sizeof(to));     /* Spurious warning */
 
439
  to.sin6_family = AF_INET6;
550
440
  /* It would be nice to have a way to detect if we were passed an
551
441
     IPv4 address here.   Now we assume an IPv6 address. */
552
 
  ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
553
 
  if(ret < 0 ){
 
442
  ret = inet_pton(AF_INET6, ip, &to.sin6_addr);
 
443
  if (ret < 0 ){
554
444
    perror("inet_pton");
555
445
    return -1;
556
446
  }
558
448
    fprintf(stderr, "Bad address: %s\n", ip);
559
449
    return -1;
560
450
  }
561
 
  to.in6.sin6_port = htons(port); /* Spurious warnings from
562
 
                                     -Wconversion and
563
 
                                     -Wunreachable-code */
 
451
  to.sin6_port = htons(port);   /* Spurious warning */
564
452
  
565
 
  to.in6.sin6_scope_id = (uint32_t)if_index;
 
453
  to.sin6_scope_id = (uint32_t)if_index;
566
454
  
567
455
  if(debug){
568
 
    fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
569
 
            port);
 
456
    fprintf(stderr, "Connection to: %s, port %d\n", ip, port);
570
457
    char addrstr[INET6_ADDRSTRLEN] = "";
571
 
    if(inet_ntop(to.in6.sin6_family, &(to.in6.sin6_addr), addrstr,
 
458
    if(inet_ntop(to.sin6_family, &(to.sin6_addr), addrstr,
572
459
                 sizeof(addrstr)) == NULL){
573
460
      perror("inet_ntop");
574
461
    } else {
578
465
    }
579
466
  }
580
467
  
581
 
  ret = connect(tcp_sd, &to.in, sizeof(to));
582
 
  if(ret < 0){
 
468
  ret = connect(tcp_sd, (struct sockaddr *) &to, sizeof(to));
 
469
  if (ret < 0){
583
470
    perror("connect");
584
471
    return -1;
585
472
  }
586
 
  
 
473
 
587
474
  const char *out = mandos_protocol_version;
588
475
  written = 0;
589
 
  while(true){
 
476
  while (true){
590
477
    size_t out_size = strlen(out);
591
 
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
 
478
    ret = TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
592
479
                                   out_size - written));
593
 
    if(ret == -1){
 
480
    if (ret == -1){
594
481
      perror("write");
595
482
      retval = -1;
596
483
      goto mandos_end;
599
486
    if(written < out_size){
600
487
      continue;
601
488
    } else {
602
 
      if(out == mandos_protocol_version){
 
489
      if (out == mandos_protocol_version){
603
490
        written = 0;
604
491
        out = "\r\n";
605
492
      } else {
607
494
      }
608
495
    }
609
496
  }
610
 
  
 
497
 
611
498
  if(debug){
612
499
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
613
500
  }
614
501
  
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){
 
502
  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) tcp_sd);
 
503
  
 
504
  ret = gnutls_handshake (session);
 
505
  
 
506
  if (ret != GNUTLS_E_SUCCESS){
622
507
    if(debug){
623
508
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
624
 
      gnutls_perror(ret);
 
509
      gnutls_perror (ret);
625
510
    }
626
511
    retval = -1;
627
512
    goto mandos_end;
633
518
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
634
519
            ip);
635
520
  }
636
 
  
 
521
 
637
522
  while(true){
638
 
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
639
 
                                   buffer_capacity);
640
 
    if(buffer_capacity == 0){
 
523
    buffer_capacity = adjustbuffer(&buffer, buffer_length, buffer_capacity);
 
524
    if (buffer_capacity == 0){
641
525
      perror("adjustbuffer");
642
526
      retval = -1;
643
527
      goto mandos_end;
644
528
    }
645
529
    
646
 
    sret = gnutls_record_recv(session, buffer+buffer_length,
647
 
                              BUFFER_SIZE);
648
 
    if(sret == 0){
 
530
    ret = gnutls_record_recv(session, buffer+buffer_length,
 
531
                             BUFFER_SIZE);
 
532
    if (ret == 0){
649
533
      break;
650
534
    }
651
 
    if(sret < 0){
652
 
      switch(sret){
 
535
    if (ret < 0){
 
536
      switch(ret){
653
537
      case GNUTLS_E_INTERRUPTED:
654
538
      case GNUTLS_E_AGAIN:
655
539
        break;
656
540
      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){
 
541
        ret = gnutls_handshake (session);
 
542
        if (ret < 0){
661
543
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
662
 
          gnutls_perror(ret);
 
544
          gnutls_perror (ret);
663
545
          retval = -1;
664
546
          goto mandos_end;
665
547
        }
668
550
        fprintf(stderr, "Unknown error while reading data from"
669
551
                " encrypted session with Mandos server\n");
670
552
        retval = -1;
671
 
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
553
        gnutls_bye (session, GNUTLS_SHUT_RDWR);
672
554
        goto mandos_end;
673
555
      }
674
556
    } else {
675
 
      buffer_length += (size_t) sret;
 
557
      buffer_length += (size_t) ret;
676
558
    }
677
559
  }
678
560
  
680
562
    fprintf(stderr, "Closing TLS session\n");
681
563
  }
682
564
  
683
 
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
565
  gnutls_bye (session, GNUTLS_SHUT_RDWR);
684
566
  
685
 
  if(buffer_length > 0){
686
 
    decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
 
567
  if (buffer_length > 0){
 
568
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
687
569
                                               buffer_length,
688
 
                                               &decrypted_buffer);
689
 
    if(decrypted_buffer_size >= 0){
 
570
                                               &decrypted_buffer,
 
571
                                               keydir);
 
572
    if (decrypted_buffer_size >= 0){
690
573
      written = 0;
691
574
      while(written < (size_t) decrypted_buffer_size){
692
 
        ret = (int)fwrite(decrypted_buffer + written, 1,
693
 
                          (size_t)decrypted_buffer_size - written,
694
 
                          stdout);
 
575
        ret = (int)fwrite (decrypted_buffer + written, 1,
 
576
                           (size_t)decrypted_buffer_size - written,
 
577
                           stdout);
695
578
        if(ret == 0 and ferror(stdout)){
696
579
          if(debug){
697
580
            fprintf(stderr, "Error writing encrypted data: %s\n",
706
589
    } else {
707
590
      retval = -1;
708
591
    }
709
 
  } else {
710
 
    retval = -1;
711
592
  }
712
593
  
713
594
  /* Shutdown procedure */
714
595
  
715
596
 mandos_end:
716
597
  free(buffer);
717
 
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
718
 
  if(ret == -1){
719
 
    perror("close");
720
 
  }
721
 
  gnutls_deinit(session);
 
598
  close(tcp_sd);
 
599
  gnutls_deinit (session);
 
600
  gnutls_certificate_free_credentials (mc->cred);
 
601
  gnutls_global_deinit ();
722
602
  return retval;
723
603
}
724
604
 
737
617
                             flags,
738
618
                             void* userdata) {
739
619
  mandos_context *mc = userdata;
740
 
  assert(r);
 
620
  assert(r);                    /* Spurious warning */
741
621
  
742
622
  /* Called whenever a service has been resolved successfully or
743
623
     timed out */
744
624
  
745
 
  switch(event) {
 
625
  switch (event) {
746
626
  default:
747
627
  case AVAHI_RESOLVER_FAILURE:
748
628
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
755
635
      char ip[AVAHI_ADDRESS_STR_MAX];
756
636
      avahi_address_snprint(ip, sizeof(ip), address);
757
637
      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);
 
638
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %d) on"
 
639
                " port %d\n", name, host_name, ip, interface, port);
761
640
      }
762
641
      int ret = start_mandos_communication(ip, port, interface, mc);
763
 
      if(ret == 0){
764
 
        avahi_simple_poll_quit(mc->simple_poll);
 
642
      if (ret == 0){
 
643
        exit(EXIT_SUCCESS);
765
644
      }
766
645
    }
767
646
  }
779
658
                             flags,
780
659
                             void* userdata) {
781
660
  mandos_context *mc = userdata;
782
 
  assert(b);
 
661
  assert(b);                    /* Spurious warning */
783
662
  
784
663
  /* Called whenever a new services becomes available on the LAN or
785
664
     is removed from the LAN */
786
665
  
787
 
  switch(event) {
 
666
  switch (event) {
788
667
  default:
789
668
  case AVAHI_BROWSER_FAILURE:
790
669
    
799
678
       the callback function is called the Avahi server will free the
800
679
       resolver for us. */
801
680
    
802
 
    if(!(avahi_s_service_resolver_new(mc->server, interface,
 
681
    if (!(avahi_s_service_resolver_new(mc->server, interface,
803
682
                                       protocol, name, type, domain,
804
683
                                       AVAHI_PROTO_INET6, 0,
805
684
                                       resolve_callback, mc)))
819
698
  }
820
699
}
821
700
 
 
701
/* Combines file name and path and returns the malloced new
 
702
   string. some sane checks could/should be added */
 
703
static const char *combinepath(const char *first, const char *second){
 
704
  size_t f_len = strlen(first);
 
705
  size_t s_len = strlen(second);
 
706
  char *tmp = malloc(f_len + s_len + 2);
 
707
  if (tmp == NULL){
 
708
    return NULL;
 
709
  }
 
710
  if(f_len > 0){
 
711
    memcpy(tmp, first, f_len);  /* Spurious warning */
 
712
  }
 
713
  tmp[f_len] = '/';
 
714
  if(s_len > 0){
 
715
    memcpy(tmp + f_len + 1, second, s_len); /* Spurious warning */
 
716
  }
 
717
  tmp[f_len + 1 + s_len] = '\0';
 
718
  return tmp;
 
719
}
 
720
 
 
721
 
822
722
int main(int argc, char *argv[]){
823
723
    AvahiSServiceBrowser *sb = NULL;
824
724
    int error;
825
725
    int ret;
826
 
    intmax_t tmpmax;
827
 
    int numchars;
828
726
    int exitcode = EXIT_SUCCESS;
829
727
    const char *interface = "eth0";
830
728
    struct ifreq network;
832
730
    uid_t uid;
833
731
    gid_t gid;
834
732
    char *connect_to = NULL;
835
 
    char tempdir[] = "/tmp/mandosXXXXXX";
836
 
    bool tempdir_created = false;
837
733
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
838
 
    const char *seckey = PATHDIR "/" SECKEY;
839
 
    const char *pubkey = PATHDIR "/" PUBKEY;
840
 
    
841
734
    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;
 
735
                          .dh_bits = 1024, .priority = "SECURE256"};
847
736
    
848
737
    {
849
 
      struct argp_option options[] = {
850
 
        { .name = "debug", .key = 128,
851
 
          .doc = "Debug mode", .group = 3 },
852
 
        { .name = "connect", .key = 'c',
853
 
          .arg = "ADDRESS:PORT",
854
 
          .doc = "Connect directly to a specific Mandos server",
855
 
          .group = 1 },
856
 
        { .name = "interface", .key = 'i',
857
 
          .arg = "NAME",
858
 
          .doc = "Interface that will be used to search for Mandos"
859
 
          " servers",
860
 
          .group = 1 },
861
 
        { .name = "seckey", .key = 's',
862
 
          .arg = "FILE",
863
 
          .doc = "OpenPGP secret key file base name",
864
 
          .group = 1 },
865
 
        { .name = "pubkey", .key = 'p',
866
 
          .arg = "FILE",
867
 
          .doc = "OpenPGP public key file base name",
868
 
          .group = 2 },
869
 
        { .name = "dh-bits", .key = 129,
870
 
          .arg = "BITS",
871
 
          .doc = "Bit length of the prime number used in the"
872
 
          " Diffie-Hellman key exchange",
873
 
          .group = 2 },
874
 
        { .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 },
882
 
        { .name = NULL }
883
 
      };
884
 
      
885
 
      error_t parse_opt(int key, char *arg,
886
 
                        struct argp_state *state) {
887
 
        switch(key) {
888
 
        case 128:               /* --debug */
889
 
          debug = true;
890
 
          break;
891
 
        case 'c':               /* --connect */
892
 
          connect_to = arg;
893
 
          break;
894
 
        case 'i':               /* --interface */
895
 
          interface = arg;
896
 
          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");
908
 
            exit(EXIT_FAILURE);
909
 
          }
910
 
          mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
911
 
          break;
912
 
        case 130:               /* --priority */
913
 
          mc.priority = arg;
914
 
          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
 
        case ARGP_KEY_ARG:
923
 
          argp_usage(state);
924
 
        case ARGP_KEY_END:
925
 
          break;
 
738
      /* Temporary int to get the address of for getopt_long */
 
739
      int debug_int = debug ? 1 : 0;
 
740
      while (true){
 
741
        struct option long_options[] = {
 
742
          {"debug", no_argument, &debug_int, 1},
 
743
          {"connect", required_argument, NULL, 'c'},
 
744
          {"interface", required_argument, NULL, 'i'},
 
745
          {"keydir", required_argument, NULL, 'd'},
 
746
          {"seckey", required_argument, NULL, 's'},
 
747
          {"pubkey", required_argument, NULL, 'p'},
 
748
          {"dh-bits", required_argument, NULL, 'D'},
 
749
          {"priority", required_argument, NULL, 'P'},
 
750
          {0, 0, 0, 0} };
 
751
      
 
752
        int option_index = 0;
 
753
        ret = getopt_long (argc, argv, "i:", long_options,
 
754
                           &option_index);
 
755
      
 
756
        if (ret == -1){
 
757
          break;
 
758
        }
 
759
      
 
760
        switch(ret){
 
761
        case 0:
 
762
          break;
 
763
        case 'i':
 
764
          interface = optarg;
 
765
          break;
 
766
        case 'c':
 
767
          connect_to = optarg;
 
768
          break;
 
769
        case 'd':
 
770
          keydir = optarg;
 
771
          break;
 
772
        case 'p':
 
773
          pubkeyfile = optarg;
 
774
          break;
 
775
        case 's':
 
776
          seckeyfile = optarg;
 
777
          break;
 
778
        case 'D':
 
779
          errno = 0;
 
780
          mc.dh_bits = (unsigned int) strtol(optarg, NULL, 10);
 
781
          if (errno){
 
782
            perror("strtol");
 
783
            exit(EXIT_FAILURE);
 
784
          }
 
785
          break;
 
786
        case 'P':
 
787
          mc.priority = optarg;
 
788
          break;
 
789
        case '?':
926
790
        default:
927
 
          return ARGP_ERR_UNKNOWN;
928
 
        }
929
 
        return 0;
930
 
      }
931
 
      
932
 
      struct argp argp = { .options = options, .parser = parse_opt,
933
 
                           .args_doc = "",
934
 
                           .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
 
      }
942
 
    }
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
 
      
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
 
      }
1007
 
    }
1008
 
    
 
791
          /* getopt_long() has already printed a message about the
 
792
             unrcognized option, so just exit. */
 
793
          exit(EXIT_FAILURE);
 
794
        }
 
795
      }
 
796
      /* Set the global debug flag from the temporary int */
 
797
      debug = debug_int ? true : false;
 
798
    }
 
799
    
 
800
    pubkeyfile = combinepath(keydir, pubkeyfile);
 
801
    if (pubkeyfile == NULL){
 
802
      perror("combinepath");
 
803
      exitcode = EXIT_FAILURE;
 
804
      goto end;
 
805
    }
 
806
    
 
807
    seckeyfile = combinepath(keydir, seckeyfile);
 
808
    if (seckeyfile == NULL){
 
809
      perror("combinepath");
 
810
      goto end;
 
811
    }
 
812
 
 
813
    ret = init_gnutls_global(&mc);
 
814
    if (ret == -1){
 
815
      fprintf(stderr, "init_gnutls_global\n");
 
816
      goto end;
 
817
    }
 
818
 
1009
819
    uid = getuid();
1010
820
    gid = getgid();
 
821
 
 
822
    ret = setuid(uid);
 
823
    if (ret == -1){
 
824
      perror("setuid");
 
825
    }
1011
826
    
1012
827
    setgid(gid);
1013
 
    if(ret == -1){
 
828
    if (ret == -1){
1014
829
      perror("setgid");
1015
830
    }
1016
831
    
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
832
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1046
833
    if(if_index == 0){
1047
834
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1048
 
      exitcode = EXIT_FAILURE;
1049
 
      goto end;
 
835
      exit(EXIT_FAILURE);
1050
836
    }
1051
837
    
1052
838
    if(connect_to != NULL){
1058
844
        exitcode = EXIT_FAILURE;
1059
845
        goto end;
1060
846
      }
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");
 
847
      errno = 0;
 
848
      uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
 
849
      if(errno){
 
850
        perror("Bad port number");
1066
851
        exitcode = EXIT_FAILURE;
1067
852
        goto end;
1068
853
      }
1069
 
      port = (uint16_t)tmpmax;
1070
854
      *address = '\0';
1071
855
      address = connect_to;
1072
856
      ret = start_mandos_communication(address, port, if_index, &mc);
1078
862
      goto end;
1079
863
    }
1080
864
    
1081
 
    if(not debug){
 
865
    /* If the interface is down, bring it up */
 
866
    {
 
867
      sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
868
      if(sd < 0) {
 
869
        perror("socket");
 
870
        exitcode = EXIT_FAILURE;
 
871
        goto end;
 
872
      }
 
873
      strcpy(network.ifr_name, interface); /* Spurious warning */
 
874
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
875
      if(ret == -1){
 
876
        perror("ioctl SIOCGIFFLAGS");
 
877
        exitcode = EXIT_FAILURE;
 
878
        goto end;
 
879
      }
 
880
      if((network.ifr_flags & IFF_UP) == 0){
 
881
        network.ifr_flags |= IFF_UP;
 
882
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
883
        if(ret == -1){
 
884
          perror("ioctl SIOCSIFFLAGS");
 
885
          exitcode = EXIT_FAILURE;
 
886
          goto end;
 
887
        }
 
888
      }
 
889
      close(sd);
 
890
    }
 
891
    
 
892
    if (not debug){
1082
893
      avahi_set_log_function(empty_log);
1083
894
    }
1084
895
    
1087
898
    
1088
899
    /* Allocate main Avahi loop object */
1089
900
    mc.simple_poll = avahi_simple_poll_new();
1090
 
    if(mc.simple_poll == NULL) {
 
901
    if (mc.simple_poll == NULL) {
1091
902
        fprintf(stderr, "Avahi: Failed to create simple poll"
1092
903
                " object.\n");
1093
904
        exitcode = EXIT_FAILURE;
1094
905
        goto end;
1095
906
    }
1096
 
    
 
907
 
1097
908
    {
1098
909
      AvahiServerConfig config;
1099
910
      /* Do not publish any local Zeroconf records */
1102
913
      config.publish_addresses = 0;
1103
914
      config.publish_workstation = 0;
1104
915
      config.publish_domain = 0;
1105
 
      
 
916
 
1106
917
      /* Allocate a new server */
1107
918
      mc.server = avahi_server_new(avahi_simple_poll_get
1108
919
                                   (mc.simple_poll), &config, NULL,
1109
920
                                   NULL, &error);
1110
 
      
 
921
    
1111
922
      /* Free the Avahi configuration data */
1112
923
      avahi_server_config_free(&config);
1113
924
    }
1114
925
    
1115
926
    /* Check if creating the Avahi server object succeeded */
1116
 
    if(mc.server == NULL) {
 
927
    if (mc.server == NULL) {
1117
928
        fprintf(stderr, "Failed to create Avahi server: %s\n",
1118
929
                avahi_strerror(error));
1119
930
        exitcode = EXIT_FAILURE;
1125
936
                                     AVAHI_PROTO_INET6,
1126
937
                                     "_mandos._tcp", NULL, 0,
1127
938
                                     browse_callback, &mc);
1128
 
    if(sb == NULL) {
 
939
    if (sb == NULL) {
1129
940
        fprintf(stderr, "Failed to create service browser: %s\n",
1130
941
                avahi_strerror(avahi_server_errno(mc.server)));
1131
942
        exitcode = EXIT_FAILURE;
1133
944
    }
1134
945
    
1135
946
    /* Run the main loop */
1136
 
    
1137
 
    if(debug){
 
947
 
 
948
    if (debug){
1138
949
      fprintf(stderr, "Starting Avahi loop search\n");
1139
950
    }
1140
 
 
 
951
    
1141
952
    avahi_simple_poll_loop(mc.simple_poll);
1142
953
    
1143
954
 end:
1144
 
    
1145
 
    if(debug){
 
955
 
 
956
    if (debug){
1146
957
      fprintf(stderr, "%s exiting\n", argv[0]);
1147
958
    }
1148
959
    
1149
960
    /* Cleanup things */
1150
 
    if(sb != NULL)
 
961
    if (sb != NULL)
1151
962
        avahi_s_service_browser_free(sb);
1152
963
    
1153
 
    if(mc.server != NULL)
 
964
    if (mc.server != NULL)
1154
965
        avahi_server_free(mc.server);
1155
 
    
1156
 
    if(mc.simple_poll != NULL)
 
966
 
 
967
    if (mc.simple_poll != NULL)
1157
968
        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
 
      }
1211
 
    }
 
969
    free(pubkeyfile);
 
970
    free(seckeyfile);
1212
971
    
1213
972
    return exitcode;
1214
973
}