/mandos/release

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2009-01-15 04:55:10 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090115045510-wkqpp1ta8q9zcz7p
Tags: version-1.0.4-1
* debian/changelog (1.0.4-1): New entry.
* NEWS (1.0.4): - '' -

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));
 
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();
322
414
    return -1;
323
415
  }
324
416
  
325
417
  if(debug){
326
 
    fprintf(stderr, "Attempting to use OpenPGP certificate %s"
327
 
            " and keyfile %s as GnuTLS credentials\n", pubkeyfile,
328
 
            seckeyfile);
 
418
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
419
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
 
420
            seckeyfilename);
329
421
  }
330
422
  
331
423
  ret = gnutls_certificate_set_openpgp_key_file
332
 
    (mc->cred, pubkeyfile, seckeyfile, GNUTLS_OPENPGP_FMT_BASE64);
333
 
  if (ret != GNUTLS_E_SUCCESS) {
 
424
    (mc->cred, pubkeyfilename, seckeyfilename,
 
425
     GNUTLS_OPENPGP_FMT_BASE64);
 
426
  if(ret != GNUTLS_E_SUCCESS) {
334
427
    fprintf(stderr,
335
428
            "Error[%d] while reading the OpenPGP key pair ('%s',"
336
 
            " '%s')\n", ret, pubkeyfile, seckeyfile);
337
 
    fprintf(stdout, "The GnuTLS error is: %s\n",
 
429
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
430
    fprintf(stderr, "The GnuTLS error is: %s\n",
338
431
            safer_gnutls_strerror(ret));
339
 
    return -1;
 
432
    goto globalfail;
340
433
  }
341
434
  
342
435
  /* GnuTLS server initialization */
343
436
  ret = gnutls_dh_params_init(&mc->dh_params);
344
 
  if (ret != GNUTLS_E_SUCCESS) {
345
 
    fprintf (stderr, "Error in GnuTLS DH parameter initialization:"
346
 
             " %s\n", safer_gnutls_strerror(ret));
347
 
    return -1;
 
437
  if(ret != GNUTLS_E_SUCCESS) {
 
438
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
439
            " %s\n", safer_gnutls_strerror(ret));
 
440
    goto globalfail;
348
441
  }
349
442
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
350
 
  if (ret != GNUTLS_E_SUCCESS) {
351
 
    fprintf (stderr, "Error in GnuTLS prime generation: %s\n",
352
 
             safer_gnutls_strerror(ret));
353
 
    return -1;
 
443
  if(ret != GNUTLS_E_SUCCESS) {
 
444
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
445
            safer_gnutls_strerror(ret));
 
446
    goto globalfail;
354
447
  }
355
448
  
356
449
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
357
 
 
 
450
  
358
451
  return 0;
 
452
  
 
453
 globalfail:
 
454
  
 
455
  gnutls_certificate_free_credentials(mc->cred);
 
456
  gnutls_global_deinit();
 
457
  gnutls_dh_params_deinit(mc->dh_params);
 
458
  return -1;
359
459
}
360
460
 
361
461
static int init_gnutls_session(mandos_context *mc,
363
463
  int ret;
364
464
  /* GnuTLS session creation */
365
465
  ret = gnutls_init(session, GNUTLS_SERVER);
366
 
  if (ret != GNUTLS_E_SUCCESS){
 
466
  if(ret != GNUTLS_E_SUCCESS){
367
467
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
368
468
            safer_gnutls_strerror(ret));
369
469
  }
371
471
  {
372
472
    const char *err;
373
473
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
374
 
    if (ret != GNUTLS_E_SUCCESS) {
 
474
    if(ret != GNUTLS_E_SUCCESS) {
375
475
      fprintf(stderr, "Syntax error at: %s\n", err);
376
476
      fprintf(stderr, "GnuTLS error: %s\n",
377
477
              safer_gnutls_strerror(ret));
 
478
      gnutls_deinit(*session);
378
479
      return -1;
379
480
    }
380
481
  }
381
482
  
382
483
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
383
484
                               mc->cred);
384
 
  if (ret != GNUTLS_E_SUCCESS) {
 
485
  if(ret != GNUTLS_E_SUCCESS) {
385
486
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
386
487
            safer_gnutls_strerror(ret));
 
488
    gnutls_deinit(*session);
387
489
    return -1;
388
490
  }
389
491
  
390
492
  /* ignore client certificate if any. */
391
 
  gnutls_certificate_server_set_request (*session,
392
 
                                         GNUTLS_CERT_IGNORE);
 
493
  gnutls_certificate_server_set_request(*session,
 
494
                                        GNUTLS_CERT_IGNORE);
393
495
  
394
 
  gnutls_dh_set_prime_bits (*session, mc->dh_bits);
 
496
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
395
497
  
396
498
  return 0;
397
499
}
405
507
                                      AvahiIfIndex if_index,
406
508
                                      mandos_context *mc){
407
509
  int ret, tcp_sd;
 
510
  ssize_t sret;
408
511
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
409
512
  char *buffer = NULL;
410
513
  char *decrypted_buffer;
416
519
  char interface[IF_NAMESIZE];
417
520
  gnutls_session_t session;
418
521
  
419
 
  ret = init_gnutls_session (mc, &session);
420
 
  if (ret != 0){
 
522
  ret = init_gnutls_session(mc, &session);
 
523
  if(ret != 0){
421
524
    return -1;
422
525
  }
423
526
  
424
527
  if(debug){
425
 
    fprintf(stderr, "Setting up a tcp connection to %s, port %d\n",
426
 
            ip, port);
 
528
    fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
 
529
            "\n", ip, port);
427
530
  }
428
531
  
429
532
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
431
534
    perror("socket");
432
535
    return -1;
433
536
  }
434
 
 
 
537
  
435
538
  if(debug){
436
539
    if(if_indextoname((unsigned int)if_index, interface) == NULL){
437
540
      perror("if_indextoname");
440
543
    fprintf(stderr, "Binding to interface %s\n", interface);
441
544
  }
442
545
  
443
 
  memset(&to,0,sizeof(to));     /* Spurious warning */
 
546
  memset(&to, 0, sizeof(to));
444
547
  to.in6.sin6_family = AF_INET6;
445
548
  /* It would be nice to have a way to detect if we were passed an
446
549
     IPv4 address here.   Now we assume an IPv6 address. */
447
550
  ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
448
 
  if (ret < 0 ){
 
551
  if(ret < 0 ){
449
552
    perror("inet_pton");
450
553
    return -1;
451
554
  }
453
556
    fprintf(stderr, "Bad address: %s\n", ip);
454
557
    return -1;
455
558
  }
456
 
  to.in6.sin6_port = htons(port);       /* Spurious warning */
 
559
  to.in6.sin6_port = htons(port); /* Spurious warnings from
 
560
                                     -Wconversion and
 
561
                                     -Wunreachable-code */
457
562
  
458
563
  to.in6.sin6_scope_id = (uint32_t)if_index;
459
564
  
460
565
  if(debug){
461
 
    fprintf(stderr, "Connection to: %s, port %d\n", ip, port);
 
566
    fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
567
            port);
462
568
    char addrstr[INET6_ADDRSTRLEN] = "";
463
569
    if(inet_ntop(to.in6.sin6_family, &(to.in6.sin6_addr), addrstr,
464
570
                 sizeof(addrstr)) == NULL){
471
577
  }
472
578
  
473
579
  ret = connect(tcp_sd, &to.in, sizeof(to));
474
 
  if (ret < 0){
 
580
  if(ret < 0){
475
581
    perror("connect");
476
582
    return -1;
477
583
  }
478
 
 
 
584
  
479
585
  const char *out = mandos_protocol_version;
480
586
  written = 0;
481
 
  while (true){
 
587
  while(true){
482
588
    size_t out_size = strlen(out);
483
 
    ret = TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
 
589
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
484
590
                                   out_size - written));
485
 
    if (ret == -1){
 
591
    if(ret == -1){
486
592
      perror("write");
487
593
      retval = -1;
488
594
      goto mandos_end;
491
597
    if(written < out_size){
492
598
      continue;
493
599
    } else {
494
 
      if (out == mandos_protocol_version){
 
600
      if(out == mandos_protocol_version){
495
601
        written = 0;
496
602
        out = "\r\n";
497
603
      } else {
499
605
      }
500
606
    }
501
607
  }
502
 
 
 
608
  
503
609
  if(debug){
504
610
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
505
611
  }
506
612
  
507
 
  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) tcp_sd);
508
 
  
509
 
  ret = gnutls_handshake (session);
510
 
  
511
 
  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){
512
620
    if(debug){
513
621
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
514
 
      gnutls_perror (ret);
 
622
      gnutls_perror(ret);
515
623
    }
516
624
    retval = -1;
517
625
    goto mandos_end;
523
631
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
524
632
            ip);
525
633
  }
526
 
 
 
634
  
527
635
  while(true){
528
636
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
529
637
                                   buffer_capacity);
530
 
    if (buffer_capacity == 0){
 
638
    if(buffer_capacity == 0){
531
639
      perror("adjustbuffer");
532
640
      retval = -1;
533
641
      goto mandos_end;
534
642
    }
535
643
    
536
 
    ret = gnutls_record_recv(session, buffer+buffer_length,
537
 
                             BUFFER_SIZE);
538
 
    if (ret == 0){
 
644
    sret = gnutls_record_recv(session, buffer+buffer_length,
 
645
                              BUFFER_SIZE);
 
646
    if(sret == 0){
539
647
      break;
540
648
    }
541
 
    if (ret < 0){
542
 
      switch(ret){
 
649
    if(sret < 0){
 
650
      switch(sret){
543
651
      case GNUTLS_E_INTERRUPTED:
544
652
      case GNUTLS_E_AGAIN:
545
653
        break;
546
654
      case GNUTLS_E_REHANDSHAKE:
547
 
        ret = gnutls_handshake (session);
548
 
        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){
549
659
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
550
 
          gnutls_perror (ret);
 
660
          gnutls_perror(ret);
551
661
          retval = -1;
552
662
          goto mandos_end;
553
663
        }
556
666
        fprintf(stderr, "Unknown error while reading data from"
557
667
                " encrypted session with Mandos server\n");
558
668
        retval = -1;
559
 
        gnutls_bye (session, GNUTLS_SHUT_RDWR);
 
669
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
560
670
        goto mandos_end;
561
671
      }
562
672
    } else {
563
 
      buffer_length += (size_t) ret;
 
673
      buffer_length += (size_t) sret;
564
674
    }
565
675
  }
566
676
  
568
678
    fprintf(stderr, "Closing TLS session\n");
569
679
  }
570
680
  
571
 
  gnutls_bye (session, GNUTLS_SHUT_RDWR);
 
681
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
572
682
  
573
 
  if (buffer_length > 0){
574
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
683
  if(buffer_length > 0){
 
684
    decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
575
685
                                               buffer_length,
576
 
                                               &decrypted_buffer,
577
 
                                               keydir);
578
 
    if (decrypted_buffer_size >= 0){
 
686
                                               &decrypted_buffer);
 
687
    if(decrypted_buffer_size >= 0){
579
688
      written = 0;
580
689
      while(written < (size_t) decrypted_buffer_size){
581
 
        ret = (int)fwrite (decrypted_buffer + written, 1,
582
 
                           (size_t)decrypted_buffer_size - written,
583
 
                           stdout);
 
690
        ret = (int)fwrite(decrypted_buffer + written, 1,
 
691
                          (size_t)decrypted_buffer_size - written,
 
692
                          stdout);
584
693
        if(ret == 0 and ferror(stdout)){
585
694
          if(debug){
586
695
            fprintf(stderr, "Error writing encrypted data: %s\n",
595
704
    } else {
596
705
      retval = -1;
597
706
    }
 
707
  } else {
 
708
    retval = -1;
598
709
  }
599
710
  
600
711
  /* Shutdown procedure */
601
712
  
602
713
 mandos_end:
603
714
  free(buffer);
604
 
  close(tcp_sd);
605
 
  gnutls_deinit (session);
606
 
  gnutls_certificate_free_credentials (mc->cred);
607
 
  gnutls_global_deinit ();
 
715
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
716
  if(ret == -1){
 
717
    perror("close");
 
718
  }
 
719
  gnutls_deinit(session);
608
720
  return retval;
609
721
}
610
722
 
623
735
                             flags,
624
736
                             void* userdata) {
625
737
  mandos_context *mc = userdata;
626
 
  assert(r);                    /* Spurious warning */
 
738
  assert(r);
627
739
  
628
740
  /* Called whenever a service has been resolved successfully or
629
741
     timed out */
630
742
  
631
 
  switch (event) {
 
743
  switch(event) {
632
744
  default:
633
745
  case AVAHI_RESOLVER_FAILURE:
634
746
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
641
753
      char ip[AVAHI_ADDRESS_STR_MAX];
642
754
      avahi_address_snprint(ip, sizeof(ip), address);
643
755
      if(debug){
644
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %d) on"
645
 
                " 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);
646
759
      }
647
760
      int ret = start_mandos_communication(ip, port, interface, mc);
648
 
      if (ret == 0){
649
 
        exit(EXIT_SUCCESS);
 
761
      if(ret == 0){
 
762
        avahi_simple_poll_quit(mc->simple_poll);
650
763
      }
651
764
    }
652
765
  }
664
777
                             flags,
665
778
                             void* userdata) {
666
779
  mandos_context *mc = userdata;
667
 
  assert(b);                    /* Spurious warning */
 
780
  assert(b);
668
781
  
669
782
  /* Called whenever a new services becomes available on the LAN or
670
783
     is removed from the LAN */
671
784
  
672
 
  switch (event) {
 
785
  switch(event) {
673
786
  default:
674
787
  case AVAHI_BROWSER_FAILURE:
675
788
    
684
797
       the callback function is called the Avahi server will free the
685
798
       resolver for us. */
686
799
    
687
 
    if (!(avahi_s_service_resolver_new(mc->server, interface,
 
800
    if(!(avahi_s_service_resolver_new(mc->server, interface,
688
801
                                       protocol, name, type, domain,
689
802
                                       AVAHI_PROTO_INET6, 0,
690
803
                                       resolve_callback, mc)))
704
817
  }
705
818
}
706
819
 
707
 
/* Combines file name and path and returns the malloced new
708
 
   string. some sane checks could/should be added */
709
 
static const char *combinepath(const char *first, const char *second){
710
 
  size_t f_len = strlen(first);
711
 
  size_t s_len = strlen(second);
712
 
  char *tmp = malloc(f_len + s_len + 2);
713
 
  if (tmp == NULL){
714
 
    return NULL;
715
 
  }
716
 
  if(f_len > 0){
717
 
    memcpy(tmp, first, f_len);  /* Spurious warning */
718
 
  }
719
 
  tmp[f_len] = '/';
720
 
  if(s_len > 0){
721
 
    memcpy(tmp + f_len + 1, second, s_len); /* Spurious warning */
722
 
  }
723
 
  tmp[f_len + 1 + s_len] = '\0';
724
 
  return tmp;
725
 
}
726
 
 
727
 
 
728
820
int main(int argc, char *argv[]){
729
821
    AvahiSServiceBrowser *sb = NULL;
730
822
    int error;
731
823
    int ret;
 
824
    intmax_t tmpmax;
 
825
    int numchars;
732
826
    int exitcode = EXIT_SUCCESS;
733
827
    const char *interface = "eth0";
734
828
    struct ifreq network;
736
830
    uid_t uid;
737
831
    gid_t gid;
738
832
    char *connect_to = NULL;
 
833
    char tempdir[] = "/tmp/mandosXXXXXX";
739
834
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
740
 
    const char *pubkeyfile = "pubkey.txt";
741
 
    const char *seckeyfile = "seckey.txt";
 
835
    const char *seckey = PATHDIR "/" SECKEY;
 
836
    const char *pubkey = PATHDIR "/" PUBKEY;
 
837
    
742
838
    mandos_context mc = { .simple_poll = NULL, .server = NULL,
743
 
                          .dh_bits = 1024, .priority = "SECURE256"};
 
839
                          .dh_bits = 1024, .priority = "SECURE256"
 
840
                          ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
841
    bool gnutls_initalized = false;
 
842
    bool gpgme_initalized = false;
744
843
    
745
844
    {
746
845
      struct argp_option options[] = {
747
846
        { .name = "debug", .key = 128,
748
847
          .doc = "Debug mode", .group = 3 },
749
848
        { .name = "connect", .key = 'c',
750
 
          .arg = "IP",
751
 
          .doc = "Connect directly to a sepcified mandos server",
 
849
          .arg = "ADDRESS:PORT",
 
850
          .doc = "Connect directly to a specific Mandos server",
752
851
          .group = 1 },
753
852
        { .name = "interface", .key = 'i',
754
 
          .arg = "INTERFACE",
755
 
          .doc = "Interface that Avahi will conntect through",
756
 
          .group = 1 },
757
 
        { .name = "keydir", .key = 'd',
758
 
          .arg = "KEYDIR",
759
 
          .doc = "Directory where the openpgp keyring is",
 
853
          .arg = "NAME",
 
854
          .doc = "Interface that will be used to search for Mandos"
 
855
          " servers",
760
856
          .group = 1 },
761
857
        { .name = "seckey", .key = 's',
762
 
          .arg = "SECKEY",
763
 
          .doc = "Secret openpgp key for gnutls authentication",
 
858
          .arg = "FILE",
 
859
          .doc = "OpenPGP secret key file base name",
764
860
          .group = 1 },
765
861
        { .name = "pubkey", .key = 'p',
766
 
          .arg = "PUBKEY",
767
 
          .doc = "Public openpgp key for gnutls authentication",
 
862
          .arg = "FILE",
 
863
          .doc = "OpenPGP public key file base name",
768
864
          .group = 2 },
769
865
        { .name = "dh-bits", .key = 129,
770
866
          .arg = "BITS",
771
 
          .doc = "dh-bits to use in gnutls communication",
 
867
          .doc = "Bit length of the prime number used in the"
 
868
          " Diffie-Hellman key exchange",
772
869
          .group = 2 },
773
870
        { .name = "priority", .key = 130,
774
 
          .arg = "PRIORITY",
775
 
          .doc = "GNUTLS priority", .group = 1 },
 
871
          .arg = "STRING",
 
872
          .doc = "GnuTLS priority string for the TLS handshake",
 
873
          .group = 1 },
776
874
        { .name = NULL }
777
875
      };
778
 
 
779
876
      
780
 
      error_t parse_opt (int key, char *arg,
781
 
                         struct argp_state *state) {
782
 
        /* Get the INPUT argument from `argp_parse', which we know is
783
 
           a pointer to our plugin list pointer. */
784
 
        switch (key) {
785
 
        case 128:
 
877
      error_t parse_opt(int key, char *arg,
 
878
                        struct argp_state *state) {
 
879
        switch(key) {
 
880
        case 128:               /* --debug */
786
881
          debug = true;
787
882
          break;
788
 
        case 'c':
 
883
        case 'c':               /* --connect */
789
884
          connect_to = arg;
790
885
          break;
791
 
        case 'i':
 
886
        case 'i':               /* --interface */
792
887
          interface = arg;
793
888
          break;
794
 
        case 'd':
795
 
          keydir = arg;
796
 
          break;
797
 
        case 's':
798
 
          seckeyfile = arg;
799
 
          break;
800
 
        case 'p':
801
 
          pubkeyfile = arg;
802
 
          break;
803
 
        case 129:
804
 
          errno = 0;
805
 
          mc.dh_bits = (unsigned int) strtol(arg, NULL, 10);
806
 
          if (errno){
807
 
            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");
808
900
            exit(EXIT_FAILURE);
809
901
          }
 
902
          mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
810
903
          break;
811
 
        case 130:
 
904
        case 130:               /* --priority */
812
905
          mc.priority = arg;
813
906
          break;
814
907
        case ARGP_KEY_ARG:
815
 
          argp_usage (state);
 
908
          argp_usage(state);
 
909
        case ARGP_KEY_END:
816
910
          break;
817
 
          case ARGP_KEY_END:
818
 
            break;
819
911
        default:
820
912
          return ARGP_ERR_UNKNOWN;
821
913
        }
822
914
        return 0;
823
915
      }
824
 
 
 
916
      
825
917
      struct argp argp = { .options = options, .parser = parse_opt,
826
918
                           .args_doc = "",
827
919
                           .doc = "Mandos client -- Get and decrypt"
828
 
                           " passwords from mandos server" };
829
 
      argp_parse (&argp, argc, argv, 0, 0, NULL);
830
 
    }
831
 
      
832
 
    pubkeyfile = combinepath(keydir, pubkeyfile);
833
 
    if (pubkeyfile == NULL){
834
 
      perror("combinepath");
835
 
      exitcode = EXIT_FAILURE;
836
 
      goto end;
837
 
    }
838
 
    
839
 
    seckeyfile = combinepath(keydir, seckeyfile);
840
 
    if (seckeyfile == NULL){
841
 
      perror("combinepath");
842
 
      goto end;
843
 
    }
844
 
 
845
 
    ret = init_gnutls_global(&mc, pubkeyfile, seckeyfile);
846
 
    if (ret == -1){
847
 
      fprintf(stderr, "init_gnutls_global\n");
848
 
      goto end;
849
 
    }
850
 
 
 
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
    
851
959
    uid = getuid();
852
960
    gid = getgid();
853
 
 
 
961
    
854
962
    ret = setuid(uid);
855
 
    if (ret == -1){
 
963
    if(ret == -1){
856
964
      perror("setuid");
857
965
    }
858
966
    
859
967
    setgid(gid);
860
 
    if (ret == -1){
 
968
    if(ret == -1){
861
969
      perror("setgid");
862
970
    }
863
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
    
864
995
    if_index = (AvahiIfIndex) if_nametoindex(interface);
865
996
    if(if_index == 0){
866
997
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
876
1007
        exitcode = EXIT_FAILURE;
877
1008
        goto end;
878
1009
      }
879
 
      errno = 0;
880
 
      uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
881
 
      if(errno){
882
 
        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");
883
1015
        exitcode = EXIT_FAILURE;
884
1016
        goto end;
885
1017
      }
 
1018
      port = (uint16_t)tmpmax;
886
1019
      *address = '\0';
887
1020
      address = connect_to;
888
1021
      ret = start_mandos_communication(address, port, if_index, &mc);
894
1027
      goto end;
895
1028
    }
896
1029
    
897
 
    /* If the interface is down, bring it up */
898
 
    {
899
 
      sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
900
 
      if(sd < 0) {
901
 
        perror("socket");
902
 
        exitcode = EXIT_FAILURE;
903
 
        goto end;
904
 
      }
905
 
      strcpy(network.ifr_name, interface); /* Spurious warning */
906
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
907
 
      if(ret == -1){
908
 
        perror("ioctl SIOCGIFFLAGS");
909
 
        exitcode = EXIT_FAILURE;
910
 
        goto end;
911
 
      }
912
 
      if((network.ifr_flags & IFF_UP) == 0){
913
 
        network.ifr_flags |= IFF_UP;
914
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
915
 
        if(ret == -1){
916
 
          perror("ioctl SIOCSIFFLAGS");
917
 
          exitcode = EXIT_FAILURE;
918
 
          goto end;
919
 
        }
920
 
      }
921
 
      close(sd);
922
 
    }
923
 
    
924
 
    if (not debug){
 
1030
    if(not debug){
925
1031
      avahi_set_log_function(empty_log);
926
1032
    }
927
1033
    
930
1036
    
931
1037
    /* Allocate main Avahi loop object */
932
1038
    mc.simple_poll = avahi_simple_poll_new();
933
 
    if (mc.simple_poll == NULL) {
 
1039
    if(mc.simple_poll == NULL) {
934
1040
        fprintf(stderr, "Avahi: Failed to create simple poll"
935
1041
                " object.\n");
936
1042
        exitcode = EXIT_FAILURE;
937
1043
        goto end;
938
1044
    }
939
 
 
 
1045
    
940
1046
    {
941
1047
      AvahiServerConfig config;
942
1048
      /* Do not publish any local Zeroconf records */
945
1051
      config.publish_addresses = 0;
946
1052
      config.publish_workstation = 0;
947
1053
      config.publish_domain = 0;
948
 
 
 
1054
      
949
1055
      /* Allocate a new server */
950
1056
      mc.server = avahi_server_new(avahi_simple_poll_get
951
1057
                                   (mc.simple_poll), &config, NULL,
952
1058
                                   NULL, &error);
953
 
    
 
1059
      
954
1060
      /* Free the Avahi configuration data */
955
1061
      avahi_server_config_free(&config);
956
1062
    }
957
1063
    
958
1064
    /* Check if creating the Avahi server object succeeded */
959
 
    if (mc.server == NULL) {
 
1065
    if(mc.server == NULL) {
960
1066
        fprintf(stderr, "Failed to create Avahi server: %s\n",
961
1067
                avahi_strerror(error));
962
1068
        exitcode = EXIT_FAILURE;
968
1074
                                     AVAHI_PROTO_INET6,
969
1075
                                     "_mandos._tcp", NULL, 0,
970
1076
                                     browse_callback, &mc);
971
 
    if (sb == NULL) {
 
1077
    if(sb == NULL) {
972
1078
        fprintf(stderr, "Failed to create service browser: %s\n",
973
1079
                avahi_strerror(avahi_server_errno(mc.server)));
974
1080
        exitcode = EXIT_FAILURE;
976
1082
    }
977
1083
    
978
1084
    /* Run the main loop */
979
 
 
980
 
    if (debug){
 
1085
    
 
1086
    if(debug){
981
1087
      fprintf(stderr, "Starting Avahi loop search\n");
982
1088
    }
983
1089
    
984
1090
    avahi_simple_poll_loop(mc.simple_poll);
985
1091
    
986
1092
 end:
987
 
 
988
 
    if (debug){
 
1093
    
 
1094
    if(debug){
989
1095
      fprintf(stderr, "%s exiting\n", argv[0]);
990
1096
    }
991
1097
    
992
1098
    /* Cleanup things */
993
 
    if (sb != NULL)
 
1099
    if(sb != NULL)
994
1100
        avahi_s_service_browser_free(sb);
995
1101
    
996
 
    if (mc.server != NULL)
 
1102
    if(mc.server != NULL)
997
1103
        avahi_server_free(mc.server);
998
 
 
999
 
    if (mc.simple_poll != NULL)
 
1104
    
 
1105
    if(mc.simple_poll != NULL)
1000
1106
        avahi_simple_poll_free(mc.simple_poll);
1001
 
    free(pubkeyfile);
1002
 
    free(seckeyfile);
1003
 
    
 
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
          
1004
1157
    return exitcode;
1005
1158
}