/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/password-request.c

minor edits

Show diffs side-by-side

added added

removed removed

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