/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-02-03 22:41:49 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090203224149-fc1301jojmusbzlx
* Makefile (run-server): Use "--no-dbus" unconditionally.

* initramfs-tools-script: Correct tests for writable "/conf/conf.d".

* mandos: Add process ID number to logging messages.
  (IPv6_TCPServer.server_bind): Use plain "raise".
  (main): Do not try to handle SIGSEGV; it does not work.  Use plain
         "raise".  Log KeyboardInterrupt and server exit.

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