/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/mandos-client.c

  • Committer: Teddy Hogeborn
  • Date: 2008-09-21 04:22:50 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080921042250-r0qqjsbz2ulfo5le
* Makefile: Bug fix: fix syntax error.

* debian/control: Depend on "po-debconf".
  (mandos, mandos-client): Add "${misc:Depends}", used by
                           dh_installdebconf.

* debian/mandos-client.config: New; show note.
* debian/mandos-client.template: New.

* debian/mandos.README.Debian: New.

* debian/mandos.config: New; show note.
* debian/mandos.prerm: New; stop daemon.
* debian/mandos.template: New.

* debian/po/POTFILES.in: New.
* debian/po/sv.po: New.

* debian/rules (clean): Added "debconf-updatepo" as suggested by
                        po-debconf(7).
  (binary-common): Added "dh_installdebconf" to use "debian/*.config"
                   and "debian/*.template" files.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/*  -*- coding: utf-8 -*- */
2
2
/*
3
 
 * Mandos-client - get and decrypt data from a Mandos server
 
3
 * Mandos client - get and decrypt data from a Mandos server
4
4
 *
5
5
 * This program is partly derived from an example program for an Avahi
6
6
 * service browser, downloaded from
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008,2009 Teddy Hogeborn
13
 
 * Copyright © 2008,2009 Björn Påhlsson
 
12
 * Copyright © 2007-2008 Teddy Hogeborn & Björn Påhlsson
14
13
 * 
15
14
 * This program is free software: you can redistribute it and/or
16
15
 * modify it under the terms of the GNU General Public License as
36
35
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
37
36
 
38
37
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
39
 
                                   stdout, ferror(), sscanf(),
40
 
                                   remove() */
 
38
                                   stdout, ferror() */
41
39
#include <stdint.h>             /* uint16_t, uint32_t */
42
40
#include <stddef.h>             /* NULL, size_t, ssize_t */
43
41
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
49
47
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
50
48
                                   sockaddr_in6, PF_INET6,
51
49
                                   SOCK_STREAM, INET6_ADDRSTRLEN,
52
 
                                   uid_t, gid_t, open(), opendir(),
53
 
                                   DIR */
 
50
                                   uid_t, gid_t, open(), opendir(), DIR */
54
51
#include <sys/stat.h>           /* open() */
55
52
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
56
53
                                   struct in6_addr, inet_pton(),
57
54
                                   connect() */
58
55
#include <fcntl.h>              /* open() */
59
 
#include <dirent.h>             /* opendir(), struct dirent, readdir()
60
 
                                 */
61
 
#include <inttypes.h>           /* PRIu16, intmax_t, SCNdMAX */
 
56
#include <dirent.h>             /* opendir(), struct dirent, readdir() */
 
57
#include <inttypes.h>           /* PRIu16 */
62
58
#include <assert.h>             /* assert() */
63
59
#include <errno.h>              /* perror(), errno */
64
60
#include <time.h>               /* time() */
70
66
                                   getuid(), getgid(), setuid(),
71
67
                                   setgid() */
72
68
#include <arpa/inet.h>          /* inet_pton(), htons */
73
 
#include <iso646.h>             /* not, and, or */
 
69
#include <iso646.h>             /* not, and */
74
70
#include <argp.h>               /* struct argp_option, error_t, struct
75
71
                                   argp_state, struct argp,
76
72
                                   argp_parse(), ARGP_KEY_ARG,
93
89
                                   gnutls_*
94
90
                                   init_gnutls_session(),
95
91
                                   GNUTLS_* */
96
 
#include <gnutls/openpgp.h>
97
 
                          /* gnutls_certificate_set_openpgp_key_file(),
 
92
#include <gnutls/openpgp.h>     /* gnutls_certificate_set_openpgp_key_file(),
98
93
                                   GNUTLS_OPENPGP_FMT_BASE64 */
99
94
 
100
95
/* GPGME */
106
101
 
107
102
#define BUFFER_SIZE 256
108
103
 
 
104
/*
 
105
  #define PATHDIR "/conf/conf.d/mandos"
 
106
*/
 
107
 
109
108
#define PATHDIR "/conf/conf.d/mandos"
110
109
#define SECKEY "seckey.txt"
111
110
#define PUBKEY "pubkey.txt"
112
111
 
113
112
bool debug = false;
114
113
static const char mandos_protocol_version[] = "1";
115
 
const char *argp_program_version = "mandos-client " VERSION;
 
114
const char *argp_program_version = "mandos-client 1.0";
116
115
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
117
116
 
118
117
/* Used for passing in values through the Avahi callback functions */
133
132
 */
134
133
size_t adjustbuffer(char **buffer, size_t buffer_length,
135
134
                  size_t buffer_capacity){
136
 
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
 
135
  if (buffer_length + BUFFER_SIZE > buffer_capacity){
137
136
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
138
 
    if(buffer == NULL){
 
137
    if (buffer == NULL){
139
138
      return 0;
140
139
    }
141
140
    buffer_capacity += BUFFER_SIZE;
154
153
  
155
154
  
156
155
  /*
157
 
   * Helper function to insert pub and seckey to the engine keyring.
 
156
   * Helper function to insert pub and seckey to the enigne keyring.
158
157
   */
159
158
  bool import_key(const char *filename){
160
159
    int fd;
161
160
    gpgme_data_t pgp_data;
162
161
    
163
 
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
 
162
    fd = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
164
163
    if(fd == -1){
165
164
      perror("open");
166
165
      return false;
167
166
    }
168
167
    
169
168
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
170
 
    if(rc != GPG_ERR_NO_ERROR){
 
169
    if (rc != GPG_ERR_NO_ERROR){
171
170
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
172
171
              gpgme_strsource(rc), gpgme_strerror(rc));
173
172
      return false;
174
173
    }
175
174
    
176
175
    rc = gpgme_op_import(mc->ctx, pgp_data);
177
 
    if(rc != GPG_ERR_NO_ERROR){
 
176
    if (rc != GPG_ERR_NO_ERROR){
178
177
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
179
178
              gpgme_strsource(rc), gpgme_strerror(rc));
180
179
      return false;
181
180
    }
182
181
    
183
 
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
 
182
    ret = TEMP_FAILURE_RETRY(close(fd));
184
183
    if(ret == -1){
185
184
      perror("close");
186
185
    }
188
187
    return true;
189
188
  }
190
189
  
191
 
  if(debug){
 
190
  if (debug){
192
191
    fprintf(stderr, "Initialize gpgme\n");
193
192
  }
194
193
  
195
194
  /* Init GPGME */
196
195
  gpgme_check_version(NULL);
197
196
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
198
 
  if(rc != GPG_ERR_NO_ERROR){
 
197
  if (rc != GPG_ERR_NO_ERROR){
199
198
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
200
199
            gpgme_strsource(rc), gpgme_strerror(rc));
201
200
    return false;
202
201
  }
203
202
  
204
203
    /* Set GPGME home directory for the OpenPGP engine only */
205
 
  rc = gpgme_get_engine_info(&engine_info);
206
 
  if(rc != GPG_ERR_NO_ERROR){
 
204
  rc = gpgme_get_engine_info (&engine_info);
 
205
  if (rc != GPG_ERR_NO_ERROR){
207
206
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
208
207
            gpgme_strsource(rc), gpgme_strerror(rc));
209
208
    return false;
223
222
  
224
223
  /* Create new GPGME "context" */
225
224
  rc = gpgme_new(&(mc->ctx));
226
 
  if(rc != GPG_ERR_NO_ERROR){
 
225
  if (rc != GPG_ERR_NO_ERROR){
227
226
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
228
227
            gpgme_strsource(rc), gpgme_strerror(rc));
229
228
    return false;
230
229
  }
231
230
  
232
 
  if(not import_key(pubkey) or not import_key(seckey)){
 
231
  if (not import_key(pubkey) or not import_key(seckey)){
233
232
    return false;
234
233
  }
235
234
  
240
239
 * Decrypt OpenPGP data.
241
240
 * Returns -1 on error
242
241
 */
243
 
static ssize_t pgp_packet_decrypt(const mandos_context *mc,
244
 
                                  const char *cryptotext,
245
 
                                  size_t crypto_size,
246
 
                                  char **plaintext){
 
242
static ssize_t pgp_packet_decrypt (const mandos_context *mc,
 
243
                                   const char *cryptotext,
 
244
                                   size_t crypto_size,
 
245
                                   char **plaintext){
247
246
  gpgme_data_t dh_crypto, dh_plain;
248
247
  gpgme_error_t rc;
249
248
  ssize_t ret;
250
249
  size_t plaintext_capacity = 0;
251
250
  ssize_t plaintext_length = 0;
252
251
  
253
 
  if(debug){
 
252
  if (debug){
254
253
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
255
254
  }
256
255
  
257
256
  /* Create new GPGME data buffer from memory cryptotext */
258
257
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
259
258
                               0);
260
 
  if(rc != GPG_ERR_NO_ERROR){
 
259
  if (rc != GPG_ERR_NO_ERROR){
261
260
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
262
261
            gpgme_strsource(rc), gpgme_strerror(rc));
263
262
    return -1;
265
264
  
266
265
  /* Create new empty GPGME data buffer for the plaintext */
267
266
  rc = gpgme_data_new(&dh_plain);
268
 
  if(rc != GPG_ERR_NO_ERROR){
 
267
  if (rc != GPG_ERR_NO_ERROR){
269
268
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
270
269
            gpgme_strsource(rc), gpgme_strerror(rc));
271
270
    gpgme_data_release(dh_crypto);
275
274
  /* Decrypt data from the cryptotext data buffer to the plaintext
276
275
     data buffer */
277
276
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
278
 
  if(rc != GPG_ERR_NO_ERROR){
 
277
  if (rc != GPG_ERR_NO_ERROR){
279
278
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
280
279
            gpgme_strsource(rc), gpgme_strerror(rc));
281
280
    plaintext_length = -1;
282
 
    if(debug){
 
281
    if (debug){
283
282
      gpgme_decrypt_result_t result;
284
283
      result = gpgme_op_decrypt_result(mc->ctx);
285
 
      if(result == NULL){
 
284
      if (result == NULL){
286
285
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
287
286
      } else {
288
287
        fprintf(stderr, "Unsupported algorithm: %s\n",
315
314
  }
316
315
  
317
316
  /* Seek back to the beginning of the GPGME plaintext data buffer */
318
 
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
 
317
  if (gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET) == -1){
319
318
    perror("gpgme_data_seek");
320
319
    plaintext_length = -1;
321
320
    goto decrypt_end;
326
325
    plaintext_capacity = adjustbuffer(plaintext,
327
326
                                      (size_t)plaintext_length,
328
327
                                      plaintext_capacity);
329
 
    if(plaintext_capacity == 0){
 
328
    if (plaintext_capacity == 0){
330
329
        perror("adjustbuffer");
331
330
        plaintext_length = -1;
332
331
        goto decrypt_end;
335
334
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
336
335
                          BUFFER_SIZE);
337
336
    /* Print the data, if any */
338
 
    if(ret == 0){
 
337
    if (ret == 0){
339
338
      /* EOF */
340
339
      break;
341
340
    }
365
364
  return plaintext_length;
366
365
}
367
366
 
368
 
static const char * safer_gnutls_strerror(int value) {
369
 
  const char *ret = gnutls_strerror(value); /* Spurious warning from
370
 
                                               -Wunreachable-code */
371
 
  if(ret == NULL)
 
367
static const char * safer_gnutls_strerror (int value) {
 
368
  const char *ret = gnutls_strerror (value); /* Spurious warning */
 
369
  if (ret == NULL)
372
370
    ret = "(unknown)";
373
371
  return ret;
374
372
}
389
387
  }
390
388
  
391
389
  ret = gnutls_global_init();
392
 
  if(ret != GNUTLS_E_SUCCESS) {
393
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
394
 
            safer_gnutls_strerror(ret));
 
390
  if (ret != GNUTLS_E_SUCCESS) {
 
391
    fprintf (stderr, "GnuTLS global_init: %s\n",
 
392
             safer_gnutls_strerror(ret));
395
393
    return -1;
396
394
  }
397
395
  
398
 
  if(debug){
 
396
  if (debug){
399
397
    /* "Use a log level over 10 to enable all debugging options."
400
398
     * - GnuTLS manual
401
399
     */
405
403
  
406
404
  /* OpenPGP credentials */
407
405
  gnutls_certificate_allocate_credentials(&mc->cred);
408
 
  if(ret != GNUTLS_E_SUCCESS){
409
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
410
 
                                                  * from
411
 
                                                  * -Wunreachable-code
412
 
                                                  */
413
 
            safer_gnutls_strerror(ret));
414
 
    gnutls_global_deinit();
 
406
  if (ret != GNUTLS_E_SUCCESS){
 
407
    fprintf (stderr, "GnuTLS memory error: %s\n", /* Spurious
 
408
                                                     warning */
 
409
             safer_gnutls_strerror(ret));
 
410
    gnutls_global_deinit ();
415
411
    return -1;
416
412
  }
417
413
  
424
420
  ret = gnutls_certificate_set_openpgp_key_file
425
421
    (mc->cred, pubkeyfilename, seckeyfilename,
426
422
     GNUTLS_OPENPGP_FMT_BASE64);
427
 
  if(ret != GNUTLS_E_SUCCESS) {
 
423
  if (ret != GNUTLS_E_SUCCESS) {
428
424
    fprintf(stderr,
429
425
            "Error[%d] while reading the OpenPGP key pair ('%s',"
430
426
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
435
431
  
436
432
  /* GnuTLS server initialization */
437
433
  ret = gnutls_dh_params_init(&mc->dh_params);
438
 
  if(ret != GNUTLS_E_SUCCESS) {
439
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
440
 
            " %s\n", safer_gnutls_strerror(ret));
 
434
  if (ret != GNUTLS_E_SUCCESS) {
 
435
    fprintf (stderr, "Error in GnuTLS DH parameter initialization:"
 
436
             " %s\n", safer_gnutls_strerror(ret));
441
437
    goto globalfail;
442
438
  }
443
439
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
444
 
  if(ret != GNUTLS_E_SUCCESS) {
445
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
446
 
            safer_gnutls_strerror(ret));
 
440
  if (ret != GNUTLS_E_SUCCESS) {
 
441
    fprintf (stderr, "Error in GnuTLS prime generation: %s\n",
 
442
             safer_gnutls_strerror(ret));
447
443
    goto globalfail;
448
444
  }
449
445
  
464
460
  int ret;
465
461
  /* GnuTLS session creation */
466
462
  ret = gnutls_init(session, GNUTLS_SERVER);
467
 
  if(ret != GNUTLS_E_SUCCESS){
 
463
  if (ret != GNUTLS_E_SUCCESS){
468
464
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
469
465
            safer_gnutls_strerror(ret));
470
466
  }
472
468
  {
473
469
    const char *err;
474
470
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
475
 
    if(ret != GNUTLS_E_SUCCESS) {
 
471
    if (ret != GNUTLS_E_SUCCESS) {
476
472
      fprintf(stderr, "Syntax error at: %s\n", err);
477
473
      fprintf(stderr, "GnuTLS error: %s\n",
478
474
              safer_gnutls_strerror(ret));
479
 
      gnutls_deinit(*session);
 
475
      gnutls_deinit (*session);
480
476
      return -1;
481
477
    }
482
478
  }
483
479
  
484
480
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
485
481
                               mc->cred);
486
 
  if(ret != GNUTLS_E_SUCCESS) {
 
482
  if (ret != GNUTLS_E_SUCCESS) {
487
483
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
488
484
            safer_gnutls_strerror(ret));
489
 
    gnutls_deinit(*session);
 
485
    gnutls_deinit (*session);
490
486
    return -1;
491
487
  }
492
488
  
493
489
  /* ignore client certificate if any. */
494
 
  gnutls_certificate_server_set_request(*session,
495
 
                                        GNUTLS_CERT_IGNORE);
 
490
  gnutls_certificate_server_set_request (*session,
 
491
                                         GNUTLS_CERT_IGNORE);
496
492
  
497
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
493
  gnutls_dh_set_prime_bits (*session, mc->dh_bits);
498
494
  
499
495
  return 0;
500
496
}
508
504
                                      AvahiIfIndex if_index,
509
505
                                      mandos_context *mc){
510
506
  int ret, tcp_sd;
511
 
  ssize_t sret;
512
507
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
513
508
  char *buffer = NULL;
514
509
  char *decrypted_buffer;
520
515
  char interface[IF_NAMESIZE];
521
516
  gnutls_session_t session;
522
517
  
523
 
  ret = init_gnutls_session(mc, &session);
524
 
  if(ret != 0){
 
518
  ret = init_gnutls_session (mc, &session);
 
519
  if (ret != 0){
525
520
    return -1;
526
521
  }
527
522
  
549
544
  /* It would be nice to have a way to detect if we were passed an
550
545
     IPv4 address here.   Now we assume an IPv6 address. */
551
546
  ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
552
 
  if(ret < 0 ){
 
547
  if (ret < 0 ){
553
548
    perror("inet_pton");
554
549
    return -1;
555
550
  }
557
552
    fprintf(stderr, "Bad address: %s\n", ip);
558
553
    return -1;
559
554
  }
560
 
  to.in6.sin6_port = htons(port); /* Spurious warnings from
561
 
                                     -Wconversion and
562
 
                                     -Wunreachable-code */
 
555
  to.in6.sin6_port = htons(port); /* Spurious warning */
563
556
  
564
557
  to.in6.sin6_scope_id = (uint32_t)if_index;
565
558
  
578
571
  }
579
572
  
580
573
  ret = connect(tcp_sd, &to.in, sizeof(to));
581
 
  if(ret < 0){
 
574
  if (ret < 0){
582
575
    perror("connect");
583
576
    return -1;
584
577
  }
585
578
  
586
579
  const char *out = mandos_protocol_version;
587
580
  written = 0;
588
 
  while(true){
 
581
  while (true){
589
582
    size_t out_size = strlen(out);
590
 
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
 
583
    ret = TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
591
584
                                   out_size - written));
592
 
    if(ret == -1){
 
585
    if (ret == -1){
593
586
      perror("write");
594
587
      retval = -1;
595
588
      goto mandos_end;
598
591
    if(written < out_size){
599
592
      continue;
600
593
    } else {
601
 
      if(out == mandos_protocol_version){
 
594
      if (out == mandos_protocol_version){
602
595
        written = 0;
603
596
        out = "\r\n";
604
597
      } else {
611
604
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
612
605
  }
613
606
  
614
 
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
 
607
  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) tcp_sd);
615
608
  
616
609
  do{
617
 
    ret = gnutls_handshake(session);
 
610
    ret = gnutls_handshake (session);
618
611
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
619
612
  
620
 
  if(ret != GNUTLS_E_SUCCESS){
 
613
  if (ret != GNUTLS_E_SUCCESS){
621
614
    if(debug){
622
615
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
623
 
      gnutls_perror(ret);
 
616
      gnutls_perror (ret);
624
617
    }
625
618
    retval = -1;
626
619
    goto mandos_end;
636
629
  while(true){
637
630
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
638
631
                                   buffer_capacity);
639
 
    if(buffer_capacity == 0){
 
632
    if (buffer_capacity == 0){
640
633
      perror("adjustbuffer");
641
634
      retval = -1;
642
635
      goto mandos_end;
643
636
    }
644
637
    
645
 
    sret = gnutls_record_recv(session, buffer+buffer_length,
646
 
                              BUFFER_SIZE);
647
 
    if(sret == 0){
 
638
    ret = gnutls_record_recv(session, buffer+buffer_length,
 
639
                             BUFFER_SIZE);
 
640
    if (ret == 0){
648
641
      break;
649
642
    }
650
 
    if(sret < 0){
651
 
      switch(sret){
 
643
    if (ret < 0){
 
644
      switch(ret){
652
645
      case GNUTLS_E_INTERRUPTED:
653
646
      case GNUTLS_E_AGAIN:
654
647
        break;
655
648
      case GNUTLS_E_REHANDSHAKE:
656
649
        do{
657
 
          ret = gnutls_handshake(session);
 
650
          ret = gnutls_handshake (session);
658
651
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
659
 
        if(ret < 0){
 
652
        if (ret < 0){
660
653
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
661
 
          gnutls_perror(ret);
 
654
          gnutls_perror (ret);
662
655
          retval = -1;
663
656
          goto mandos_end;
664
657
        }
667
660
        fprintf(stderr, "Unknown error while reading data from"
668
661
                " encrypted session with Mandos server\n");
669
662
        retval = -1;
670
 
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
663
        gnutls_bye (session, GNUTLS_SHUT_RDWR);
671
664
        goto mandos_end;
672
665
      }
673
666
    } else {
674
 
      buffer_length += (size_t) sret;
 
667
      buffer_length += (size_t) ret;
675
668
    }
676
669
  }
677
670
  
679
672
    fprintf(stderr, "Closing TLS session\n");
680
673
  }
681
674
  
682
 
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
675
  gnutls_bye (session, GNUTLS_SHUT_RDWR);
683
676
  
684
 
  if(buffer_length > 0){
 
677
  if (buffer_length > 0){
685
678
    decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
686
679
                                               buffer_length,
687
680
                                               &decrypted_buffer);
688
 
    if(decrypted_buffer_size >= 0){
 
681
    if (decrypted_buffer_size >= 0){
689
682
      written = 0;
690
683
      while(written < (size_t) decrypted_buffer_size){
691
 
        ret = (int)fwrite(decrypted_buffer + written, 1,
692
 
                          (size_t)decrypted_buffer_size - written,
693
 
                          stdout);
 
684
        ret = (int)fwrite (decrypted_buffer + written, 1,
 
685
                           (size_t)decrypted_buffer_size - written,
 
686
                           stdout);
694
687
        if(ret == 0 and ferror(stdout)){
695
688
          if(debug){
696
689
            fprintf(stderr, "Error writing encrypted data: %s\n",
713
706
  
714
707
 mandos_end:
715
708
  free(buffer);
716
 
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
709
  ret = TEMP_FAILURE_RETRY(close(tcp_sd));
717
710
  if(ret == -1){
718
711
    perror("close");
719
712
  }
720
 
  gnutls_deinit(session);
 
713
  gnutls_deinit (session);
721
714
  return retval;
722
715
}
723
716
 
741
734
  /* Called whenever a service has been resolved successfully or
742
735
     timed out */
743
736
  
744
 
  switch(event) {
 
737
  switch (event) {
745
738
  default:
746
739
  case AVAHI_RESOLVER_FAILURE:
747
740
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
755
748
      avahi_address_snprint(ip, sizeof(ip), address);
756
749
      if(debug){
757
750
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
758
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
759
 
                ip, (intmax_t)interface, port);
 
751
                PRIu16 ") on port %d\n", name, host_name, ip,
 
752
                interface, port);
760
753
      }
761
754
      int ret = start_mandos_communication(ip, port, interface, mc);
762
 
      if(ret == 0){
 
755
      if (ret == 0){
763
756
        avahi_simple_poll_quit(mc->simple_poll);
764
757
      }
765
758
    }
783
776
  /* Called whenever a new services becomes available on the LAN or
784
777
     is removed from the LAN */
785
778
  
786
 
  switch(event) {
 
779
  switch (event) {
787
780
  default:
788
781
  case AVAHI_BROWSER_FAILURE:
789
782
    
798
791
       the callback function is called the Avahi server will free the
799
792
       resolver for us. */
800
793
    
801
 
    if(!(avahi_s_service_resolver_new(mc->server, interface,
 
794
    if (!(avahi_s_service_resolver_new(mc->server, interface,
802
795
                                       protocol, name, type, domain,
803
796
                                       AVAHI_PROTO_INET6, 0,
804
797
                                       resolve_callback, mc)))
822
815
    AvahiSServiceBrowser *sb = NULL;
823
816
    int error;
824
817
    int ret;
825
 
    intmax_t tmpmax;
826
 
    int numchars;
827
818
    int exitcode = EXIT_SUCCESS;
828
819
    const char *interface = "eth0";
829
820
    struct ifreq network;
832
823
    gid_t gid;
833
824
    char *connect_to = NULL;
834
825
    char tempdir[] = "/tmp/mandosXXXXXX";
835
 
    bool tempdir_created = false;
836
826
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
837
827
    const char *seckey = PATHDIR "/" SECKEY;
838
828
    const char *pubkey = PATHDIR "/" PUBKEY;
840
830
    mandos_context mc = { .simple_poll = NULL, .server = NULL,
841
831
                          .dh_bits = 1024, .priority = "SECURE256"
842
832
                          ":!CTYPE-X.509:+CTYPE-OPENPGP" };
843
 
    bool gnutls_initialized = false;
844
 
    bool gpgme_initialized = false;
 
833
    bool gnutls_initalized = false;
 
834
    bool gpgme_initalized = false;
845
835
    
846
836
    {
847
837
      struct argp_option options[] = {
876
866
        { .name = NULL }
877
867
      };
878
868
      
879
 
      error_t parse_opt(int key, char *arg,
880
 
                        struct argp_state *state) {
881
 
        switch(key) {
 
869
      error_t parse_opt (int key, char *arg,
 
870
                         struct argp_state *state) {
 
871
        /* Get the INPUT argument from `argp_parse', which we know is
 
872
           a pointer to our plugin list pointer. */
 
873
        switch (key) {
882
874
        case 128:               /* --debug */
883
875
          debug = true;
884
876
          break;
895
887
          pubkey = arg;
896
888
          break;
897
889
        case 129:               /* --dh-bits */
898
 
          ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
899
 
          if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
900
 
             or arg[numchars] != '\0'){
901
 
            fprintf(stderr, "Bad number of DH bits\n");
 
890
          errno = 0;
 
891
          mc.dh_bits = (unsigned int) strtol(arg, NULL, 10);
 
892
          if (errno){
 
893
            perror("strtol");
902
894
            exit(EXIT_FAILURE);
903
895
          }
904
 
          mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
905
896
          break;
906
897
        case 130:               /* --priority */
907
898
          mc.priority = arg;
908
899
          break;
909
900
        case ARGP_KEY_ARG:
910
 
          argp_usage(state);
 
901
          argp_usage (state);
911
902
        case ARGP_KEY_END:
912
903
          break;
913
904
        default:
920
911
                           .args_doc = "",
921
912
                           .doc = "Mandos client -- Get and decrypt"
922
913
                           " passwords from a Mandos server" };
923
 
      ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
924
 
      if(ret == ARGP_ERR_UNKNOWN){
 
914
      ret = argp_parse (&argp, argc, argv, 0, 0, NULL);
 
915
      if (ret == ARGP_ERR_UNKNOWN){
925
916
        fprintf(stderr, "Unknown error while parsing arguments\n");
926
917
        exitcode = EXIT_FAILURE;
927
918
        goto end;
952
943
          goto end;
953
944
        }
954
945
      }
955
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
946
      ret = TEMP_FAILURE_RETRY(close(sd));
956
947
      if(ret == -1){
957
948
        perror("close");
958
949
      }
962
953
    gid = getgid();
963
954
    
964
955
    ret = setuid(uid);
965
 
    if(ret == -1){
 
956
    if (ret == -1){
966
957
      perror("setuid");
967
958
    }
968
959
    
969
960
    setgid(gid);
970
 
    if(ret == -1){
 
961
    if (ret == -1){
971
962
      perror("setgid");
972
963
    }
973
964
    
974
965
    ret = init_gnutls_global(&mc, pubkey, seckey);
975
 
    if(ret == -1){
 
966
    if (ret == -1){
976
967
      fprintf(stderr, "init_gnutls_global failed\n");
977
968
      exitcode = EXIT_FAILURE;
978
969
      goto end;
979
970
    } else {
980
 
      gnutls_initialized = true;
 
971
      gnutls_initalized = true;
981
972
    }
982
973
    
983
974
    if(mkdtemp(tempdir) == NULL){
984
975
      perror("mkdtemp");
 
976
      tempdir[0] = '\0';
985
977
      goto end;
986
978
    }
987
 
    tempdir_created = true;
988
979
    
989
980
    if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
990
 
      fprintf(stderr, "init_gpgme failed\n");
 
981
      fprintf(stderr, "gpgme_initalized failed\n");
991
982
      exitcode = EXIT_FAILURE;
992
983
      goto end;
993
984
    } else {
994
 
      gpgme_initialized = true;
 
985
      gpgme_initalized = true;
995
986
    }
996
987
    
997
988
    if_index = (AvahiIfIndex) if_nametoindex(interface);
998
989
    if(if_index == 0){
999
990
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1000
 
      exitcode = EXIT_FAILURE;
1001
 
      goto end;
 
991
      exit(EXIT_FAILURE);
1002
992
    }
1003
993
    
1004
994
    if(connect_to != NULL){
1010
1000
        exitcode = EXIT_FAILURE;
1011
1001
        goto end;
1012
1002
      }
1013
 
      uint16_t port;
1014
 
      ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
1015
 
      if(ret < 1 or tmpmax != (uint16_t)tmpmax
1016
 
         or address[numchars+1] != '\0'){
1017
 
        fprintf(stderr, "Bad port number\n");
 
1003
      errno = 0;
 
1004
      uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
 
1005
      if(errno){
 
1006
        perror("Bad port number");
1018
1007
        exitcode = EXIT_FAILURE;
1019
1008
        goto end;
1020
1009
      }
1021
 
      port = (uint16_t)tmpmax;
1022
1010
      *address = '\0';
1023
1011
      address = connect_to;
1024
1012
      ret = start_mandos_communication(address, port, if_index, &mc);
1030
1018
      goto end;
1031
1019
    }
1032
1020
    
1033
 
    if(not debug){
 
1021
    if (not debug){
1034
1022
      avahi_set_log_function(empty_log);
1035
1023
    }
1036
1024
    
1039
1027
    
1040
1028
    /* Allocate main Avahi loop object */
1041
1029
    mc.simple_poll = avahi_simple_poll_new();
1042
 
    if(mc.simple_poll == NULL) {
 
1030
    if (mc.simple_poll == NULL) {
1043
1031
        fprintf(stderr, "Avahi: Failed to create simple poll"
1044
1032
                " object.\n");
1045
1033
        exitcode = EXIT_FAILURE;
1065
1053
    }
1066
1054
    
1067
1055
    /* Check if creating the Avahi server object succeeded */
1068
 
    if(mc.server == NULL) {
 
1056
    if (mc.server == NULL) {
1069
1057
        fprintf(stderr, "Failed to create Avahi server: %s\n",
1070
1058
                avahi_strerror(error));
1071
1059
        exitcode = EXIT_FAILURE;
1077
1065
                                     AVAHI_PROTO_INET6,
1078
1066
                                     "_mandos._tcp", NULL, 0,
1079
1067
                                     browse_callback, &mc);
1080
 
    if(sb == NULL) {
 
1068
    if (sb == NULL) {
1081
1069
        fprintf(stderr, "Failed to create service browser: %s\n",
1082
1070
                avahi_strerror(avahi_server_errno(mc.server)));
1083
1071
        exitcode = EXIT_FAILURE;
1086
1074
    
1087
1075
    /* Run the main loop */
1088
1076
    
1089
 
    if(debug){
 
1077
    if (debug){
1090
1078
      fprintf(stderr, "Starting Avahi loop search\n");
1091
1079
    }
1092
1080
    
1094
1082
    
1095
1083
 end:
1096
1084
    
1097
 
    if(debug){
 
1085
    if (debug){
1098
1086
      fprintf(stderr, "%s exiting\n", argv[0]);
1099
1087
    }
1100
1088
    
1101
1089
    /* Cleanup things */
1102
 
    if(sb != NULL)
 
1090
    if (sb != NULL)
1103
1091
        avahi_s_service_browser_free(sb);
1104
1092
    
1105
 
    if(mc.server != NULL)
 
1093
    if (mc.server != NULL)
1106
1094
        avahi_server_free(mc.server);
1107
1095
    
1108
 
    if(mc.simple_poll != NULL)
 
1096
    if (mc.simple_poll != NULL)
1109
1097
        avahi_simple_poll_free(mc.simple_poll);
1110
1098
    
1111
 
    if(gnutls_initialized){
 
1099
    if (gnutls_initalized){
1112
1100
      gnutls_certificate_free_credentials(mc.cred);
1113
 
      gnutls_global_deinit();
 
1101
      gnutls_global_deinit ();
1114
1102
      gnutls_dh_params_deinit(mc.dh_params);
1115
1103
    }
1116
1104
    
1117
 
    if(gpgme_initialized){
 
1105
    if(gpgme_initalized){
1118
1106
      gpgme_release(mc.ctx);
1119
1107
    }
1120
1108
    
1121
1109
    /* Removes the temp directory used by GPGME */
1122
 
    if(tempdir_created){
 
1110
    if(tempdir[0] != '\0'){
1123
1111
      DIR *d;
1124
1112
      struct dirent *direntry;
1125
1113
      d = opendir(tempdir);
1126
1114
      if(d == NULL){
1127
 
        if(errno != ENOENT){
1128
 
          perror("opendir");
1129
 
        }
 
1115
        perror("opendir");
1130
1116
      } else {
1131
1117
        while(true){
1132
1118
          direntry = readdir(d);
1133
1119
          if(direntry == NULL){
1134
1120
            break;
1135
1121
          }
1136
 
          /* Skip "." and ".." */
1137
 
          if(direntry->d_name[0] == '.'
1138
 
             and (direntry->d_name[1] == '\0'
1139
 
                  or (direntry->d_name[1] == '.'
1140
 
                      and direntry->d_name[2] == '\0'))){
1141
 
            continue;
1142
 
          }
1143
 
          char *fullname = NULL;
1144
 
          ret = asprintf(&fullname, "%s/%s", tempdir,
1145
 
                         direntry->d_name);
1146
 
          if(ret < 0){
1147
 
            perror("asprintf");
1148
 
            continue;
1149
 
          }
1150
 
          ret = remove(fullname);
1151
 
          if(ret == -1){
1152
 
            fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1153
 
                    strerror(errno));
1154
 
          }
1155
 
          free(fullname);
 
1122
          if (direntry->d_type == DT_REG){
 
1123
            char *fullname = NULL;
 
1124
            ret = asprintf(&fullname, "%s/%s", tempdir,
 
1125
                           direntry->d_name);
 
1126
            if(ret < 0){
 
1127
              perror("asprintf");
 
1128
              continue;
 
1129
            }
 
1130
            ret = unlink(fullname);
 
1131
            if(ret == -1){
 
1132
              fprintf(stderr, "unlink(\"%s\"): %s",
 
1133
                      fullname, strerror(errno));
 
1134
            }
 
1135
            free(fullname);
 
1136
          }
1156
1137
        }
1157
1138
        closedir(d);
1158
1139
      }
1159
1140
      ret = rmdir(tempdir);
1160
 
      if(ret == -1 and errno != ENOENT){
 
1141
      if(ret == -1){
1161
1142
        perror("rmdir");
1162
1143
      }
1163
1144
    }
1164
 
    
 
1145
          
1165
1146
    return exitcode;
1166
1147
}