/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

  • Committer: Teddy Hogeborn
  • Date: 2008-08-03 01:09:36 UTC
  • mfrom: (24.1.9 mandos)
  • Revision ID: teddy@fukt.bsnet.se-20080803010936-ujme8tgxceszfbi1
* plugbasedclient.c (main): New "--userid" and "--groupid" options.
                            Take an additional non-option argument and
                            parse it as a plus-separated and -prefixed
                            list of additional options.

* plugins.d/mandosclient.c (DH_BITS): Replaced with
                                      "mandos_context.dh_bits".  All
                                      users changed.
  (certdir): Renamed to "keydir".  All users changed.
  (certfile): Renamed to "pubkeyfile".  All users changed.
  (certkey): Renamed to "seckeyfile".  All users changed.
  (encrypted_session): Replaced with "mandos_context".  All users
                       changed.
  (initgnutls): Take additional "session" and "dh_params" arguments.
                All callers changed.
  (start_mandos_communication): Take additional "mc" argument.  All
                                callers changed.  Print target IPv6
                                address if different than supplied
                                string.
  (simple_poll) Replaced with "mandos_context.simple_poll".  All users
                changed.
  (server): Replaced with "mandos_context.server".  All users changed.
  (main): Default interface to "eth0".  Rename "--certdir" to
          "--keydir", "--certkey" to "--seckey", and "--certfile" to
          "--pubkey".  New options "--dh-bits" and "--priority".  If
          the interface is not up, bring it up.

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