/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

  • Committer: Teddy Hogeborn
  • Date: 2008-08-31 09:26:12 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080831092612-atz9uzia38h1ijy5
* mandos.xml (OPTIONS): Moved long options before short.  Use <option>
                        tags instead of <literal>.

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