/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-08-10 20:35:01 UTC
  • mfrom: (24.1.42 mandos)
  • Revision ID: teddy@fukt.bsnet.se-20080810203501-euh3qcf1nopilksm
Merge.

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
 
#include <stdio.h>
36
 
#include <assert.h>
37
 
#include <stdlib.h>
38
 
#include <time.h>
39
 
#include <net/if.h>             /* if_nametoindex */
40
 
 
 
35
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY() */
 
36
 
 
37
#include <stdio.h>              /* fprintf(), stderr, fwrite(), stdout,
 
38
                                   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(), memcpy(), strcpy() */
 
46
#include <sys/ioctl.h>          /* ioctl */
 
47
#include <net/if.h>             /* ifreq, SIOCGIFFLAGS, SIOCSIFFLAGS,
 
48
                                   IFF_UP */
 
49
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
 
50
                                   sockaddr_in6, PF_INET6,
 
51
                                   SOCK_STREAM, INET6_ADDRSTRLEN,
 
52
                                   uid_t, gid_t */
 
53
#include <inttypes.h>           /* PRIu16 */
 
54
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
 
55
                                   struct in6_addr, inet_pton(),
 
56
                                   connect() */
 
57
#include <assert.h>             /* assert() */
 
58
#include <errno.h>              /* perror(), errno */
 
59
#include <time.h>               /* time() */
 
60
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
 
61
                                   SIOCSIFFLAGS, if_indextoname(),
 
62
                                   if_nametoindex(), IF_NAMESIZE */
 
63
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
 
64
                                   getuid(), getgid(), setuid(),
 
65
                                   setgid() */
 
66
#include <netinet/in.h>
 
67
#include <arpa/inet.h>          /* inet_pton(), htons */
 
68
#include <iso646.h>             /* not, and */
 
69
#include <argp.h>               /* struct argp_option, error_t, struct
 
70
                                   argp_state, struct argp,
 
71
                                   argp_parse(), ARGP_KEY_ARG,
 
72
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
 
73
 
 
74
/* Avahi */
 
75
/* All Avahi types, constants and functions
 
76
 Avahi*, avahi_*,
 
77
 AVAHI_* */
41
78
#include <avahi-core/core.h>
42
79
#include <avahi-core/lookup.h>
43
80
#include <avahi-core/log.h>
45
82
#include <avahi-common/malloc.h>
46
83
#include <avahi-common/error.h>
47
84
 
48
 
//mandos client part
49
 
#include <sys/types.h>          /* socket(), inet_pton() */
50
 
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
51
 
                                   struct in6_addr, inet_pton() */
52
 
#include <gnutls/gnutls.h>      /* All GnuTLS stuff */
53
 
#include <gnutls/openpgp.h>     /* GnuTLS with openpgp stuff */
54
 
 
55
 
#include <unistd.h>             /* close() */
56
 
#include <netinet/in.h>
57
 
#include <stdbool.h>            /* true */
58
 
#include <string.h>             /* memset */
59
 
#include <arpa/inet.h>          /* inet_pton() */
60
 
#include <iso646.h>             /* not */
61
 
 
62
 
// gpgme
63
 
#include <errno.h>              /* perror() */
64
 
#include <gpgme.h>
65
 
 
66
 
// getopt_long
67
 
#include <getopt.h>
 
85
/* GnuTLS */
 
86
#include <gnutls/gnutls.h>      /* All GnuTLS types, constants and functions
 
87
                                   gnutls_*
 
88
                                   init_gnutls_session(),
 
89
                                   GNUTLS_* */
 
90
#include <gnutls/openpgp.h>     /* gnutls_certificate_set_openpgp_key_file(),
 
91
                                   GNUTLS_OPENPGP_FMT_BASE64 */
 
92
 
 
93
/* GPGME */
 
94
#include <gpgme.h>              /* All GPGME types, constants and functions
 
95
                                   gpgme_*
 
96
                                   GPGME_PROTOCOL_OpenPGP,
 
97
                                   GPG_ERR_NO_* */
68
98
 
69
99
#define BUFFER_SIZE 256
70
100
 
71
 
static int dh_bits = 1024;
72
 
 
 
101
bool debug = false;
73
102
static const char *keydir = "/conf/conf.d/mandos";
74
 
static const char *pubkeyfile = "pubkey.txt";
75
 
static const char *seckeyfile = "seckey.txt";
76
 
 
77
 
bool debug = false;
78
 
 
79
 
/* Used for  */
 
103
static const char mandos_protocol_version[] = "1";
 
104
const char *argp_program_version = "password-request 1.0";
 
105
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
106
 
 
107
/* Used for passing in values through the Avahi callback functions */
80
108
typedef struct {
81
 
  gnutls_session_t session;
 
109
  AvahiSimplePoll *simple_poll;
 
110
  AvahiServer *server;
82
111
  gnutls_certificate_credentials_t cred;
 
112
  unsigned int dh_bits;
83
113
  gnutls_dh_params_t dh_params;
84
 
} encrypted_session;
85
 
 
86
 
 
87
 
static ssize_t pgp_packet_decrypt (char *packet, size_t packet_size,
88
 
                                   char **new_packet,
 
114
  const char *priority;
 
115
} mandos_context;
 
116
 
 
117
/*
 
118
 * Make room in "buffer" for at least BUFFER_SIZE additional bytes.
 
119
 * "buffer_capacity" is how much is currently allocated,
 
120
 * "buffer_length" is how much is already used.
 
121
 */
 
122
size_t adjustbuffer(char **buffer, size_t buffer_length,
 
123
                  size_t buffer_capacity){
 
124
  if (buffer_length + BUFFER_SIZE > buffer_capacity){
 
125
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
126
    if (buffer == NULL){
 
127
      return 0;
 
128
    }
 
129
    buffer_capacity += BUFFER_SIZE;
 
130
  }
 
131
  return buffer_capacity;
 
132
}
 
133
 
 
134
/* 
 
135
 * Decrypt OpenPGP data using keyrings in HOMEDIR.
 
136
 * Returns -1 on error
 
137
 */
 
138
static ssize_t pgp_packet_decrypt (const char *cryptotext,
 
139
                                   size_t crypto_size,
 
140
                                   char **plaintext,
89
141
                                   const char *homedir){
90
142
  gpgme_data_t dh_crypto, dh_plain;
91
143
  gpgme_ctx_t ctx;
92
144
  gpgme_error_t rc;
93
145
  ssize_t ret;
94
 
  ssize_t new_packet_capacity = 0;
95
 
  ssize_t new_packet_length = 0;
 
146
  size_t plaintext_capacity = 0;
 
147
  ssize_t plaintext_length = 0;
96
148
  gpgme_engine_info_t engine_info;
97
 
 
 
149
  
98
150
  if (debug){
99
 
    fprintf(stderr, "Trying to decrypt OpenPGP packet\n");
 
151
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
100
152
  }
101
153
  
102
154
  /* Init GPGME */
108
160
    return -1;
109
161
  }
110
162
  
111
 
  /* Set GPGME home directory */
 
163
  /* Set GPGME home directory for the OpenPGP engine only */
112
164
  rc = gpgme_get_engine_info (&engine_info);
113
165
  if (rc != GPG_ERR_NO_ERROR){
114
166
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
124
176
    engine_info = engine_info->next;
125
177
  }
126
178
  if(engine_info == NULL){
127
 
    fprintf(stderr, "Could not set home dir to %s\n", homedir);
 
179
    fprintf(stderr, "Could not set GPGME home dir to %s\n", homedir);
128
180
    return -1;
129
181
  }
130
182
  
131
 
  /* Create new GPGME data buffer from packet buffer */
132
 
  rc = gpgme_data_new_from_mem(&dh_crypto, packet, packet_size, 0);
 
183
  /* Create new GPGME data buffer from memory cryptotext */
 
184
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
 
185
                               0);
133
186
  if (rc != GPG_ERR_NO_ERROR){
134
187
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
135
188
            gpgme_strsource(rc), gpgme_strerror(rc));
141
194
  if (rc != GPG_ERR_NO_ERROR){
142
195
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
143
196
            gpgme_strsource(rc), gpgme_strerror(rc));
 
197
    gpgme_data_release(dh_crypto);
144
198
    return -1;
145
199
  }
146
200
  
149
203
  if (rc != GPG_ERR_NO_ERROR){
150
204
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
151
205
            gpgme_strsource(rc), gpgme_strerror(rc));
152
 
    return -1;
 
206
    plaintext_length = -1;
 
207
    goto decrypt_end;
153
208
  }
154
209
  
155
 
  /* Decrypt data from the FILE pointer to the plaintext data
156
 
     buffer */
 
210
  /* Decrypt data from the cryptotext data buffer to the plaintext
 
211
     data buffer */
157
212
  rc = gpgme_op_decrypt(ctx, dh_crypto, dh_plain);
158
213
  if (rc != GPG_ERR_NO_ERROR){
159
214
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
160
215
            gpgme_strsource(rc), gpgme_strerror(rc));
161
 
    return -1;
 
216
    plaintext_length = -1;
 
217
    goto decrypt_end;
162
218
  }
163
 
 
 
219
  
164
220
  if(debug){
165
 
    fprintf(stderr, "Decryption of OpenPGP packet succeeded\n");
 
221
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
166
222
  }
167
 
 
 
223
  
168
224
  if (debug){
169
225
    gpgme_decrypt_result_t result;
170
226
    result = gpgme_op_decrypt_result(ctx);
173
229
    } else {
174
230
      fprintf(stderr, "Unsupported algorithm: %s\n",
175
231
              result->unsupported_algorithm);
176
 
      fprintf(stderr, "Wrong key usage: %d\n",
 
232
      fprintf(stderr, "Wrong key usage: %u\n",
177
233
              result->wrong_key_usage);
178
234
      if(result->file_name != NULL){
179
235
        fprintf(stderr, "File name: %s\n", result->file_name);
194
250
    }
195
251
  }
196
252
  
197
 
  /* Delete the GPGME FILE pointer cryptotext data buffer */
198
 
  gpgme_data_release(dh_crypto);
199
 
  
200
253
  /* Seek back to the beginning of the GPGME plaintext data buffer */
201
254
  if (gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET) == -1){
202
255
    perror("pgpme_data_seek");
 
256
    plaintext_length = -1;
 
257
    goto decrypt_end;
203
258
  }
204
259
  
205
 
  *new_packet = 0;
 
260
  *plaintext = NULL;
206
261
  while(true){
207
 
    if (new_packet_length + BUFFER_SIZE > new_packet_capacity){
208
 
      *new_packet = realloc(*new_packet,
209
 
                            (unsigned int)new_packet_capacity
210
 
                            + BUFFER_SIZE);
211
 
      if (*new_packet == NULL){
212
 
        perror("realloc");
213
 
        return -1;
214
 
      }
215
 
      new_packet_capacity += BUFFER_SIZE;
 
262
    plaintext_capacity = adjustbuffer(plaintext,
 
263
                                      (size_t)plaintext_length,
 
264
                                      plaintext_capacity);
 
265
    if (plaintext_capacity == 0){
 
266
        perror("adjustbuffer");
 
267
        plaintext_length = -1;
 
268
        goto decrypt_end;
216
269
    }
217
270
    
218
 
    ret = gpgme_data_read(dh_plain, *new_packet + new_packet_length,
 
271
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
219
272
                          BUFFER_SIZE);
220
273
    /* Print the data, if any */
221
274
    if (ret == 0){
 
275
      /* EOF */
222
276
      break;
223
277
    }
224
278
    if(ret < 0){
225
279
      perror("gpgme_data_read");
226
 
      return -1;
 
280
      plaintext_length = -1;
 
281
      goto decrypt_end;
227
282
    }
228
 
    new_packet_length += ret;
 
283
    plaintext_length += ret;
229
284
  }
230
285
 
231
 
  /* FIXME: check characters before printing to screen so to not print
232
 
     terminal control characters */
233
 
  /*   if(debug){ */
234
 
  /*     fprintf(stderr, "decrypted password is: "); */
235
 
  /*     fwrite(*new_packet, 1, new_packet_length, stderr); */
236
 
  /*     fprintf(stderr, "\n"); */
237
 
  /*   } */
 
286
  if(debug){
 
287
    fprintf(stderr, "Decrypted password is: ");
 
288
    for(ssize_t i = 0; i < plaintext_length; i++){
 
289
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
 
290
    }
 
291
    fprintf(stderr, "\n");
 
292
  }
 
293
  
 
294
 decrypt_end:
 
295
  
 
296
  /* Delete the GPGME cryptotext data buffer */
 
297
  gpgme_data_release(dh_crypto);
238
298
  
239
299
  /* Delete the GPGME plaintext data buffer */
240
300
  gpgme_data_release(dh_plain);
241
 
  return new_packet_length;
 
301
  return plaintext_length;
242
302
}
243
303
 
244
304
static const char * safer_gnutls_strerror (int value) {
248
308
  return ret;
249
309
}
250
310
 
 
311
/* GnuTLS log function callback */
251
312
static void debuggnutls(__attribute__((unused)) int level,
252
313
                        const char* string){
253
 
  fprintf(stderr, "%s", string);
 
314
  fprintf(stderr, "GnuTLS: %s", string);
254
315
}
255
316
 
256
 
static int initgnutls(encrypted_session *es){
257
 
  const char *err;
 
317
static int init_gnutls_global(mandos_context *mc,
 
318
                              const char *pubkeyfile,
 
319
                              const char *seckeyfile){
258
320
  int ret;
259
321
  
260
322
  if(debug){
261
323
    fprintf(stderr, "Initializing GnuTLS\n");
262
324
  }
263
 
 
264
 
  if ((ret = gnutls_global_init ())
265
 
      != GNUTLS_E_SUCCESS) {
266
 
    fprintf (stderr, "global_init: %s\n", safer_gnutls_strerror(ret));
 
325
  
 
326
  ret = gnutls_global_init();
 
327
  if (ret != GNUTLS_E_SUCCESS) {
 
328
    fprintf (stderr, "GnuTLS global_init: %s\n",
 
329
             safer_gnutls_strerror(ret));
267
330
    return -1;
268
331
  }
269
 
 
 
332
  
270
333
  if (debug){
 
334
    /* "Use a log level over 10 to enable all debugging options."
 
335
     * - GnuTLS manual
 
336
     */
271
337
    gnutls_global_set_log_level(11);
272
338
    gnutls_global_set_log_function(debuggnutls);
273
339
  }
274
340
  
275
 
  /* openpgp credentials */
276
 
  if ((ret = gnutls_certificate_allocate_credentials (&es->cred))
277
 
      != GNUTLS_E_SUCCESS) {
278
 
    fprintf (stderr, "memory error: %s\n",
 
341
  /* OpenPGP credentials */
 
342
  gnutls_certificate_allocate_credentials(&mc->cred);
 
343
  if (ret != GNUTLS_E_SUCCESS){
 
344
    fprintf (stderr, "GnuTLS memory error: %s\n",
279
345
             safer_gnutls_strerror(ret));
 
346
    gnutls_global_deinit ();
280
347
    return -1;
281
348
  }
282
349
  
287
354
  }
288
355
  
289
356
  ret = gnutls_certificate_set_openpgp_key_file
290
 
    (es->cred, pubkeyfile, seckeyfile, GNUTLS_OPENPGP_FMT_BASE64);
 
357
    (mc->cred, pubkeyfile, seckeyfile, GNUTLS_OPENPGP_FMT_BASE64);
291
358
  if (ret != GNUTLS_E_SUCCESS) {
292
 
    fprintf
293
 
      (stderr, "Error[%d] while reading the OpenPGP key pair ('%s',"
294
 
       " '%s')\n",
295
 
       ret, pubkeyfile, seckeyfile);
296
 
    fprintf(stdout, "The Error is: %s\n",
 
359
    fprintf(stderr,
 
360
            "Error[%d] while reading the OpenPGP key pair ('%s',"
 
361
            " '%s')\n", ret, pubkeyfile, seckeyfile);
 
362
    fprintf(stdout, "The GnuTLS error is: %s\n",
297
363
            safer_gnutls_strerror(ret));
298
 
    return -1;
299
 
  }
300
 
  
301
 
  //GnuTLS server initialization
302
 
  if ((ret = gnutls_dh_params_init (&es->dh_params))
303
 
      != GNUTLS_E_SUCCESS) {
304
 
    fprintf (stderr, "Error in dh parameter initialization: %s\n",
305
 
             safer_gnutls_strerror(ret));
306
 
    return -1;
307
 
  }
308
 
  
309
 
  if ((ret = gnutls_dh_params_generate2 (es->dh_params, dh_bits))
310
 
      != GNUTLS_E_SUCCESS) {
311
 
    fprintf (stderr, "Error in prime generation: %s\n",
312
 
             safer_gnutls_strerror(ret));
313
 
    return -1;
314
 
  }
315
 
  
316
 
  gnutls_certificate_set_dh_params (es->cred, es->dh_params);
317
 
  
318
 
  // GnuTLS session creation
319
 
  if ((ret = gnutls_init (&es->session, GNUTLS_SERVER))
320
 
      != GNUTLS_E_SUCCESS){
 
364
    goto globalfail;
 
365
  }
 
366
  
 
367
  /* GnuTLS server initialization */
 
368
  ret = gnutls_dh_params_init(&mc->dh_params);
 
369
  if (ret != GNUTLS_E_SUCCESS) {
 
370
    fprintf (stderr, "Error in GnuTLS DH parameter initialization:"
 
371
             " %s\n", safer_gnutls_strerror(ret));
 
372
    goto globalfail;
 
373
  }
 
374
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
375
  if (ret != GNUTLS_E_SUCCESS) {
 
376
    fprintf (stderr, "Error in GnuTLS prime generation: %s\n",
 
377
             safer_gnutls_strerror(ret));
 
378
    goto globalfail;
 
379
  }
 
380
  
 
381
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
382
 
 
383
  return 0;
 
384
 
 
385
 globalfail:
 
386
 
 
387
  gnutls_certificate_free_credentials(mc->cred);
 
388
  gnutls_global_deinit();
 
389
  return -1;
 
390
 
 
391
}
 
392
 
 
393
static int init_gnutls_session(mandos_context *mc,
 
394
                               gnutls_session_t *session){
 
395
  int ret;
 
396
  /* GnuTLS session creation */
 
397
  ret = gnutls_init(session, GNUTLS_SERVER);
 
398
  if (ret != GNUTLS_E_SUCCESS){
321
399
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
322
400
            safer_gnutls_strerror(ret));
323
401
  }
324
402
  
325
 
  if ((ret = gnutls_priority_set_direct (es->session, "NORMAL", &err))
326
 
      != GNUTLS_E_SUCCESS) {
327
 
    fprintf(stderr, "Syntax error at: %s\n", err);
328
 
    fprintf(stderr, "GnuTLS error: %s\n",
329
 
            safer_gnutls_strerror(ret));
330
 
    return -1;
 
403
  {
 
404
    const char *err;
 
405
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
 
406
    if (ret != GNUTLS_E_SUCCESS) {
 
407
      fprintf(stderr, "Syntax error at: %s\n", err);
 
408
      fprintf(stderr, "GnuTLS error: %s\n",
 
409
              safer_gnutls_strerror(ret));
 
410
      gnutls_deinit (*session);
 
411
      return -1;
 
412
    }
331
413
  }
332
414
  
333
 
  if ((ret = gnutls_credentials_set
334
 
       (es->session, GNUTLS_CRD_CERTIFICATE, es->cred))
335
 
      != GNUTLS_E_SUCCESS) {
336
 
    fprintf(stderr, "Error setting a credentials set: %s\n",
 
415
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
 
416
                               mc->cred);
 
417
  if (ret != GNUTLS_E_SUCCESS) {
 
418
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
337
419
            safer_gnutls_strerror(ret));
 
420
    gnutls_deinit (*session);
338
421
    return -1;
339
422
  }
340
423
  
341
424
  /* ignore client certificate if any. */
342
 
  gnutls_certificate_server_set_request (es->session,
 
425
  gnutls_certificate_server_set_request (*session,
343
426
                                         GNUTLS_CERT_IGNORE);
344
427
  
345
 
  gnutls_dh_set_prime_bits (es->session, dh_bits);
 
428
  gnutls_dh_set_prime_bits (*session, mc->dh_bits);
346
429
  
347
430
  return 0;
348
431
}
349
432
 
 
433
/* Avahi log function callback */
350
434
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
351
435
                      __attribute__((unused)) const char *txt){}
352
436
 
 
437
/* Called when a Mandos server is found */
353
438
static int start_mandos_communication(const char *ip, uint16_t port,
354
 
                                      AvahiIfIndex if_index){
 
439
                                      AvahiIfIndex if_index,
 
440
                                      mandos_context *mc){
355
441
  int ret, tcp_sd;
356
 
  struct sockaddr_in6 to;
357
 
  encrypted_session es;
 
442
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
358
443
  char *buffer = NULL;
359
444
  char *decrypted_buffer;
360
445
  size_t buffer_length = 0;
361
446
  size_t buffer_capacity = 0;
362
447
  ssize_t decrypted_buffer_size;
363
 
  size_t written = 0;
 
448
  size_t written;
364
449
  int retval = 0;
365
450
  char interface[IF_NAMESIZE];
 
451
  gnutls_session_t session;
 
452
  
 
453
  ret = init_gnutls_session (mc, &session);
 
454
  if (ret != 0){
 
455
    return -1;
 
456
  }
366
457
  
367
458
  if(debug){
368
 
    fprintf(stderr, "Setting up a tcp connection to %s, port %d\n",
369
 
            ip, port);
 
459
    fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
 
460
            "\n", ip, port);
370
461
  }
371
462
  
372
463
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
374
465
    perror("socket");
375
466
    return -1;
376
467
  }
377
 
  
378
 
  if(if_indextoname((unsigned int)if_index, interface) == NULL){
379
 
    if(debug){
 
468
 
 
469
  if(debug){
 
470
    if(if_indextoname((unsigned int)if_index, interface) == NULL){
380
471
      perror("if_indextoname");
 
472
      return -1;
381
473
    }
382
 
    return -1;
383
 
  }
384
 
  
385
 
  if(debug){
386
474
    fprintf(stderr, "Binding to interface %s\n", interface);
387
475
  }
388
476
  
389
477
  memset(&to,0,sizeof(to));     /* Spurious warning */
390
 
  to.sin6_family = AF_INET6;
391
 
  ret = inet_pton(AF_INET6, ip, &to.sin6_addr);
 
478
  to.in6.sin6_family = AF_INET6;
 
479
  /* It would be nice to have a way to detect if we were passed an
 
480
     IPv4 address here.   Now we assume an IPv6 address. */
 
481
  ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
392
482
  if (ret < 0 ){
393
483
    perror("inet_pton");
394
484
    return -1;
395
 
  }  
 
485
  }
396
486
  if(ret == 0){
397
487
    fprintf(stderr, "Bad address: %s\n", ip);
398
488
    return -1;
399
489
  }
400
 
  to.sin6_port = htons(port);   /* Spurious warning */
 
490
  to.in6.sin6_port = htons(port);       /* Spurious warning */
401
491
  
402
 
  to.sin6_scope_id = (uint32_t)if_index;
 
492
  to.in6.sin6_scope_id = (uint32_t)if_index;
403
493
  
404
494
  if(debug){
405
 
    fprintf(stderr, "Connection to: %s, port %d\n", ip, port);
 
495
    fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
496
            port);
406
497
    char addrstr[INET6_ADDRSTRLEN] = "";
407
 
    if(inet_ntop(to.sin6_family, &(to.sin6_addr), addrstr,
 
498
    if(inet_ntop(to.in6.sin6_family, &(to.in6.sin6_addr), addrstr,
408
499
                 sizeof(addrstr)) == NULL){
409
500
      perror("inet_ntop");
410
501
    } else {
411
502
      if(strcmp(addrstr, ip) != 0){
412
 
        fprintf(stderr, "Canonical address form: %s\n",
413
 
                addrstr, ntohs(to.sin6_port));
 
503
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
414
504
      }
415
505
    }
416
506
  }
417
507
  
418
 
  ret = connect(tcp_sd, (struct sockaddr *) &to, sizeof(to));
 
508
  ret = connect(tcp_sd, &to.in, sizeof(to));
419
509
  if (ret < 0){
420
510
    perror("connect");
421
511
    return -1;
422
512
  }
423
 
  
424
 
  ret = initgnutls (&es);
425
 
  if (ret != 0){
426
 
    retval = -1;
427
 
    return -1;
 
513
 
 
514
  const char *out = mandos_protocol_version;
 
515
  written = 0;
 
516
  while (true){
 
517
    size_t out_size = strlen(out);
 
518
    ret = TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
 
519
                                   out_size - written));
 
520
    if (ret == -1){
 
521
      perror("write");
 
522
      retval = -1;
 
523
      goto mandos_end;
 
524
    }
 
525
    written += (size_t)ret;
 
526
    if(written < out_size){
 
527
      continue;
 
528
    } else {
 
529
      if (out == mandos_protocol_version){
 
530
        written = 0;
 
531
        out = "\r\n";
 
532
      } else {
 
533
        break;
 
534
      }
 
535
    }
428
536
  }
429
 
  
430
 
  gnutls_transport_set_ptr (es.session,
431
 
                            (gnutls_transport_ptr_t) tcp_sd);
432
 
  
 
537
 
433
538
  if(debug){
434
539
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
435
540
  }
436
541
  
437
 
  ret = gnutls_handshake (es.session);
 
542
  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) tcp_sd);
 
543
 
 
544
  do{
 
545
    ret = gnutls_handshake (session);
 
546
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
438
547
  
439
548
  if (ret != GNUTLS_E_SUCCESS){
440
549
    if(debug){
441
 
      fprintf(stderr, "\n*** Handshake failed ***\n");
 
550
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
442
551
      gnutls_perror (ret);
443
552
    }
444
553
    retval = -1;
445
 
    goto exit;
 
554
    goto mandos_end;
446
555
  }
447
556
  
448
 
  //Retrieve OpenPGP packet that contains the wanted password
 
557
  /* Read OpenPGP packet that contains the wanted password */
449
558
  
450
559
  if(debug){
451
560
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
453
562
  }
454
563
 
455
564
  while(true){
456
 
    if (buffer_length + BUFFER_SIZE > buffer_capacity){
457
 
      buffer = realloc(buffer, buffer_capacity + BUFFER_SIZE);
458
 
      if (buffer == NULL){
459
 
        perror("realloc");
460
 
        goto exit;
461
 
      }
462
 
      buffer_capacity += BUFFER_SIZE;
 
565
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
 
566
                                   buffer_capacity);
 
567
    if (buffer_capacity == 0){
 
568
      perror("adjustbuffer");
 
569
      retval = -1;
 
570
      goto mandos_end;
463
571
    }
464
572
    
465
 
    ret = gnutls_record_recv
466
 
      (es.session, buffer+buffer_length, BUFFER_SIZE);
 
573
    ret = gnutls_record_recv(session, buffer+buffer_length,
 
574
                             BUFFER_SIZE);
467
575
    if (ret == 0){
468
576
      break;
469
577
    }
473
581
      case GNUTLS_E_AGAIN:
474
582
        break;
475
583
      case GNUTLS_E_REHANDSHAKE:
476
 
        ret = gnutls_handshake (es.session);
 
584
        do{
 
585
          ret = gnutls_handshake (session);
 
586
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
477
587
        if (ret < 0){
478
 
          fprintf(stderr, "\n*** Handshake failed ***\n");
 
588
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
479
589
          gnutls_perror (ret);
480
590
          retval = -1;
481
 
          goto exit;
 
591
          goto mandos_end;
482
592
        }
483
593
        break;
484
594
      default:
485
595
        fprintf(stderr, "Unknown error while reading data from"
486
 
                " encrypted session with mandos server\n");
 
596
                " encrypted session with Mandos server\n");
487
597
        retval = -1;
488
 
        gnutls_bye (es.session, GNUTLS_SHUT_RDWR);
489
 
        goto exit;
 
598
        gnutls_bye (session, GNUTLS_SHUT_RDWR);
 
599
        goto mandos_end;
490
600
      }
491
601
    } else {
492
602
      buffer_length += (size_t) ret;
493
603
    }
494
604
  }
495
605
  
 
606
  if(debug){
 
607
    fprintf(stderr, "Closing TLS session\n");
 
608
  }
 
609
  
 
610
  gnutls_bye (session, GNUTLS_SHUT_RDWR);
 
611
  
496
612
  if (buffer_length > 0){
497
613
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
498
614
                                               buffer_length,
499
615
                                               &decrypted_buffer,
500
616
                                               keydir);
501
617
    if (decrypted_buffer_size >= 0){
 
618
      written = 0;
502
619
      while(written < (size_t) decrypted_buffer_size){
503
620
        ret = (int)fwrite (decrypted_buffer + written, 1,
504
621
                           (size_t)decrypted_buffer_size - written,
518
635
      retval = -1;
519
636
    }
520
637
  }
521
 
 
522
 
  //shutdown procedure
523
 
 
524
 
  if(debug){
525
 
    fprintf(stderr, "Closing TLS session\n");
526
 
  }
527
 
 
 
638
  
 
639
  /* Shutdown procedure */
 
640
  
 
641
 mandos_end:
528
642
  free(buffer);
529
 
  gnutls_bye (es.session, GNUTLS_SHUT_RDWR);
530
 
 exit:
531
643
  close(tcp_sd);
532
 
  gnutls_deinit (es.session);
533
 
  gnutls_certificate_free_credentials (es.cred);
534
 
  gnutls_global_deinit ();
 
644
  gnutls_deinit (session);
535
645
  return retval;
536
646
}
537
647
 
538
 
static AvahiSimplePoll *simple_poll = NULL;
539
 
static AvahiServer *server = NULL;
540
 
 
541
 
static void resolve_callback(
542
 
    AvahiSServiceResolver *r,
543
 
    AvahiIfIndex interface,
544
 
    AVAHI_GCC_UNUSED AvahiProtocol protocol,
545
 
    AvahiResolverEvent event,
546
 
    const char *name,
547
 
    const char *type,
548
 
    const char *domain,
549
 
    const char *host_name,
550
 
    const AvahiAddress *address,
551
 
    uint16_t port,
552
 
    AVAHI_GCC_UNUSED AvahiStringList *txt,
553
 
    AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
554
 
    AVAHI_GCC_UNUSED void* userdata) {
555
 
    
 
648
static void resolve_callback(AvahiSServiceResolver *r,
 
649
                             AvahiIfIndex interface,
 
650
                             AVAHI_GCC_UNUSED AvahiProtocol protocol,
 
651
                             AvahiResolverEvent event,
 
652
                             const char *name,
 
653
                             const char *type,
 
654
                             const char *domain,
 
655
                             const char *host_name,
 
656
                             const AvahiAddress *address,
 
657
                             uint16_t port,
 
658
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
 
659
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
 
660
                             flags,
 
661
                             void* userdata) {
 
662
  mandos_context *mc = userdata;
556
663
  assert(r);                    /* Spurious warning */
557
664
  
558
665
  /* Called whenever a service has been resolved successfully or
561
668
  switch (event) {
562
669
  default:
563
670
  case AVAHI_RESOLVER_FAILURE:
564
 
    fprintf(stderr, "(Resolver) Failed to resolve service '%s' of"
565
 
            " type '%s' in domain '%s': %s\n", name, type, domain,
566
 
            avahi_strerror(avahi_server_errno(server)));
 
671
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
 
672
            " of type '%s' in domain '%s': %s\n", name, type, domain,
 
673
            avahi_strerror(avahi_server_errno(mc->server)));
567
674
    break;
568
675
    
569
676
  case AVAHI_RESOLVER_FOUND:
571
678
      char ip[AVAHI_ADDRESS_STR_MAX];
572
679
      avahi_address_snprint(ip, sizeof(ip), address);
573
680
      if(debug){
574
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s) on"
575
 
                " port %d\n", name, host_name, ip, port);
 
681
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
682
                PRIu16 ") on port %d\n", name, host_name, ip,
 
683
                interface, port);
576
684
      }
577
 
      int ret = start_mandos_communication(ip, port, interface);
 
685
      int ret = start_mandos_communication(ip, port, interface, mc);
578
686
      if (ret == 0){
579
687
        exit(EXIT_SUCCESS);
580
688
      }
583
691
  avahi_s_service_resolver_free(r);
584
692
}
585
693
 
586
 
static void browse_callback(
587
 
    AvahiSServiceBrowser *b,
588
 
    AvahiIfIndex interface,
589
 
    AvahiProtocol protocol,
590
 
    AvahiBrowserEvent event,
591
 
    const char *name,
592
 
    const char *type,
593
 
    const char *domain,
594
 
    AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
595
 
    void* userdata) {
596
 
    
597
 
    AvahiServer *s = userdata;
598
 
    assert(b);                  /* Spurious warning */
599
 
    
600
 
    /* Called whenever a new services becomes available on the LAN or
601
 
       is removed from the LAN */
602
 
    
603
 
    switch (event) {
604
 
    default:
605
 
    case AVAHI_BROWSER_FAILURE:
606
 
      
607
 
      fprintf(stderr, "(Browser) %s\n",
608
 
              avahi_strerror(avahi_server_errno(server)));
609
 
      avahi_simple_poll_quit(simple_poll);
610
 
      return;
611
 
      
612
 
    case AVAHI_BROWSER_NEW:
613
 
      /* We ignore the returned resolver object. In the callback
614
 
         function we free it. If the server is terminated before
615
 
         the callback function is called the server will free
616
 
         the resolver for us. */
617
 
      
618
 
      if (!(avahi_s_service_resolver_new(s, interface, protocol, name,
619
 
                                         type, domain,
620
 
                                         AVAHI_PROTO_INET6, 0,
621
 
                                         resolve_callback, s)))
622
 
        fprintf(stderr, "Failed to resolve service '%s': %s\n", name,
623
 
                avahi_strerror(avahi_server_errno(s)));
624
 
      break;
625
 
      
626
 
    case AVAHI_BROWSER_REMOVE:
627
 
      break;
628
 
      
629
 
    case AVAHI_BROWSER_ALL_FOR_NOW:
630
 
    case AVAHI_BROWSER_CACHE_EXHAUSTED:
631
 
      break;
 
694
static void browse_callback( AvahiSServiceBrowser *b,
 
695
                             AvahiIfIndex interface,
 
696
                             AvahiProtocol protocol,
 
697
                             AvahiBrowserEvent event,
 
698
                             const char *name,
 
699
                             const char *type,
 
700
                             const char *domain,
 
701
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
 
702
                             flags,
 
703
                             void* userdata) {
 
704
  mandos_context *mc = userdata;
 
705
  assert(b);                    /* Spurious warning */
 
706
  
 
707
  /* Called whenever a new services becomes available on the LAN or
 
708
     is removed from the LAN */
 
709
  
 
710
  switch (event) {
 
711
  default:
 
712
  case AVAHI_BROWSER_FAILURE:
 
713
    
 
714
    fprintf(stderr, "(Avahi browser) %s\n",
 
715
            avahi_strerror(avahi_server_errno(mc->server)));
 
716
    avahi_simple_poll_quit(mc->simple_poll);
 
717
    return;
 
718
    
 
719
  case AVAHI_BROWSER_NEW:
 
720
    /* We ignore the returned Avahi resolver object. In the callback
 
721
       function we free it. If the Avahi server is terminated before
 
722
       the callback function is called the Avahi server will free the
 
723
       resolver for us. */
 
724
    
 
725
    if (!(avahi_s_service_resolver_new(mc->server, interface,
 
726
                                       protocol, name, type, domain,
 
727
                                       AVAHI_PROTO_INET6, 0,
 
728
                                       resolve_callback, mc)))
 
729
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
730
              name, avahi_strerror(avahi_server_errno(mc->server)));
 
731
    break;
 
732
    
 
733
  case AVAHI_BROWSER_REMOVE:
 
734
    break;
 
735
    
 
736
  case AVAHI_BROWSER_ALL_FOR_NOW:
 
737
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
 
738
    if(debug){
 
739
      fprintf(stderr, "No Mandos server found, still searching...\n");
632
740
    }
 
741
    break;
 
742
  }
633
743
}
634
744
 
635
745
/* Combines file name and path and returns the malloced new
642
752
    return NULL;
643
753
  }
644
754
  if(f_len > 0){
645
 
    memcpy(tmp, first, f_len);
 
755
    memcpy(tmp, first, f_len);  /* Spurious warning */
646
756
  }
647
757
  tmp[f_len] = '/';
648
758
  if(s_len > 0){
649
 
    memcpy(tmp + f_len + 1, second, s_len);
 
759
    memcpy(tmp + f_len + 1, second, s_len); /* Spurious warning */
650
760
  }
651
761
  tmp[f_len + 1 + s_len] = '\0';
652
762
  return tmp;
653
763
}
654
764
 
655
765
 
656
 
int main(AVAHI_GCC_UNUSED int argc, AVAHI_GCC_UNUSED char*argv[]) {
657
 
    AvahiServerConfig config;
 
766
int main(int argc, char *argv[]){
658
767
    AvahiSServiceBrowser *sb = NULL;
659
768
    int error;
660
769
    int ret;
661
 
    int debug_int = 0;
662
 
    int returncode = EXIT_SUCCESS;
663
 
    const char *interface = NULL;
 
770
    int exitcode = EXIT_SUCCESS;
 
771
    const char *interface = "eth0";
 
772
    struct ifreq network;
 
773
    int sd;
 
774
    uid_t uid;
 
775
    gid_t gid;
 
776
    char *connect_to = NULL;
664
777
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
665
 
    char *connect_to = NULL;
 
778
    const char *pubkeyfile = "pubkey.txt";
 
779
    const char *seckeyfile = "seckey.txt";
 
780
    mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
781
                          .dh_bits = 1024, .priority = "SECURE256"};
 
782
    bool gnutls_initalized = false;
666
783
    
667
 
    debug_int = debug ? 1 : 0;
668
 
    while (true){
669
 
      static struct option long_options[] = {
670
 
        {"debug", no_argument, &debug_int, 1},
671
 
        {"connect", required_argument, NULL, 'C'},
672
 
        {"interface", required_argument, NULL, 'i'},
673
 
        {"keydir", required_argument, NULL, 'd'},
674
 
        {"seckey", required_argument, NULL, 'c'},
675
 
        {"pubkey", required_argument, NULL, 'k'},
676
 
        {"dh-bits", required_argument, NULL, 'D'},
677
 
        {0, 0, 0, 0} };
678
 
      
679
 
      int option_index = 0;
680
 
      ret = getopt_long (argc, argv, "i:", long_options,
681
 
                         &option_index);
682
 
      
683
 
      if (ret == -1){
684
 
        break;
 
784
    {
 
785
      struct argp_option options[] = {
 
786
        { .name = "debug", .key = 128,
 
787
          .doc = "Debug mode", .group = 3 },
 
788
        { .name = "connect", .key = 'c',
 
789
          .arg = "IP",
 
790
          .doc = "Connect directly to a sepcified mandos server",
 
791
          .group = 1 },
 
792
        { .name = "interface", .key = 'i',
 
793
          .arg = "INTERFACE",
 
794
          .doc = "Interface that Avahi will conntect through",
 
795
          .group = 1 },
 
796
        { .name = "keydir", .key = 'd',
 
797
          .arg = "KEYDIR",
 
798
          .doc = "Directory where the openpgp keyring is",
 
799
          .group = 1 },
 
800
        { .name = "seckey", .key = 's',
 
801
          .arg = "SECKEY",
 
802
          .doc = "Secret openpgp key for gnutls authentication",
 
803
          .group = 1 },
 
804
        { .name = "pubkey", .key = 'p',
 
805
          .arg = "PUBKEY",
 
806
          .doc = "Public openpgp key for gnutls authentication",
 
807
          .group = 2 },
 
808
        { .name = "dh-bits", .key = 129,
 
809
          .arg = "BITS",
 
810
          .doc = "dh-bits to use in gnutls communication",
 
811
          .group = 2 },
 
812
        { .name = "priority", .key = 130,
 
813
          .arg = "PRIORITY",
 
814
          .doc = "GNUTLS priority", .group = 1 },
 
815
        { .name = NULL }
 
816
      };
 
817
 
 
818
      
 
819
      error_t parse_opt (int key, char *arg,
 
820
                         struct argp_state *state) {
 
821
        /* Get the INPUT argument from `argp_parse', which we know is
 
822
           a pointer to our plugin list pointer. */
 
823
        switch (key) {
 
824
        case 128:
 
825
          debug = true;
 
826
          break;
 
827
        case 'c':
 
828
          connect_to = arg;
 
829
          break;
 
830
        case 'i':
 
831
          interface = arg;
 
832
          break;
 
833
        case 'd':
 
834
          keydir = arg;
 
835
          break;
 
836
        case 's':
 
837
          seckeyfile = arg;
 
838
          break;
 
839
        case 'p':
 
840
          pubkeyfile = arg;
 
841
          break;
 
842
        case 129:
 
843
          errno = 0;
 
844
          mc.dh_bits = (unsigned int) strtol(arg, NULL, 10);
 
845
          if (errno){
 
846
            perror("strtol");
 
847
            exit(EXIT_FAILURE);
 
848
          }
 
849
          break;
 
850
        case 130:
 
851
          mc.priority = arg;
 
852
          break;
 
853
        case ARGP_KEY_ARG:
 
854
          argp_usage (state);
 
855
          break;
 
856
          case ARGP_KEY_END:
 
857
            break;
 
858
        default:
 
859
          return ARGP_ERR_UNKNOWN;
 
860
        }
 
861
        return 0;
685
862
      }
686
 
      
687
 
      switch(ret){
688
 
      case 0:
689
 
        break;
690
 
      case 'i':
691
 
        interface = optarg;
692
 
        break;
693
 
      case 'C':
694
 
        connect_to = optarg;
695
 
        break;
696
 
      case 'd':
697
 
        keydir = optarg;
698
 
        break;
699
 
      case 'c':
700
 
        pubkeyfile = optarg;
701
 
        break;
702
 
      case 'k':
703
 
        seckeyfile = optarg;
704
 
        break;
705
 
      case 'D':
706
 
        dh_bits = atoi(optarg);
707
 
        break;
708
 
      case '?':
709
 
        break
710
 
      default:
711
 
        exit(EXIT_FAILURE);
 
863
 
 
864
      struct argp argp = { .options = options, .parser = parse_opt,
 
865
                           .args_doc = "",
 
866
                           .doc = "Mandos client -- Get and decrypt"
 
867
                           " passwords from mandos server" };
 
868
      ret = argp_parse (&argp, argc, argv, 0, 0, NULL);
 
869
      if (ret == ARGP_ERR_UNKNOWN){
 
870
        fprintf(stderr, "Unkown error while parsing arguments\n");
 
871
        exitcode = EXIT_FAILURE;
 
872
        goto end;
712
873
      }
713
874
    }
714
 
    debug = debug_int ? true : false;
715
 
    
 
875
      
716
876
    pubkeyfile = combinepath(keydir, pubkeyfile);
717
877
    if (pubkeyfile == NULL){
718
878
      perror("combinepath");
719
 
      goto exit;
720
 
    }
721
 
    
722
 
    if(interface != NULL){
723
 
      if_index = (AvahiIfIndex) if_nametoindex(interface);
724
 
      if(if_index == 0){
725
 
        fprintf(stderr, "No such interface: \"%s\"\n", interface);
726
 
        exit(EXIT_FAILURE);
727
 
      }
 
879
      exitcode = EXIT_FAILURE;
 
880
      goto end;
 
881
    }
 
882
    
 
883
    seckeyfile = combinepath(keydir, seckeyfile);
 
884
    if (seckeyfile == NULL){
 
885
      perror("combinepath");
 
886
      goto end;
 
887
    }
 
888
 
 
889
    ret = init_gnutls_global(&mc, pubkeyfile, seckeyfile);
 
890
    if (ret == -1){
 
891
      fprintf(stderr, "init_gnutls_global\n");
 
892
      goto end;
 
893
    } else {
 
894
      gnutls_initalized = true;
 
895
    }
 
896
 
 
897
    uid = getuid();
 
898
    gid = getgid();
 
899
 
 
900
    ret = setuid(uid);
 
901
    if (ret == -1){
 
902
      perror("setuid");
 
903
    }
 
904
    
 
905
    setgid(gid);
 
906
    if (ret == -1){
 
907
      perror("setgid");
 
908
    }
 
909
    
 
910
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
911
    if(if_index == 0){
 
912
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
913
      exit(EXIT_FAILURE);
728
914
    }
729
915
    
730
916
    if(connect_to != NULL){
733
919
      char *address = strrchr(connect_to, ':');
734
920
      if(address == NULL){
735
921
        fprintf(stderr, "No colon in address\n");
736
 
        exit(EXIT_FAILURE);
 
922
        exitcode = EXIT_FAILURE;
 
923
        goto end;
737
924
      }
738
925
      errno = 0;
739
926
      uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
740
927
      if(errno){
741
928
        perror("Bad port number");
742
 
        exit(EXIT_FAILURE);
 
929
        exitcode = EXIT_FAILURE;
 
930
        goto end;
743
931
      }
744
932
      *address = '\0';
745
933
      address = connect_to;
746
 
      ret = start_mandos_communication(address, port, if_index);
 
934
      ret = start_mandos_communication(address, port, if_index, &mc);
747
935
      if(ret < 0){
748
 
        exit(EXIT_FAILURE);
 
936
        exitcode = EXIT_FAILURE;
749
937
      } else {
750
 
        exit(EXIT_SUCCESS);
 
938
        exitcode = EXIT_SUCCESS;
751
939
      }
 
940
      goto end;
752
941
    }
753
942
    
754
 
    seckeyfile = combinepath(keydir, seckeyfile);
755
 
    if (seckeyfile == NULL){
756
 
      perror("combinepath");
757
 
      goto exit;
 
943
    /* If the interface is down, bring it up */
 
944
    {
 
945
      sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
946
      if(sd < 0) {
 
947
        perror("socket");
 
948
        exitcode = EXIT_FAILURE;
 
949
        goto end;
 
950
      }
 
951
      strcpy(network.ifr_name, interface); /* Spurious warning */
 
952
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
953
      if(ret == -1){
 
954
        perror("ioctl SIOCGIFFLAGS");
 
955
        exitcode = EXIT_FAILURE;
 
956
        goto end;
 
957
      }
 
958
      if((network.ifr_flags & IFF_UP) == 0){
 
959
        network.ifr_flags |= IFF_UP;
 
960
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
961
        if(ret == -1){
 
962
          perror("ioctl SIOCSIFFLAGS");
 
963
          exitcode = EXIT_FAILURE;
 
964
          goto end;
 
965
        }
 
966
      }
 
967
      close(sd);
758
968
    }
759
969
    
760
970
    if (not debug){
761
971
      avahi_set_log_function(empty_log);
762
972
    }
763
973
    
764
 
    /* Initialize the psuedo-RNG */
 
974
    /* Initialize the pseudo-RNG for Avahi */
765
975
    srand((unsigned int) time(NULL));
766
 
 
767
 
    /* Allocate main loop object */
768
 
    if (!(simple_poll = avahi_simple_poll_new())) {
769
 
        fprintf(stderr, "Failed to create simple poll object.\n");
770
 
        
771
 
        goto exit;
772
 
    }
773
 
 
774
 
    /* Do not publish any local records */
775
 
    avahi_server_config_init(&config);
776
 
    config.publish_hinfo = 0;
777
 
    config.publish_addresses = 0;
778
 
    config.publish_workstation = 0;
779
 
    config.publish_domain = 0;
780
 
 
781
 
    /* Allocate a new server */
782
 
    server = avahi_server_new(avahi_simple_poll_get(simple_poll),
783
 
                              &config, NULL, NULL, &error);
784
 
 
785
 
    /* Free the configuration data */
786
 
    avahi_server_config_free(&config);
787
 
 
788
 
    /* Check if creating the server object succeeded */
789
 
    if (!server) {
790
 
        fprintf(stderr, "Failed to create server: %s\n",
 
976
    
 
977
    /* Allocate main Avahi loop object */
 
978
    mc.simple_poll = avahi_simple_poll_new();
 
979
    if (mc.simple_poll == NULL) {
 
980
        fprintf(stderr, "Avahi: Failed to create simple poll"
 
981
                " object.\n");
 
982
        exitcode = EXIT_FAILURE;
 
983
        goto end;
 
984
    }
 
985
 
 
986
    {
 
987
      AvahiServerConfig config;
 
988
      /* Do not publish any local Zeroconf records */
 
989
      avahi_server_config_init(&config);
 
990
      config.publish_hinfo = 0;
 
991
      config.publish_addresses = 0;
 
992
      config.publish_workstation = 0;
 
993
      config.publish_domain = 0;
 
994
 
 
995
      /* Allocate a new server */
 
996
      mc.server = avahi_server_new(avahi_simple_poll_get
 
997
                                   (mc.simple_poll), &config, NULL,
 
998
                                   NULL, &error);
 
999
    
 
1000
      /* Free the Avahi configuration data */
 
1001
      avahi_server_config_free(&config);
 
1002
    }
 
1003
    
 
1004
    /* Check if creating the Avahi server object succeeded */
 
1005
    if (mc.server == NULL) {
 
1006
        fprintf(stderr, "Failed to create Avahi server: %s\n",
791
1007
                avahi_strerror(error));
792
 
        returncode = EXIT_FAILURE;
793
 
        goto exit;
 
1008
        exitcode = EXIT_FAILURE;
 
1009
        goto end;
794
1010
    }
795
1011
    
796
 
    /* Create the service browser */
797
 
    sb = avahi_s_service_browser_new(server, if_index,
 
1012
    /* Create the Avahi service browser */
 
1013
    sb = avahi_s_service_browser_new(mc.server, if_index,
798
1014
                                     AVAHI_PROTO_INET6,
799
1015
                                     "_mandos._tcp", NULL, 0,
800
 
                                     browse_callback, server);
801
 
    if (!sb) {
 
1016
                                     browse_callback, &mc);
 
1017
    if (sb == NULL) {
802
1018
        fprintf(stderr, "Failed to create service browser: %s\n",
803
 
                avahi_strerror(avahi_server_errno(server)));
804
 
        returncode = EXIT_FAILURE;
805
 
        goto exit;
 
1019
                avahi_strerror(avahi_server_errno(mc.server)));
 
1020
        exitcode = EXIT_FAILURE;
 
1021
        goto end;
806
1022
    }
807
1023
    
808
1024
    /* Run the main loop */
809
1025
 
810
1026
    if (debug){
811
 
      fprintf(stderr, "Starting avahi loop search\n");
 
1027
      fprintf(stderr, "Starting Avahi loop search\n");
812
1028
    }
813
1029
    
814
 
    avahi_simple_poll_loop(simple_poll);
 
1030
    avahi_simple_poll_loop(mc.simple_poll);
815
1031
    
816
 
 exit:
 
1032
 end:
817
1033
 
818
1034
    if (debug){
819
1035
      fprintf(stderr, "%s exiting\n", argv[0]);
820
1036
    }
821
1037
    
822
1038
    /* Cleanup things */
823
 
    if (sb)
 
1039
    if (sb != NULL)
824
1040
        avahi_s_service_browser_free(sb);
825
1041
    
826
 
    if (server)
827
 
        avahi_server_free(server);
 
1042
    if (mc.server != NULL)
 
1043
        avahi_server_free(mc.server);
828
1044
 
829
 
    if (simple_poll)
830
 
        avahi_simple_poll_free(simple_poll);
 
1045
    if (mc.simple_poll != NULL)
 
1046
        avahi_simple_poll_free(mc.simple_poll);
831
1047
    free(pubkeyfile);
832
1048
    free(seckeyfile);
 
1049
 
 
1050
    if (gnutls_initalized){
 
1051
      gnutls_certificate_free_credentials(mc.cred);
 
1052
      gnutls_global_deinit ();
 
1053
    }
833
1054
    
834
 
    return returncode;
 
1055
    return exitcode;
835
1056
}