/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-09-04 14:04:09 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080904140409-anr3hckg8ew7q60e
* plugin-runner.xml (BUGS): Document the non-recursiveness of the
                            "--config-file" option.

Show diffs side-by-side

added added

removed removed

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