/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release

« back to all changes in this revision

Viewing changes to plugins.d/password-request.c

  • Committer: Teddy Hogeborn
  • Date: 2008-09-05 23:39:07 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080905233907-3rz7kuwyjwma0pjx
* Makefile (confdir/clients.conf): Tighten permissions to "u=rw".
  (install-server): Set mode of "/etc/mandos/clients.conf" to
                             "u=rw".
  (install-client): Set mode of "/etc/mandos/plugins.d" to "u=rwx".
  (uninstall-client): Also remove "/usr/lib/mandos/plugins.d/usplash",
                "/usr/share/initramfs-tools/scripts/local-top/mandos",
                      and "/etc/keys/mandos".
  (purge-server): Also remove "/var/run/mandos.pid".

* initramfs-tools-hook: Use "install" instead of "mkdir".  Change
                        owner of "/lib/mandos/plugins.d" and key
                        files.  Bug fix: do not repair permissions of
                        "/lib/mandos/plugins.d".  Bug fix: Really
                        avoid deliberately unreadable files and/or
                        directories.

* mandos-keygen (umask): Changed to "077".

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