/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/mandosclient.c

passprompt
        Using argp instead off getopt

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(), asprintf() */
 
35
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY() */
36
36
 
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() */
 
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 */
61
44
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
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 */
 
45
                                   SIOCSIFFLAGS */
74
46
 
75
 
/* Avahi */
76
 
/* All Avahi types, constants and functions
77
 
 Avahi*, avahi_*,
78
 
 AVAHI_* */
79
47
#include <avahi-core/core.h>
80
48
#include <avahi-core/lookup.h>
81
49
#include <avahi-core/log.h>
83
51
#include <avahi-common/malloc.h>
84
52
#include <avahi-common/error.h>
85
53
 
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 */
 
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 */
94
60
 
 
61
#include <unistd.h>             /* close() */
 
62
#include <netinet/in.h>
 
63
#include <stdbool.h>            /* true */
 
64
#include <string.h>             /* memset */
 
65
#include <arpa/inet.h>          /* inet_pton() */
 
66
#include <iso646.h>             /* not */
 
67
#include <net/if.h>             /* IF_NAMESIZE */
 
68
#include <argp.h>               /* struct argp_option,
 
69
                                   struct argp_state, struct argp,
 
70
                                   argp_parse() */
95
71
/* GPGME */
96
 
#include <gpgme.h>              /* All GPGME types, constants and
97
 
                                   functions:
98
 
                                   gpgme_*
99
 
                                   GPGME_PROTOCOL_OpenPGP,
100
 
                                   GPG_ERR_NO_* */
 
72
#include <errno.h>              /* perror() */
 
73
#include <gpgme.h>
101
74
 
102
75
#define BUFFER_SIZE 256
103
76
 
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"
111
 
 
112
77
bool debug = false;
 
78
static const char *keydir = "/conf/conf.d/mandos";
 
79
const char *argp_program_version = "mandosclient 0.9";
 
80
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
113
81
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
82
 
117
83
/* Used for passing in values through the Avahi callback functions */
118
84
typedef struct {
122
88
  unsigned int dh_bits;
123
89
  gnutls_dh_params_t dh_params;
124
90
  const char *priority;
125
 
  gpgme_ctx_t ctx;
126
91
} mandos_context;
127
92
 
128
 
/*
129
 
 * Make room in "buffer" for at least BUFFER_SIZE additional bytes.
 
93
/* Make room in "buffer" for at least BUFFER_SIZE additional bytes.
130
94
 * "buffer_capacity" is how much is currently allocated,
131
 
 * "buffer_length" is how much is already used.
132
 
 */
 
95
 * "buffer_length" is how much is already used. */
133
96
size_t adjustbuffer(char **buffer, size_t buffer_length,
134
97
                  size_t buffer_capacity){
135
98
  if (buffer_length + BUFFER_SIZE > buffer_capacity){
143
106
}
144
107
 
145
108
/* 
146
 
 * Initialize GPGME.
 
109
 * Decrypt OpenPGP data using keyrings in HOMEDIR.
 
110
 * Returns -1 on error
147
111
 */
148
 
static bool init_gpgme(mandos_context *mc, const char *seckey,
149
 
                       const char *pubkey, const char *tempdir){
150
 
  int ret;
 
112
static ssize_t pgp_packet_decrypt (const char *cryptotext,
 
113
                                   size_t crypto_size,
 
114
                                   char **plaintext,
 
115
                                   const char *homedir){
 
116
  gpgme_data_t dh_crypto, dh_plain;
 
117
  gpgme_ctx_t ctx;
151
118
  gpgme_error_t rc;
 
119
  ssize_t ret;
 
120
  size_t plaintext_capacity = 0;
 
121
  ssize_t plaintext_length = 0;
152
122
  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
 
  }
189
123
  
190
124
  if (debug){
191
 
    fprintf(stderr, "Initialize gpgme\n");
 
125
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
192
126
  }
193
 
 
 
127
  
194
128
  /* Init GPGME */
195
129
  gpgme_check_version(NULL);
196
130
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
197
131
  if (rc != GPG_ERR_NO_ERROR){
198
132
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
199
133
            gpgme_strsource(rc), gpgme_strerror(rc));
200
 
    return false;
 
134
    return -1;
201
135
  }
202
 
 
203
 
    /* Set GPGME home directory for the OpenPGP engine only */
 
136
  
 
137
  /* Set GPGME home directory for the OpenPGP engine only */
204
138
  rc = gpgme_get_engine_info (&engine_info);
205
139
  if (rc != GPG_ERR_NO_ERROR){
206
140
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
207
141
            gpgme_strsource(rc), gpgme_strerror(rc));
208
 
    return false;
 
142
    return -1;
209
143
  }
210
144
  while(engine_info != NULL){
211
145
    if(engine_info->protocol == GPGME_PROTOCOL_OpenPGP){
212
146
      gpgme_set_engine_info(GPGME_PROTOCOL_OpenPGP,
213
 
                            engine_info->file_name, tempdir);
 
147
                            engine_info->file_name, homedir);
214
148
      break;
215
149
    }
216
150
    engine_info = engine_info->next;
217
151
  }
218
152
  if(engine_info == NULL){
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");
 
153
    fprintf(stderr, "Could not set GPGME home dir to %s\n", homedir);
 
154
    return -1;
254
155
  }
255
156
  
256
157
  /* Create new GPGME data buffer from memory cryptotext */
271
172
    return -1;
272
173
  }
273
174
  
 
175
  /* Create new GPGME "context" */
 
176
  rc = gpgme_new(&ctx);
 
177
  if (rc != GPG_ERR_NO_ERROR){
 
178
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
179
            gpgme_strsource(rc), gpgme_strerror(rc));
 
180
    plaintext_length = -1;
 
181
    goto decrypt_end;
 
182
  }
 
183
  
274
184
  /* Decrypt data from the cryptotext data buffer to the plaintext
275
185
     data buffer */
276
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
 
186
  rc = gpgme_op_decrypt(ctx, dh_crypto, dh_plain);
277
187
  if (rc != GPG_ERR_NO_ERROR){
278
188
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
279
189
            gpgme_strsource(rc), gpgme_strerror(rc));
280
190
    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
 
    }
309
191
    goto decrypt_end;
310
192
  }
311
193
  
313
195
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
314
196
  }
315
197
  
 
198
  if (debug){
 
199
    gpgme_decrypt_result_t result;
 
200
    result = gpgme_op_decrypt_result(ctx);
 
201
    if (result == NULL){
 
202
      fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
203
    } else {
 
204
      fprintf(stderr, "Unsupported algorithm: %s\n",
 
205
              result->unsupported_algorithm);
 
206
      fprintf(stderr, "Wrong key usage: %d\n",
 
207
              result->wrong_key_usage);
 
208
      if(result->file_name != NULL){
 
209
        fprintf(stderr, "File name: %s\n", result->file_name);
 
210
      }
 
211
      gpgme_recipient_t recipient;
 
212
      recipient = result->recipients;
 
213
      if(recipient){
 
214
        while(recipient != NULL){
 
215
          fprintf(stderr, "Public key algorithm: %s\n",
 
216
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
217
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
218
          fprintf(stderr, "Secret key available: %s\n",
 
219
                  recipient->status == GPG_ERR_NO_SECKEY
 
220
                  ? "No" : "Yes");
 
221
          recipient = recipient->next;
 
222
        }
 
223
      }
 
224
    }
 
225
  }
 
226
  
316
227
  /* Seek back to the beginning of the GPGME plaintext data buffer */
317
228
  if (gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET) == -1){
318
229
    perror("pgpme_data_seek");
345
256
    }
346
257
    plaintext_length += ret;
347
258
  }
348
 
  
 
259
 
349
260
  if(debug){
350
261
    fprintf(stderr, "Decrypted password is: ");
351
262
    for(ssize_t i = 0; i < plaintext_length; i++){
365
276
}
366
277
 
367
278
static const char * safer_gnutls_strerror (int value) {
368
 
  const char *ret = gnutls_strerror (value); /* Spurious warning */
 
279
  const char *ret = gnutls_strerror (value);
369
280
  if (ret == NULL)
370
281
    ret = "(unknown)";
371
282
  return ret;
378
289
}
379
290
 
380
291
static int init_gnutls_global(mandos_context *mc,
381
 
                              const char *pubkeyfilename,
382
 
                              const char *seckeyfilename){
 
292
                              const char *pubkeyfile,
 
293
                              const char *seckeyfile){
383
294
  int ret;
384
295
  
385
296
  if(debug){
386
297
    fprintf(stderr, "Initializing GnuTLS\n");
387
298
  }
388
 
  
389
 
  ret = gnutls_global_init();
390
 
  if (ret != GNUTLS_E_SUCCESS) {
 
299
 
 
300
  if ((ret = gnutls_global_init ())
 
301
      != GNUTLS_E_SUCCESS) {
391
302
    fprintf (stderr, "GnuTLS global_init: %s\n",
392
303
             safer_gnutls_strerror(ret));
393
304
    return -1;
402
313
  }
403
314
  
404
315
  /* OpenPGP credentials */
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
  if ((ret = gnutls_certificate_allocate_credentials (&mc->cred))
 
317
      != GNUTLS_E_SUCCESS) {
 
318
    fprintf (stderr, "GnuTLS memory error: %s\n",
409
319
             safer_gnutls_strerror(ret));
410
 
    gnutls_global_deinit ();
411
320
    return -1;
412
321
  }
413
322
  
414
323
  if(debug){
415
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
416
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
417
 
            seckeyfilename);
 
324
    fprintf(stderr, "Attempting to use OpenPGP certificate %s"
 
325
            " and keyfile %s as GnuTLS credentials\n", pubkeyfile,
 
326
            seckeyfile);
418
327
  }
419
328
  
420
329
  ret = gnutls_certificate_set_openpgp_key_file
421
 
    (mc->cred, pubkeyfilename, seckeyfilename,
422
 
     GNUTLS_OPENPGP_FMT_BASE64);
 
330
    (mc->cred, pubkeyfile, seckeyfile, GNUTLS_OPENPGP_FMT_BASE64);
423
331
  if (ret != GNUTLS_E_SUCCESS) {
424
332
    fprintf(stderr,
425
333
            "Error[%d] while reading the OpenPGP key pair ('%s',"
426
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
427
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
 
334
            " '%s')\n", ret, pubkeyfile, seckeyfile);
 
335
    fprintf(stdout, "The GnuTLS error is: %s\n",
428
336
            safer_gnutls_strerror(ret));
429
 
    goto globalfail;
 
337
    return -1;
430
338
  }
431
339
  
432
340
  /* GnuTLS server initialization */
434
342
  if (ret != GNUTLS_E_SUCCESS) {
435
343
    fprintf (stderr, "Error in GnuTLS DH parameter initialization:"
436
344
             " %s\n", safer_gnutls_strerror(ret));
437
 
    goto globalfail;
 
345
    return -1;
438
346
  }
439
347
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
440
348
  if (ret != GNUTLS_E_SUCCESS) {
441
349
    fprintf (stderr, "Error in GnuTLS prime generation: %s\n",
442
350
             safer_gnutls_strerror(ret));
443
 
    goto globalfail;
 
351
    return -1;
444
352
  }
445
353
  
446
354
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
447
 
  
 
355
 
448
356
  return 0;
449
 
  
450
 
 globalfail:
451
 
  
452
 
  gnutls_certificate_free_credentials(mc->cred);
453
 
  gnutls_global_deinit();
454
 
  return -1;
455
357
}
456
358
 
457
359
static int init_gnutls_session(mandos_context *mc,
471
373
      fprintf(stderr, "Syntax error at: %s\n", err);
472
374
      fprintf(stderr, "GnuTLS error: %s\n",
473
375
              safer_gnutls_strerror(ret));
474
 
      gnutls_deinit (*session);
475
376
      return -1;
476
377
    }
477
378
  }
481
382
  if (ret != GNUTLS_E_SUCCESS) {
482
383
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
483
384
            safer_gnutls_strerror(ret));
484
 
    gnutls_deinit (*session);
485
385
    return -1;
486
386
  }
487
387
  
520
420
  }
521
421
  
522
422
  if(debug){
523
 
    fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
524
 
            "\n", ip, port);
 
423
    fprintf(stderr, "Setting up a tcp connection to %s, port %d\n",
 
424
            ip, port);
525
425
  }
526
426
  
527
427
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
529
429
    perror("socket");
530
430
    return -1;
531
431
  }
532
 
  
 
432
 
533
433
  if(debug){
534
434
    if(if_indextoname((unsigned int)if_index, interface) == NULL){
535
435
      perror("if_indextoname");
538
438
    fprintf(stderr, "Binding to interface %s\n", interface);
539
439
  }
540
440
  
541
 
  memset(&to, 0, sizeof(to));
 
441
  memset(&to,0,sizeof(to));     /* Spurious warning */
542
442
  to.in6.sin6_family = AF_INET6;
543
443
  /* It would be nice to have a way to detect if we were passed an
544
444
     IPv4 address here.   Now we assume an IPv6 address. */
551
451
    fprintf(stderr, "Bad address: %s\n", ip);
552
452
    return -1;
553
453
  }
554
 
  to.in6.sin6_port = htons(port); /* Spurious warning */
 
454
  to.in6.sin6_port = htons(port);       /* Spurious warning */
555
455
  
556
456
  to.in6.sin6_scope_id = (uint32_t)if_index;
557
457
  
558
458
  if(debug){
559
 
    fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
560
 
            port);
 
459
    fprintf(stderr, "Connection to: %s, port %d\n", ip, port);
561
460
    char addrstr[INET6_ADDRSTRLEN] = "";
562
461
    if(inet_ntop(to.in6.sin6_family, &(to.in6.sin6_addr), addrstr,
563
462
                 sizeof(addrstr)) == NULL){
574
473
    perror("connect");
575
474
    return -1;
576
475
  }
577
 
  
 
476
 
578
477
  const char *out = mandos_protocol_version;
579
478
  written = 0;
580
479
  while (true){
598
497
      }
599
498
    }
600
499
  }
601
 
  
 
500
 
602
501
  if(debug){
603
502
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
604
503
  }
605
504
  
606
505
  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) tcp_sd);
607
506
  
608
 
  do{
609
 
    ret = gnutls_handshake (session);
610
 
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
 
507
  ret = gnutls_handshake (session);
611
508
  
612
509
  if (ret != GNUTLS_E_SUCCESS){
613
510
    if(debug){
624
521
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
625
522
            ip);
626
523
  }
627
 
  
 
524
 
628
525
  while(true){
629
526
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
630
527
                                   buffer_capacity);
645
542
      case GNUTLS_E_AGAIN:
646
543
        break;
647
544
      case GNUTLS_E_REHANDSHAKE:
648
 
        do{
649
 
          ret = gnutls_handshake (session);
650
 
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
 
545
        ret = gnutls_handshake (session);
651
546
        if (ret < 0){
652
547
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
653
548
          gnutls_perror (ret);
674
569
  gnutls_bye (session, GNUTLS_SHUT_RDWR);
675
570
  
676
571
  if (buffer_length > 0){
677
 
    decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
 
572
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
678
573
                                               buffer_length,
679
 
                                               &decrypted_buffer);
 
574
                                               &decrypted_buffer,
 
575
                                               keydir);
680
576
    if (decrypted_buffer_size >= 0){
681
577
      written = 0;
682
578
      while(written < (size_t) decrypted_buffer_size){
697
593
    } else {
698
594
      retval = -1;
699
595
    }
700
 
  } else {
701
 
    retval = -1;
702
596
  }
703
597
  
704
598
  /* Shutdown procedure */
705
599
  
706
600
 mandos_end:
707
601
  free(buffer);
708
 
  ret = TEMP_FAILURE_RETRY(close(tcp_sd));
709
 
  if(ret == -1){
710
 
    perror("close");
711
 
  }
 
602
  close(tcp_sd);
712
603
  gnutls_deinit (session);
 
604
  gnutls_certificate_free_credentials (mc->cred);
 
605
  gnutls_global_deinit ();
713
606
  return retval;
714
607
}
715
608
 
728
621
                             flags,
729
622
                             void* userdata) {
730
623
  mandos_context *mc = userdata;
731
 
  assert(r);
 
624
  assert(r);                    /* Spurious warning */
732
625
  
733
626
  /* Called whenever a service has been resolved successfully or
734
627
     timed out */
746
639
      char ip[AVAHI_ADDRESS_STR_MAX];
747
640
      avahi_address_snprint(ip, sizeof(ip), address);
748
641
      if(debug){
749
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
750
 
                PRIu16 ") on port %d\n", name, host_name, ip,
751
 
                interface, port);
 
642
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %d) on"
 
643
                " port %d\n", name, host_name, ip, interface, port);
752
644
      }
753
645
      int ret = start_mandos_communication(ip, port, interface, mc);
754
646
      if (ret == 0){
755
 
        avahi_simple_poll_quit(mc->simple_poll);
 
647
        exit(EXIT_SUCCESS);
756
648
      }
757
649
    }
758
650
  }
770
662
                             flags,
771
663
                             void* userdata) {
772
664
  mandos_context *mc = userdata;
773
 
  assert(b);
 
665
  assert(b);                    /* Spurious warning */
774
666
  
775
667
  /* Called whenever a new services becomes available on the LAN or
776
668
     is removed from the LAN */
810
702
  }
811
703
}
812
704
 
 
705
/* Combines file name and path and returns the malloced new
 
706
   string. some sane checks could/should be added */
 
707
static const char *combinepath(const char *first, const char *second){
 
708
  size_t f_len = strlen(first);
 
709
  size_t s_len = strlen(second);
 
710
  char *tmp = malloc(f_len + s_len + 2);
 
711
  if (tmp == NULL){
 
712
    return NULL;
 
713
  }
 
714
  if(f_len > 0){
 
715
    memcpy(tmp, first, f_len);  /* Spurious warning */
 
716
  }
 
717
  tmp[f_len] = '/';
 
718
  if(s_len > 0){
 
719
    memcpy(tmp + f_len + 1, second, s_len); /* Spurious warning */
 
720
  }
 
721
  tmp[f_len + 1 + s_len] = '\0';
 
722
  return tmp;
 
723
}
 
724
 
 
725
 
813
726
int main(int argc, char *argv[]){
814
727
    AvahiSServiceBrowser *sb = NULL;
815
728
    int error;
821
734
    uid_t uid;
822
735
    gid_t gid;
823
736
    char *connect_to = NULL;
824
 
    char tempdir[] = "/tmp/mandosXXXXXX";
825
737
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
826
 
    const char *seckey = PATHDIR "/" SECKEY;
827
 
    const char *pubkey = PATHDIR "/" PUBKEY;
828
 
    
 
738
    const char *pubkeyfile = "pubkey.txt";
 
739
    const char *seckeyfile = "seckey.txt";
829
740
    mandos_context mc = { .simple_poll = NULL, .server = NULL,
830
 
                          .dh_bits = 1024, .priority = "SECURE256"
831
 
                          ":!CTYPE-X.509:+CTYPE-OPENPGP" };
832
 
    bool gnutls_initalized = false;
833
 
    bool pgpme_initalized = false;
 
741
                          .dh_bits = 1024, .priority = "SECURE256"};
834
742
    
835
743
    {
836
744
      struct argp_option options[] = {
837
745
        { .name = "debug", .key = 128,
838
746
          .doc = "Debug mode", .group = 3 },
839
747
        { .name = "connect", .key = 'c',
840
 
          .arg = "ADDRESS:PORT",
841
 
          .doc = "Connect directly to a specific Mandos server",
 
748
          .arg = "IP",
 
749
          .doc = "Connect directly to a sepcified mandos server",
842
750
          .group = 1 },
843
751
        { .name = "interface", .key = 'i',
844
 
          .arg = "NAME",
845
 
          .doc = "Interface that will be used to search for Mandos"
846
 
          " servers",
 
752
          .arg = "INTERFACE",
 
753
          .doc = "Interface that Avahi will conntect through",
 
754
          .group = 1 },
 
755
        { .name = "keydir", .key = 'd',
 
756
          .arg = "KEYDIR",
 
757
          .doc = "Directory where the openpgp keyring is",
847
758
          .group = 1 },
848
759
        { .name = "seckey", .key = 's',
849
 
          .arg = "FILE",
850
 
          .doc = "OpenPGP secret key file base name",
 
760
          .arg = "SECKEY",
 
761
          .doc = "Secret openpgp key for gnutls authentication",
851
762
          .group = 1 },
852
763
        { .name = "pubkey", .key = 'p',
853
 
          .arg = "FILE",
854
 
          .doc = "OpenPGP public key file base name",
 
764
          .arg = "PUBKEY",
 
765
          .doc = "Public openpgp key for gnutls authentication",
855
766
          .group = 2 },
856
767
        { .name = "dh-bits", .key = 129,
857
768
          .arg = "BITS",
858
 
          .doc = "Bit length of the prime number used in the"
859
 
          " Diffie-Hellman key exchange",
 
769
          .doc = "dh-bits to use in gnutls communication",
860
770
          .group = 2 },
861
771
        { .name = "priority", .key = 130,
862
 
          .arg = "STRING",
863
 
          .doc = "GnuTLS priority string for the TLS handshake",
864
 
          .group = 1 },
 
772
          .arg = "PRIORITY",
 
773
          .doc = "GNUTLS priority", .group = 1 },
865
774
        { .name = NULL }
866
775
      };
 
776
 
867
777
      
868
778
      error_t parse_opt (int key, char *arg,
869
779
                         struct argp_state *state) {
870
780
        /* Get the INPUT argument from `argp_parse', which we know is
871
781
           a pointer to our plugin list pointer. */
872
782
        switch (key) {
873
 
        case 128:               /* --debug */
 
783
        case 128:
874
784
          debug = true;
875
785
          break;
876
 
        case 'c':               /* --connect */
 
786
        case 'c':
877
787
          connect_to = arg;
878
788
          break;
879
 
        case 'i':               /* --interface */
 
789
        case 'i':
880
790
          interface = arg;
881
791
          break;
882
 
        case 's':               /* --seckey */
883
 
          seckey = arg;
884
 
          break;
885
 
        case 'p':               /* --pubkey */
886
 
          pubkey = arg;
887
 
          break;
888
 
        case 129:               /* --dh-bits */
 
792
        case 'd':
 
793
          keydir = arg;
 
794
          break;
 
795
        case 's':
 
796
          seckeyfile = arg;
 
797
          break;
 
798
        case 'p':
 
799
          pubkeyfile = arg;
 
800
          break;
 
801
        case 129:
889
802
          errno = 0;
890
803
          mc.dh_bits = (unsigned int) strtol(arg, NULL, 10);
891
804
          if (errno){
893
806
            exit(EXIT_FAILURE);
894
807
          }
895
808
          break;
896
 
        case 130:               /* --priority */
 
809
        case 130:
897
810
          mc.priority = arg;
898
811
          break;
899
812
        case ARGP_KEY_ARG:
900
813
          argp_usage (state);
901
 
        case ARGP_KEY_END:
902
814
          break;
 
815
          case ARGP_KEY_END:
 
816
            break;
903
817
        default:
904
818
          return ARGP_ERR_UNKNOWN;
905
819
        }
906
820
        return 0;
907
821
      }
908
 
      
 
822
 
909
823
      struct argp argp = { .options = options, .parser = parse_opt,
910
824
                           .args_doc = "",
911
825
                           .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
 
      }
 
826
                           " passwords from mandos server" };
 
827
      argp_parse (&argp, argc, argv, 0, 0, NULL);
 
828
    }
 
829
      
 
830
    pubkeyfile = combinepath(keydir, pubkeyfile);
 
831
    if (pubkeyfile == NULL){
 
832
      perror("combinepath");
 
833
      exitcode = EXIT_FAILURE;
 
834
      goto end;
919
835
    }
920
836
    
921
 
    ret = init_gnutls_global(&mc, pubkey, seckey);
 
837
    seckeyfile = combinepath(keydir, seckeyfile);
 
838
    if (seckeyfile == NULL){
 
839
      perror("combinepath");
 
840
      goto end;
 
841
    }
 
842
 
 
843
    ret = init_gnutls_global(&mc, pubkeyfile, seckeyfile);
922
844
    if (ret == -1){
923
 
      fprintf(stderr, "init_gnutls_global failed\n");
924
 
      exitcode = EXIT_FAILURE;
 
845
      fprintf(stderr, "init_gnutls_global\n");
925
846
      goto end;
926
 
    } else {
927
 
      gnutls_initalized = true;
928
847
    }
929
848
 
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
849
    uid = getuid();
975
850
    gid = getgid();
976
 
    
 
851
 
977
852
    ret = setuid(uid);
978
853
    if (ret == -1){
979
854
      perror("setuid");
1017
892
      goto end;
1018
893
    }
1019
894
    
 
895
    /* If the interface is down, bring it up */
 
896
    {
 
897
      sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
898
      if(sd < 0) {
 
899
        perror("socket");
 
900
        exitcode = EXIT_FAILURE;
 
901
        goto end;
 
902
      }
 
903
      strcpy(network.ifr_name, interface); /* Spurious warning */
 
904
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
905
      if(ret == -1){
 
906
        perror("ioctl SIOCGIFFLAGS");
 
907
        exitcode = EXIT_FAILURE;
 
908
        goto end;
 
909
      }
 
910
      if((network.ifr_flags & IFF_UP) == 0){
 
911
        network.ifr_flags |= IFF_UP;
 
912
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
913
        if(ret == -1){
 
914
          perror("ioctl SIOCSIFFLAGS");
 
915
          exitcode = EXIT_FAILURE;
 
916
          goto end;
 
917
        }
 
918
      }
 
919
      close(sd);
 
920
    }
 
921
    
1020
922
    if (not debug){
1021
923
      avahi_set_log_function(empty_log);
1022
924
    }
1032
934
        exitcode = EXIT_FAILURE;
1033
935
        goto end;
1034
936
    }
1035
 
    
 
937
 
1036
938
    {
1037
939
      AvahiServerConfig config;
1038
940
      /* Do not publish any local Zeroconf records */
1041
943
      config.publish_addresses = 0;
1042
944
      config.publish_workstation = 0;
1043
945
      config.publish_domain = 0;
1044
 
      
 
946
 
1045
947
      /* Allocate a new server */
1046
948
      mc.server = avahi_server_new(avahi_simple_poll_get
1047
949
                                   (mc.simple_poll), &config, NULL,
1048
950
                                   NULL, &error);
1049
 
      
 
951
    
1050
952
      /* Free the Avahi configuration data */
1051
953
      avahi_server_config_free(&config);
1052
954
    }
1072
974
    }
1073
975
    
1074
976
    /* Run the main loop */
1075
 
    
 
977
 
1076
978
    if (debug){
1077
979
      fprintf(stderr, "Starting Avahi loop search\n");
1078
980
    }
1080
982
    avahi_simple_poll_loop(mc.simple_poll);
1081
983
    
1082
984
 end:
1083
 
    
 
985
 
1084
986
    if (debug){
1085
987
      fprintf(stderr, "%s exiting\n", argv[0]);
1086
988
    }
1091
993
    
1092
994
    if (mc.server != NULL)
1093
995
        avahi_server_free(mc.server);
1094
 
    
 
996
 
1095
997
    if (mc.simple_poll != NULL)
1096
998
        avahi_simple_poll_free(mc.simple_poll);
 
999
    free(pubkeyfile);
 
1000
    free(seckeyfile);
1097
1001
    
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
 
          
1143
1002
    return exitcode;
1144
1003
}