/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

mandosclient
        changed to argp

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