/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2009-01-15 05:27:55 UTC
  • mfrom: (237.2.9 mandos-release)
  • Revision ID: teddy@fukt.bsnet.se-20090115052755-luw0gjx8727p24o3
Merge from release branch.

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