/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 02:52:02 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090115025202-utyjssfivzumvw7m
* debian/watch: New file.

* debian/mandos-client.README.Debian (Emergency Escape): New section;
                                                         document the
                                                         "mandos=off"
                                                         kernel
                                                         parameter.
* initramfs-tools-script: Exit if kernel has parameter "mandos=off".

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