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

  • Committer: Björn Påhlsson
  • Date: 2008-08-02 21:06:29 UTC
  • mto: (237.7.1 mandos) (24.1.154 mandos)
  • mto: This revision was merged to the branch mainline in revision 38.
  • Revision ID: belorn@braxen-20080802210629-p9jc5515yufcg4ge
not working midwork...

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
33
32
#define _LARGEFILE_SOURCE
34
33
#define _FILE_OFFSET_BITS 64
35
34
 
36
 
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
37
 
 
38
 
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
39
 
                                   stdout, ferror(), sscanf(),
40
 
                                   remove() */
41
 
#include <stdint.h>             /* uint16_t, uint32_t */
42
 
#include <stddef.h>             /* NULL, size_t, ssize_t */
43
 
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
44
 
                                   srand() */
45
 
#include <stdbool.h>            /* bool, false, true */
46
 
#include <string.h>             /* memset(), strcmp(), strlen(),
47
 
                                   strerror(), asprintf(), strcpy() */
48
 
#include <sys/ioctl.h>          /* ioctl */
49
 
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
50
 
                                   sockaddr_in6, PF_INET6,
51
 
                                   SOCK_STREAM, uid_t, gid_t, open(),
52
 
                                   opendir(), DIR */
53
 
#include <sys/stat.h>           /* open() */
54
 
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
55
 
                                   inet_pton(), connect() */
56
 
#include <fcntl.h>              /* open() */
57
 
#include <dirent.h>             /* opendir(), struct dirent, readdir()
58
 
                                 */
59
 
#include <inttypes.h>           /* PRIu16, intmax_t, SCNdMAX */
60
 
#include <assert.h>             /* assert() */
61
 
#include <errno.h>              /* perror(), errno */
62
 
#include <time.h>               /* nanosleep(), time() */
63
 
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
64
 
                                   SIOCSIFFLAGS, if_indextoname(),
65
 
                                   if_nametoindex(), IF_NAMESIZE */
66
 
#include <netinet/in.h>         /* IN6_IS_ADDR_LINKLOCAL,
67
 
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
68
 
                                */
69
 
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
70
 
                                   getuid(), getgid(), setuid(),
71
 
                                   setgid() */
72
 
#include <arpa/inet.h>          /* inet_pton(), htons */
73
 
#include <iso646.h>             /* not, or, and */
74
 
#include <argp.h>               /* struct argp_option, error_t, struct
75
 
                                   argp_state, struct argp,
76
 
                                   argp_parse(), ARGP_KEY_ARG,
77
 
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
78
 
#include <signal.h>             /* sigemptyset(), sigaddset(),
79
 
                                   sigaction(), SIGTERM, sigaction,
80
 
                                   sig_atomic_t */
81
 
 
82
 
#ifdef __linux__
83
 
#include <sys/klog.h>           /* klogctl() */
84
 
#endif  /* __linux__ */
85
 
 
86
 
/* Avahi */
87
 
/* All Avahi types, constants and functions
88
 
 Avahi*, avahi_*,
89
 
 AVAHI_* */
 
35
#include <stdio.h>
 
36
#include <assert.h>
 
37
#include <stdlib.h>
 
38
#include <time.h>
 
39
#include <net/if.h>             /* if_nametoindex */
 
40
#include <sys/ioctl.h>          // ioctl, ifreq, SIOCGIFFLAGS, IFF_UP, SIOCSIFFLAGS
 
41
#include <net/if.h>             // ioctl, ifreq, SIOCGIFFLAGS, IFF_UP, SIOCSIFFLAGS
 
42
 
90
43
#include <avahi-core/core.h>
91
44
#include <avahi-core/lookup.h>
92
45
#include <avahi-core/log.h>
94
47
#include <avahi-common/malloc.h>
95
48
#include <avahi-common/error.h>
96
49
 
97
 
/* GnuTLS */
98
 
#include <gnutls/gnutls.h>      /* All GnuTLS types, constants and
99
 
                                   functions:
100
 
                                   gnutls_*
101
 
                                   init_gnutls_session(),
102
 
                                   GNUTLS_* */
103
 
#include <gnutls/openpgp.h>
104
 
                          /* gnutls_certificate_set_openpgp_key_file(),
105
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
106
 
 
107
 
/* GPGME */
108
 
#include <gpgme.h>              /* All GPGME types, constants and
109
 
                                   functions:
110
 
                                   gpgme_*
111
 
                                   GPGME_PROTOCOL_OpenPGP,
112
 
                                   GPG_ERR_NO_* */
 
50
//mandos client part
 
51
#include <sys/types.h>          /* socket(), inet_pton() */
 
52
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
 
53
                                   struct in6_addr, inet_pton() */
 
54
#include <gnutls/gnutls.h>      /* All GnuTLS stuff */
 
55
#include <gnutls/openpgp.h>     /* GnuTLS with openpgp stuff */
 
56
 
 
57
#include <unistd.h>             /* close() */
 
58
#include <netinet/in.h>
 
59
#include <stdbool.h>            /* true */
 
60
#include <string.h>             /* memset */
 
61
#include <arpa/inet.h>          /* inet_pton() */
 
62
#include <iso646.h>             /* not */
 
63
 
 
64
// gpgme
 
65
#include <errno.h>              /* perror() */
 
66
#include <gpgme.h>
 
67
 
 
68
// getopt long
 
69
#include <getopt.h>
113
70
 
114
71
#define BUFFER_SIZE 256
 
72
#define DH_BITS 1024
115
73
 
116
 
#define PATHDIR "/conf/conf.d/mandos"
117
 
#define SECKEY "seckey.txt"
118
 
#define PUBKEY "pubkey.txt"
 
74
static const char *certdir = "/conf/conf.d/mandos";
 
75
static const char *certfile = "openpgp-client.txt";
 
76
static const char *certkey = "openpgp-client-key.txt";
119
77
 
120
78
bool debug = false;
121
 
static const char mandos_protocol_version[] = "1";
122
 
const char *argp_program_version = "mandos-client " VERSION;
123
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
124
79
 
125
 
/* Used for passing in values through the Avahi callback functions */
126
80
typedef struct {
127
81
  AvahiSimplePoll *simple_poll;
128
82
  AvahiServer *server;
129
83
  gnutls_certificate_credentials_t cred;
130
84
  unsigned int dh_bits;
131
 
  gnutls_dh_params_t dh_params;
132
85
  const char *priority;
 
86
} mandos_context;
 
87
 
 
88
static ssize_t pgp_packet_decrypt (char *packet, size_t packet_size,
 
89
                                   char **new_packet,
 
90
                                   const char *homedir){
 
91
  gpgme_data_t dh_crypto, dh_plain;
133
92
  gpgme_ctx_t ctx;
134
 
} mandos_context;
135
 
 
136
 
/* global context so signal handler can reach it*/
137
 
mandos_context mc = { .simple_poll = NULL, .server = NULL,
138
 
                      .dh_bits = 1024, .priority = "SECURE256"
139
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
140
 
 
141
 
/*
142
 
 * Make additional room in "buffer" for at least BUFFER_SIZE more
143
 
 * bytes. "buffer_capacity" is how much is currently allocated,
144
 
 * "buffer_length" is how much is already used.
145
 
 */
146
 
size_t incbuffer(char **buffer, size_t buffer_length,
147
 
                  size_t buffer_capacity){
148
 
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
149
 
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
150
 
    if(buffer == NULL){
151
 
      return 0;
152
 
    }
153
 
    buffer_capacity += BUFFER_SIZE;
154
 
  }
155
 
  return buffer_capacity;
156
 
}
157
 
 
158
 
/* 
159
 
 * Initialize GPGME.
160
 
 */
161
 
static bool init_gpgme(const char *seckey,
162
 
                       const char *pubkey, const char *tempdir){
163
 
  int ret;
164
93
  gpgme_error_t rc;
 
94
  ssize_t ret;
 
95
  ssize_t new_packet_capacity = 0;
 
96
  ssize_t new_packet_length = 0;
165
97
  gpgme_engine_info_t engine_info;
166
 
  
167
 
  
168
 
  /*
169
 
   * Helper function to insert pub and seckey to the engine keyring.
170
 
   */
171
 
  bool import_key(const char *filename){
172
 
    int fd;
173
 
    gpgme_data_t pgp_data;
174
 
    
175
 
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
176
 
    if(fd == -1){
177
 
      perror("open");
178
 
      return false;
179
 
    }
180
 
    
181
 
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
182
 
    if(rc != GPG_ERR_NO_ERROR){
183
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
184
 
              gpgme_strsource(rc), gpgme_strerror(rc));
185
 
      return false;
186
 
    }
187
 
    
188
 
    rc = gpgme_op_import(mc.ctx, pgp_data);
189
 
    if(rc != GPG_ERR_NO_ERROR){
190
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
191
 
              gpgme_strsource(rc), gpgme_strerror(rc));
192
 
      return false;
193
 
    }
194
 
    
195
 
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
196
 
    if(ret == -1){
197
 
      perror("close");
198
 
    }
199
 
    gpgme_data_release(pgp_data);
200
 
    return true;
201
 
  }
202
 
  
203
 
  if(debug){
204
 
    fprintf(stderr, "Initializing GPGME\n");
 
98
 
 
99
  if (debug){
 
100
    fprintf(stderr, "Trying to decrypt OpenPGP packet\n");
205
101
  }
206
102
  
207
103
  /* Init GPGME */
208
104
  gpgme_check_version(NULL);
209
105
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
210
 
  if(rc != GPG_ERR_NO_ERROR){
 
106
  if (rc != GPG_ERR_NO_ERROR){
211
107
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
212
108
            gpgme_strsource(rc), gpgme_strerror(rc));
213
 
    return false;
 
109
    return -1;
214
110
  }
215
111
  
216
 
    /* Set GPGME home directory for the OpenPGP engine only */
217
 
  rc = gpgme_get_engine_info(&engine_info);
218
 
  if(rc != GPG_ERR_NO_ERROR){
 
112
  /* Set GPGME home directory */
 
113
  rc = gpgme_get_engine_info (&engine_info);
 
114
  if (rc != GPG_ERR_NO_ERROR){
219
115
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
220
116
            gpgme_strsource(rc), gpgme_strerror(rc));
221
 
    return false;
 
117
    return -1;
222
118
  }
223
119
  while(engine_info != NULL){
224
120
    if(engine_info->protocol == GPGME_PROTOCOL_OpenPGP){
225
121
      gpgme_set_engine_info(GPGME_PROTOCOL_OpenPGP,
226
 
                            engine_info->file_name, tempdir);
 
122
                            engine_info->file_name, homedir);
227
123
      break;
228
124
    }
229
125
    engine_info = engine_info->next;
230
126
  }
231
127
  if(engine_info == NULL){
232
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
233
 
    return false;
234
 
  }
235
 
  
236
 
  /* Create new GPGME "context" */
237
 
  rc = gpgme_new(&(mc.ctx));
238
 
  if(rc != GPG_ERR_NO_ERROR){
239
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
240
 
            gpgme_strsource(rc), gpgme_strerror(rc));
241
 
    return false;
242
 
  }
243
 
  
244
 
  if(not import_key(pubkey) or not import_key(seckey)){
245
 
    return false;
246
 
  }
247
 
  
248
 
  return true; 
249
 
}
250
 
 
251
 
/* 
252
 
 * Decrypt OpenPGP data.
253
 
 * Returns -1 on error
254
 
 */
255
 
static ssize_t pgp_packet_decrypt(const char *cryptotext,
256
 
                                  size_t crypto_size,
257
 
                                  char **plaintext){
258
 
  gpgme_data_t dh_crypto, dh_plain;
259
 
  gpgme_error_t rc;
260
 
  ssize_t ret;
261
 
  size_t plaintext_capacity = 0;
262
 
  ssize_t plaintext_length = 0;
263
 
  
264
 
  if(debug){
265
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
266
 
  }
267
 
  
268
 
  /* Create new GPGME data buffer from memory cryptotext */
269
 
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
270
 
                               0);
271
 
  if(rc != GPG_ERR_NO_ERROR){
 
128
    fprintf(stderr, "Could not set home dir to %s\n", homedir);
 
129
    return -1;
 
130
  }
 
131
  
 
132
  /* Create new GPGME data buffer from packet buffer */
 
133
  rc = gpgme_data_new_from_mem(&dh_crypto, packet, packet_size, 0);
 
134
  if (rc != GPG_ERR_NO_ERROR){
272
135
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
273
136
            gpgme_strsource(rc), gpgme_strerror(rc));
274
137
    return -1;
276
139
  
277
140
  /* Create new empty GPGME data buffer for the plaintext */
278
141
  rc = gpgme_data_new(&dh_plain);
279
 
  if(rc != GPG_ERR_NO_ERROR){
 
142
  if (rc != GPG_ERR_NO_ERROR){
280
143
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
281
144
            gpgme_strsource(rc), gpgme_strerror(rc));
282
 
    gpgme_data_release(dh_crypto);
283
 
    return -1;
284
 
  }
285
 
  
286
 
  /* Decrypt data from the cryptotext data buffer to the plaintext
287
 
     data buffer */
288
 
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
289
 
  if(rc != GPG_ERR_NO_ERROR){
 
145
    return -1;
 
146
  }
 
147
  
 
148
  /* Create new GPGME "context" */
 
149
  rc = gpgme_new(&ctx);
 
150
  if (rc != GPG_ERR_NO_ERROR){
 
151
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
152
            gpgme_strsource(rc), gpgme_strerror(rc));
 
153
    return -1;
 
154
  }
 
155
  
 
156
  /* Decrypt data from the FILE pointer to the plaintext data
 
157
     buffer */
 
158
  rc = gpgme_op_decrypt(ctx, dh_crypto, dh_plain);
 
159
  if (rc != GPG_ERR_NO_ERROR){
290
160
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
291
161
            gpgme_strsource(rc), gpgme_strerror(rc));
292
 
    plaintext_length = -1;
293
 
    if(debug){
294
 
      gpgme_decrypt_result_t result;
295
 
      result = gpgme_op_decrypt_result(mc.ctx);
296
 
      if(result == NULL){
297
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
298
 
      } else {
299
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
300
 
                result->unsupported_algorithm);
301
 
        fprintf(stderr, "Wrong key usage: %u\n",
302
 
                result->wrong_key_usage);
303
 
        if(result->file_name != NULL){
304
 
          fprintf(stderr, "File name: %s\n", result->file_name);
305
 
        }
306
 
        gpgme_recipient_t recipient;
307
 
        recipient = result->recipients;
308
 
        if(recipient){
309
 
          while(recipient != NULL){
310
 
            fprintf(stderr, "Public key algorithm: %s\n",
311
 
                    gpgme_pubkey_algo_name(recipient->pubkey_algo));
312
 
            fprintf(stderr, "Key ID: %s\n", recipient->keyid);
313
 
            fprintf(stderr, "Secret key available: %s\n",
314
 
                    recipient->status == GPG_ERR_NO_SECKEY
315
 
                    ? "No" : "Yes");
316
 
            recipient = recipient->next;
317
 
          }
 
162
    return -1;
 
163
  }
 
164
 
 
165
  if(debug){
 
166
    fprintf(stderr, "Decryption of OpenPGP packet succeeded\n");
 
167
  }
 
168
 
 
169
  if (debug){
 
170
    gpgme_decrypt_result_t result;
 
171
    result = gpgme_op_decrypt_result(ctx);
 
172
    if (result == NULL){
 
173
      fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
174
    } else {
 
175
      fprintf(stderr, "Unsupported algorithm: %s\n",
 
176
              result->unsupported_algorithm);
 
177
      fprintf(stderr, "Wrong key usage: %d\n",
 
178
              result->wrong_key_usage);
 
179
      if(result->file_name != NULL){
 
180
        fprintf(stderr, "File name: %s\n", result->file_name);
 
181
      }
 
182
      gpgme_recipient_t recipient;
 
183
      recipient = result->recipients;
 
184
      if(recipient){
 
185
        while(recipient != NULL){
 
186
          fprintf(stderr, "Public key algorithm: %s\n",
 
187
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
188
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
189
          fprintf(stderr, "Secret key available: %s\n",
 
190
                  recipient->status == GPG_ERR_NO_SECKEY
 
191
                  ? "No" : "Yes");
 
192
          recipient = recipient->next;
318
193
        }
319
194
      }
320
195
    }
321
 
    goto decrypt_end;
322
196
  }
323
197
  
324
 
  if(debug){
325
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
326
 
  }
 
198
  /* Delete the GPGME FILE pointer cryptotext data buffer */
 
199
  gpgme_data_release(dh_crypto);
327
200
  
328
201
  /* Seek back to the beginning of the GPGME plaintext data buffer */
329
 
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
330
 
    perror("gpgme_data_seek");
331
 
    plaintext_length = -1;
332
 
    goto decrypt_end;
 
202
  if (gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET) == -1){
 
203
    perror("pgpme_data_seek");
333
204
  }
334
205
  
335
 
  *plaintext = NULL;
 
206
  *new_packet = 0;
336
207
  while(true){
337
 
    plaintext_capacity = incbuffer(plaintext,
338
 
                                      (size_t)plaintext_length,
339
 
                                      plaintext_capacity);
340
 
    if(plaintext_capacity == 0){
341
 
        perror("incbuffer");
342
 
        plaintext_length = -1;
343
 
        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;
344
217
    }
345
218
    
346
 
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
 
219
    ret = gpgme_data_read(dh_plain, *new_packet + new_packet_length,
347
220
                          BUFFER_SIZE);
348
221
    /* Print the data, if any */
349
 
    if(ret == 0){
350
 
      /* EOF */
 
222
    if (ret == 0){
351
223
      break;
352
224
    }
353
225
    if(ret < 0){
354
226
      perror("gpgme_data_read");
355
 
      plaintext_length = -1;
356
 
      goto decrypt_end;
357
 
    }
358
 
    plaintext_length += ret;
359
 
  }
360
 
  
361
 
  if(debug){
362
 
    fprintf(stderr, "Decrypted password is: ");
363
 
    for(ssize_t i = 0; i < plaintext_length; i++){
364
 
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
365
 
    }
366
 
    fprintf(stderr, "\n");
367
 
  }
368
 
  
369
 
 decrypt_end:
370
 
  
371
 
  /* Delete the GPGME cryptotext data buffer */
372
 
  gpgme_data_release(dh_crypto);
 
227
      return -1;
 
228
    }
 
229
    new_packet_length += ret;
 
230
  }
 
231
 
 
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
  /*   } */
373
239
  
374
240
  /* Delete the GPGME plaintext data buffer */
375
241
  gpgme_data_release(dh_plain);
376
 
  return plaintext_length;
 
242
  return new_packet_length;
377
243
}
378
244
 
379
 
static const char * safer_gnutls_strerror(int value){
380
 
  const char *ret = gnutls_strerror(value); /* Spurious warning from
381
 
                                               -Wunreachable-code */
382
 
  if(ret == NULL)
 
245
static const char * safer_gnutls_strerror (int value) {
 
246
  const char *ret = gnutls_strerror (value);
 
247
  if (ret == NULL)
383
248
    ret = "(unknown)";
384
249
  return ret;
385
250
}
386
251
 
387
 
/* GnuTLS log function callback */
388
252
static void debuggnutls(__attribute__((unused)) int level,
389
253
                        const char* string){
390
 
  fprintf(stderr, "GnuTLS: %s", string);
 
254
  fprintf(stderr, "%s", string);
391
255
}
392
256
 
393
 
static int init_gnutls_global(const char *pubkeyfilename,
394
 
                              const char *seckeyfilename){
 
257
static int initgnutls(mandos_context *mc){
 
258
  const char *err;
395
259
  int ret;
396
260
  
397
261
  if(debug){
398
262
    fprintf(stderr, "Initializing GnuTLS\n");
399
263
  }
400
 
  
401
 
  ret = gnutls_global_init();
402
 
  if(ret != GNUTLS_E_SUCCESS){
403
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
404
 
            safer_gnutls_strerror(ret));
 
264
 
 
265
  if ((ret = gnutls_global_init ())
 
266
      != GNUTLS_E_SUCCESS) {
 
267
    fprintf (stderr, "global_init: %s\n", safer_gnutls_strerror(ret));
405
268
    return -1;
406
269
  }
407
 
  
408
 
  if(debug){
409
 
    /* "Use a log level over 10 to enable all debugging options."
410
 
     * - GnuTLS manual
411
 
     */
 
270
 
 
271
  if (debug){
412
272
    gnutls_global_set_log_level(11);
413
273
    gnutls_global_set_log_function(debuggnutls);
414
274
  }
415
275
  
416
 
  /* OpenPGP credentials */
417
 
  gnutls_certificate_allocate_credentials(&mc.cred);
418
 
  if(ret != GNUTLS_E_SUCCESS){
419
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
420
 
                                                    from
421
 
                                                    -Wunreachable-code
422
 
                                                 */
423
 
            safer_gnutls_strerror(ret));
424
 
    gnutls_global_deinit();
 
276
  /* openpgp credentials */
 
277
  if ((ret = gnutls_certificate_allocate_credentials (&es->cred))
 
278
      != GNUTLS_E_SUCCESS) {
 
279
    fprintf (stderr, "memory error: %s\n",
 
280
             safer_gnutls_strerror(ret));
425
281
    return -1;
426
282
  }
427
283
  
428
284
  if(debug){
429
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
430
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
431
 
            seckeyfilename);
 
285
    fprintf(stderr, "Attempting to use OpenPGP certificate %s"
 
286
            " and keyfile %s as GnuTLS credentials\n", certfile,
 
287
            certkey);
432
288
  }
433
289
  
434
290
  ret = gnutls_certificate_set_openpgp_key_file
435
 
    (mc.cred, pubkeyfilename, seckeyfilename,
436
 
     GNUTLS_OPENPGP_FMT_BASE64);
437
 
  if(ret != GNUTLS_E_SUCCESS){
438
 
    fprintf(stderr,
439
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
440
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
441
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
442
 
            safer_gnutls_strerror(ret));
443
 
    goto globalfail;
444
 
  }
445
 
  
446
 
  /* GnuTLS server initialization */
447
 
  ret = gnutls_dh_params_init(&mc.dh_params);
448
 
  if(ret != GNUTLS_E_SUCCESS){
449
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
450
 
            " %s\n", safer_gnutls_strerror(ret));
451
 
    goto globalfail;
452
 
  }
453
 
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
454
 
  if(ret != GNUTLS_E_SUCCESS){
455
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
456
 
            safer_gnutls_strerror(ret));
457
 
    goto globalfail;
458
 
  }
459
 
  
460
 
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
461
 
  
462
 
  return 0;
463
 
  
464
 
 globalfail:
465
 
  
466
 
  gnutls_certificate_free_credentials(mc.cred);
467
 
  gnutls_global_deinit();
468
 
  gnutls_dh_params_deinit(mc.dh_params);
469
 
  return -1;
470
 
}
471
 
 
472
 
static int init_gnutls_session(gnutls_session_t *session){
473
 
  int ret;
474
 
  /* GnuTLS session creation */
475
 
  ret = gnutls_init(session, GNUTLS_SERVER);
476
 
  if(ret != GNUTLS_E_SUCCESS){
 
291
    (es->cred, certfile, certkey, GNUTLS_OPENPGP_FMT_BASE64);
 
292
  if (ret != GNUTLS_E_SUCCESS) {
 
293
    fprintf
 
294
      (stderr, "Error[%d] while reading the OpenPGP key pair ('%s',"
 
295
       " '%s')\n",
 
296
       ret, certfile, certkey);
 
297
    fprintf(stdout, "The Error is: %s\n",
 
298
            safer_gnutls_strerror(ret));
 
299
    return -1;
 
300
  }
 
301
  
 
302
  //GnuTLS server initialization
 
303
  if ((ret = gnutls_dh_params_init (&es->dh_params))
 
304
      != GNUTLS_E_SUCCESS) {
 
305
    fprintf (stderr, "Error in dh parameter initialization: %s\n",
 
306
             safer_gnutls_strerror(ret));
 
307
    return -1;
 
308
  }
 
309
  
 
310
  if ((ret = gnutls_dh_params_generate2 (es->dh_params, DH_BITS))
 
311
      != GNUTLS_E_SUCCESS) {
 
312
    fprintf (stderr, "Error in prime generation: %s\n",
 
313
             safer_gnutls_strerror(ret));
 
314
    return -1;
 
315
  }
 
316
  
 
317
  gnutls_certificate_set_dh_params (es->cred, es->dh_params);
 
318
  
 
319
  // GnuTLS session creation
 
320
  if ((ret = gnutls_init (&es->session, GNUTLS_SERVER))
 
321
      != GNUTLS_E_SUCCESS){
477
322
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
478
323
            safer_gnutls_strerror(ret));
479
324
  }
480
325
  
481
 
  {
482
 
    const char *err;
483
 
    ret = gnutls_priority_set_direct(*session, mc.priority, &err);
484
 
    if(ret != GNUTLS_E_SUCCESS){
485
 
      fprintf(stderr, "Syntax error at: %s\n", err);
486
 
      fprintf(stderr, "GnuTLS error: %s\n",
487
 
              safer_gnutls_strerror(ret));
488
 
      gnutls_deinit(*session);
489
 
      return -1;
490
 
    }
 
326
  if ((ret = gnutls_priority_set_direct (es->session, mc->priority, &err))
 
327
      != GNUTLS_E_SUCCESS) {
 
328
    fprintf(stderr, "Syntax error at: %s\n", err);
 
329
    fprintf(stderr, "GnuTLS error: %s\n",
 
330
            safer_gnutls_strerror(ret));
 
331
    return -1;
491
332
  }
492
333
  
493
 
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
494
 
                               mc.cred);
495
 
  if(ret != GNUTLS_E_SUCCESS){
496
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
334
  if ((ret = gnutls_credentials_set
 
335
       (es->session, GNUTLS_CRD_CERTIFICATE, es->cred))
 
336
      != GNUTLS_E_SUCCESS) {
 
337
    fprintf(stderr, "Error setting a credentials set: %s\n",
497
338
            safer_gnutls_strerror(ret));
498
 
    gnutls_deinit(*session);
499
339
    return -1;
500
340
  }
501
341
  
502
342
  /* ignore client certificate if any. */
503
 
  gnutls_certificate_server_set_request(*session,
504
 
                                        GNUTLS_CERT_IGNORE);
 
343
  gnutls_certificate_server_set_request (es->session,
 
344
                                         GNUTLS_CERT_IGNORE);
505
345
  
506
 
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
346
  gnutls_dh_set_prime_bits (es->session, DH_BITS);
507
347
  
508
348
  return 0;
509
349
}
510
350
 
511
 
/* Avahi log function callback */
512
351
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
513
352
                      __attribute__((unused)) const char *txt){}
514
353
 
515
 
/* Called when a Mandos server is found */
516
354
static int start_mandos_communication(const char *ip, uint16_t port,
517
355
                                      AvahiIfIndex if_index,
518
 
                                      int af){
 
356
                                      mandos_context *mc){
519
357
  int ret, tcp_sd;
520
 
  ssize_t sret;
521
 
  union {
522
 
    struct sockaddr_in in;
523
 
    struct sockaddr_in6 in6;
524
 
  } to;
 
358
  struct sockaddr_in6 to;
 
359
  encrypted_session es;
525
360
  char *buffer = NULL;
526
361
  char *decrypted_buffer;
527
362
  size_t buffer_length = 0;
528
363
  size_t buffer_capacity = 0;
529
364
  ssize_t decrypted_buffer_size;
530
 
  size_t written;
 
365
  size_t written = 0;
531
366
  int retval = 0;
532
 
  gnutls_session_t session;
533
 
  int pf;                       /* Protocol family */
534
 
  
535
 
  switch(af){
536
 
  case AF_INET6:
537
 
    pf = PF_INET6;
538
 
    break;
539
 
  case AF_INET:
540
 
    pf = PF_INET;
541
 
    break;
542
 
  default:
543
 
    fprintf(stderr, "Bad address family: %d\n", af);
544
 
    return -1;
545
 
  }
546
 
  
547
 
  ret = init_gnutls_session(&session);
548
 
  if(ret != 0){
549
 
    return -1;
550
 
  }
 
367
  char interface[IF_NAMESIZE];
551
368
  
552
369
  if(debug){
553
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
554
 
            "\n", ip, port);
 
370
    fprintf(stderr, "Setting up a tcp connection to %s, port %d\n",
 
371
            ip, port);
555
372
  }
556
373
  
557
 
  tcp_sd = socket(pf, SOCK_STREAM, 0);
558
 
  if(tcp_sd < 0){
 
374
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
 
375
  if(tcp_sd < 0) {
559
376
    perror("socket");
560
377
    return -1;
561
378
  }
 
379
 
 
380
  if(debug){
 
381
    if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
382
      if(debug){
 
383
        perror("if_indextoname");
 
384
      }
 
385
      return -1;
 
386
    }
 
387
    
 
388
    fprintf(stderr, "Binding to interface %s\n", interface);
 
389
  }
562
390
  
563
 
  memset(&to, 0, sizeof(to));
564
 
  if(af == AF_INET6){
565
 
    to.in6.sin6_family = (uint16_t)af;
566
 
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
567
 
  } else {                      /* IPv4 */
568
 
    to.in.sin_family = (sa_family_t)af;
569
 
    ret = inet_pton(af, ip, &to.in.sin_addr);
570
 
  }
571
 
  if(ret < 0 ){
 
391
  memset(&to,0,sizeof(to));     /* Spurious warning */
 
392
  to.sin6_family = AF_INET6;
 
393
  ret = inet_pton(AF_INET6, ip, &to.sin6_addr);
 
394
  if (ret < 0 ){
572
395
    perror("inet_pton");
573
396
    return -1;
574
 
  }
 
397
  }  
575
398
  if(ret == 0){
576
399
    fprintf(stderr, "Bad address: %s\n", ip);
577
400
    return -1;
578
401
  }
579
 
  if(af == AF_INET6){
580
 
    to.in6.sin6_port = htons(port); /* Spurious warnings from
581
 
                                       -Wconversion and
582
 
                                       -Wunreachable-code */
583
 
    
584
 
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
585
 
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
586
 
                              -Wunreachable-code*/
587
 
      if(if_index == AVAHI_IF_UNSPEC){
588
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
589
 
                " without a network interface\n");
590
 
        return -1;
591
 
      }
592
 
      /* Set the network interface number as scope */
593
 
      to.in6.sin6_scope_id = (uint32_t)if_index;
594
 
    }
595
 
  } else {
596
 
    to.in.sin_port = htons(port); /* Spurious warnings from
597
 
                                     -Wconversion and
598
 
                                     -Wunreachable-code */
599
 
  }
 
402
  to.sin6_port = htons(port);   /* Spurious warning */
 
403
  
 
404
  to.sin6_scope_id = (uint32_t)if_index;
600
405
  
601
406
  if(debug){
602
 
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
603
 
      char interface[IF_NAMESIZE];
604
 
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
605
 
        perror("if_indextoname");
606
 
      } else {
607
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
608
 
                ip, interface, port);
609
 
      }
610
 
    } else {
611
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
612
 
              port);
613
 
    }
614
 
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
615
 
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
616
 
    const char *pcret;
617
 
    if(af == AF_INET6){
618
 
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
619
 
                        sizeof(addrstr));
620
 
    } else {
621
 
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
622
 
                        sizeof(addrstr));
623
 
    }
624
 
    if(pcret == NULL){
625
 
      perror("inet_ntop");
626
 
    } else {
627
 
      if(strcmp(addrstr, ip) != 0){
628
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
629
 
      }
630
 
    }
 
407
    fprintf(stderr, "Connection to: %s, port %d\n", ip, port);
 
408
/*     char addrstr[INET6_ADDRSTRLEN]; */
 
409
/*     if(inet_ntop(to.sin6_family, &(to.sin6_addr), addrstr, */
 
410
/*               sizeof(addrstr)) == NULL){ */
 
411
/*       perror("inet_ntop"); */
 
412
/*     } else { */
 
413
/*       fprintf(stderr, "Really connecting to: %s, port %d\n", */
 
414
/*            addrstr, ntohs(to.sin6_port)); */
 
415
/*     } */
631
416
  }
632
417
  
633
 
  if(af == AF_INET6){
634
 
    ret = connect(tcp_sd, &to.in6, sizeof(to));
635
 
  } else {
636
 
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
637
 
  }
638
 
  if(ret < 0){
 
418
  ret = connect(tcp_sd, (struct sockaddr *) &to, sizeof(to));
 
419
  if (ret < 0){
639
420
    perror("connect");
640
421
    return -1;
641
422
  }
642
423
  
643
 
  const char *out = mandos_protocol_version;
644
 
  written = 0;
645
 
  while(true){
646
 
    size_t out_size = strlen(out);
647
 
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
648
 
                                   out_size - written));
649
 
    if(ret == -1){
650
 
      perror("write");
651
 
      retval = -1;
652
 
      goto mandos_end;
653
 
    }
654
 
    written += (size_t)ret;
655
 
    if(written < out_size){
656
 
      continue;
657
 
    } else {
658
 
      if(out == mandos_protocol_version){
659
 
        written = 0;
660
 
        out = "\r\n";
661
 
      } else {
662
 
        break;
663
 
      }
664
 
    }
 
424
  ret = initgnutls (&es);
 
425
  if (ret != 0){
 
426
    retval = -1;
 
427
    return -1;
665
428
  }
666
429
  
 
430
  gnutls_transport_set_ptr (es.session,
 
431
                            (gnutls_transport_ptr_t) tcp_sd);
 
432
  
667
433
  if(debug){
668
434
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
669
435
  }
670
436
  
671
 
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
672
 
  
673
 
  do{
674
 
    ret = gnutls_handshake(session);
675
 
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
676
 
  
677
 
  if(ret != GNUTLS_E_SUCCESS){
 
437
  ret = gnutls_handshake (es.session);
 
438
  
 
439
  if (ret != GNUTLS_E_SUCCESS){
678
440
    if(debug){
679
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
680
 
      gnutls_perror(ret);
 
441
      fprintf(stderr, "\n*** Handshake failed ***\n");
 
442
      gnutls_perror (ret);
681
443
    }
682
444
    retval = -1;
683
 
    goto mandos_end;
 
445
    goto exit;
684
446
  }
685
447
  
686
 
  /* Read OpenPGP packet that contains the wanted password */
 
448
  //Retrieve OpenPGP packet that contains the wanted password
687
449
  
688
450
  if(debug){
689
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
451
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
690
452
            ip);
691
453
  }
692
 
  
 
454
 
693
455
  while(true){
694
 
    buffer_capacity = incbuffer(&buffer, buffer_length,
695
 
                                   buffer_capacity);
696
 
    if(buffer_capacity == 0){
697
 
      perror("incbuffer");
698
 
      retval = -1;
699
 
      goto mandos_end;
 
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;
700
463
    }
701
464
    
702
 
    sret = gnutls_record_recv(session, buffer+buffer_length,
703
 
                              BUFFER_SIZE);
704
 
    if(sret == 0){
 
465
    ret = gnutls_record_recv
 
466
      (es.session, buffer+buffer_length, BUFFER_SIZE);
 
467
    if (ret == 0){
705
468
      break;
706
469
    }
707
 
    if(sret < 0){
708
 
      switch(sret){
 
470
    if (ret < 0){
 
471
      switch(ret){
709
472
      case GNUTLS_E_INTERRUPTED:
710
473
      case GNUTLS_E_AGAIN:
711
474
        break;
712
475
      case GNUTLS_E_REHANDSHAKE:
713
 
        do{
714
 
          ret = gnutls_handshake(session);
715
 
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
716
 
        if(ret < 0){
717
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
718
 
          gnutls_perror(ret);
 
476
        ret = gnutls_handshake (es.session);
 
477
        if (ret < 0){
 
478
          fprintf(stderr, "\n*** Handshake failed ***\n");
 
479
          gnutls_perror (ret);
719
480
          retval = -1;
720
 
          goto mandos_end;
 
481
          goto exit;
721
482
        }
722
483
        break;
723
484
      default:
724
485
        fprintf(stderr, "Unknown error while reading data from"
725
 
                " encrypted session with Mandos server\n");
 
486
                " encrypted session with mandos server\n");
726
487
        retval = -1;
727
 
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
728
 
        goto mandos_end;
 
488
        gnutls_bye (es.session, GNUTLS_SHUT_RDWR);
 
489
        goto exit;
729
490
      }
730
491
    } else {
731
 
      buffer_length += (size_t) sret;
 
492
      buffer_length += (size_t) ret;
732
493
    }
733
494
  }
734
495
  
735
 
  if(debug){
736
 
    fprintf(stderr, "Closing TLS session\n");
737
 
  }
738
 
  
739
 
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
740
 
  
741
 
  if(buffer_length > 0){
 
496
  if (buffer_length > 0){
742
497
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
743
498
                                               buffer_length,
744
 
                                               &decrypted_buffer);
745
 
    if(decrypted_buffer_size >= 0){
746
 
      written = 0;
 
499
                                               &decrypted_buffer,
 
500
                                               certdir);
 
501
    if (decrypted_buffer_size >= 0){
747
502
      while(written < (size_t) decrypted_buffer_size){
748
 
        ret = (int)fwrite(decrypted_buffer + written, 1,
749
 
                          (size_t)decrypted_buffer_size - written,
750
 
                          stdout);
 
503
        ret = (int)fwrite (decrypted_buffer + written, 1,
 
504
                           (size_t)decrypted_buffer_size - written,
 
505
                           stdout);
751
506
        if(ret == 0 and ferror(stdout)){
752
507
          if(debug){
753
508
            fprintf(stderr, "Error writing encrypted data: %s\n",
762
517
    } else {
763
518
      retval = -1;
764
519
    }
765
 
  } else {
766
 
    retval = -1;
767
 
  }
768
 
  
769
 
  /* Shutdown procedure */
770
 
  
771
 
 mandos_end:
 
520
  }
 
521
 
 
522
  //shutdown procedure
 
523
 
 
524
  if(debug){
 
525
    fprintf(stderr, "Closing TLS session\n");
 
526
  }
 
527
 
772
528
  free(buffer);
773
 
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
774
 
  if(ret == -1){
775
 
    perror("close");
776
 
  }
777
 
  gnutls_deinit(session);
 
529
  gnutls_bye (es.session, GNUTLS_SHUT_RDWR);
 
530
 exit:
 
531
  close(tcp_sd);
 
532
  gnutls_deinit (es.session);
 
533
  gnutls_certificate_free_credentials (es.cred);
 
534
  gnutls_global_deinit ();
778
535
  return retval;
779
536
}
780
537
 
781
 
static void resolve_callback(AvahiSServiceResolver *r,
782
 
                             AvahiIfIndex interface,
783
 
                             AvahiProtocol proto,
784
 
                             AvahiResolverEvent event,
785
 
                             const char *name,
786
 
                             const char *type,
787
 
                             const char *domain,
788
 
                             const char *host_name,
789
 
                             const AvahiAddress *address,
790
 
                             uint16_t port,
791
 
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
792
 
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
793
 
                             flags,
794
 
                             AVAHI_GCC_UNUSED void* userdata){
795
 
  assert(r);
 
538
static void resolve_callback( AvahiSServiceResolver *r,
 
539
                              AvahiIfIndex interface,
 
540
                              AVAHI_GCC_UNUSED AvahiProtocol protocol,
 
541
                              AvahiResolverEvent event,
 
542
                              const char *name,
 
543
                              const char *type,
 
544
                              const char *domain,
 
545
                              const char *host_name,
 
546
                              const AvahiAddress *address,
 
547
                              uint16_t port,
 
548
                              AVAHI_GCC_UNUSED AvahiStringList *txt,
 
549
                              AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
 
550
                              AVAHI_GCC_UNUSED void* userdata) {
 
551
  mandos_context *mc = userdata;
 
552
  assert(r);                    /* Spurious warning */
796
553
  
797
554
  /* Called whenever a service has been resolved successfully or
798
555
     timed out */
799
556
  
800
 
  switch(event){
 
557
  switch (event) {
801
558
  default:
802
559
  case AVAHI_RESOLVER_FAILURE:
803
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
804
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
805
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
560
    fprintf(stderr, "(Resolver) Failed to resolve service '%s' of"
 
561
            " type '%s' in domain '%s': %s\n", name, type, domain,
 
562
            avahi_strerror(avahi_server_errno(mc->server)));
806
563
    break;
807
564
    
808
565
  case AVAHI_RESOLVER_FOUND:
810
567
      char ip[AVAHI_ADDRESS_STR_MAX];
811
568
      avahi_address_snprint(ip, sizeof(ip), address);
812
569
      if(debug){
813
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
814
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
815
 
                ip, (intmax_t)interface, port);
 
570
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s) on"
 
571
                " port %d\n", name, host_name, ip, port);
816
572
      }
817
 
      int ret = start_mandos_communication(ip, port, interface,
818
 
                                           avahi_proto_to_af(proto));
819
 
      if(ret == 0){
820
 
        avahi_simple_poll_quit(mc.simple_poll);
 
573
      int ret = start_mandos_communication(ip, port, interface, mc);
 
574
      if (ret == 0){
 
575
        exit(EXIT_SUCCESS);
821
576
      }
822
577
    }
823
578
  }
824
579
  avahi_s_service_resolver_free(r);
825
580
}
826
581
 
827
 
static void browse_callback(AvahiSServiceBrowser *b,
828
 
                            AvahiIfIndex interface,
829
 
                            AvahiProtocol protocol,
830
 
                            AvahiBrowserEvent event,
831
 
                            const char *name,
832
 
                            const char *type,
833
 
                            const char *domain,
834
 
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
835
 
                            flags,
836
 
                            AVAHI_GCC_UNUSED void* userdata){
837
 
  assert(b);
 
582
static void browse_callback( AvahiSServiceBrowser *b,
 
583
                             AvahiIfIndex interface,
 
584
                             AvahiProtocol protocol,
 
585
                             AvahiBrowserEvent event,
 
586
                             const char *name,
 
587
                             const char *type,
 
588
                             const char *domain,
 
589
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
 
590
                             void* userdata) {
 
591
  mandos_context *mc = userdata;
 
592
  assert(b);                    /* Spurious warning */
838
593
  
839
594
  /* Called whenever a new services becomes available on the LAN or
840
595
     is removed from the LAN */
841
596
  
842
 
  switch(event){
 
597
  switch (event) {
843
598
  default:
844
599
  case AVAHI_BROWSER_FAILURE:
845
 
    
846
 
    fprintf(stderr, "(Avahi browser) %s\n",
847
 
            avahi_strerror(avahi_server_errno(mc.server)));
848
 
    avahi_simple_poll_quit(mc.simple_poll);
 
600
      
 
601
    fprintf(stderr, "(Browser) %s\n",
 
602
            avahi_strerror(avahi_server_errno(mc->server)));
 
603
    avahi_simple_poll_quit(mc->simple_poll);
849
604
    return;
850
 
    
 
605
      
851
606
  case AVAHI_BROWSER_NEW:
852
 
    /* We ignore the returned Avahi resolver object. In the callback
853
 
       function we free it. If the Avahi server is terminated before
854
 
       the callback function is called the Avahi server will free the
855
 
       resolver for us. */
856
 
    
857
 
    if(!(avahi_s_service_resolver_new(mc.server, interface,
858
 
                                       protocol, name, type, domain,
 
607
    /* We ignore the returned resolver object. In the callback
 
608
       function we free it. If the server is terminated before
 
609
       the callback function is called the server will free
 
610
       the resolver for us. */
 
611
      
 
612
    if (!(avahi_s_service_resolver_new(mc->server, interface, protocol, name,
 
613
                                       type, domain,
859
614
                                       AVAHI_PROTO_INET6, 0,
860
 
                                       resolve_callback, NULL)))
861
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
862
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
615
                                       resolve_callback, mc)))
 
616
      fprintf(stderr, "Failed to resolve service '%s': %s\n", name,
 
617
              avahi_strerror(avahi_server_errno(s)));
863
618
    break;
864
 
    
 
619
      
865
620
  case AVAHI_BROWSER_REMOVE:
866
621
    break;
867
 
    
 
622
      
868
623
  case AVAHI_BROWSER_ALL_FOR_NOW:
869
624
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
870
 
    if(debug){
871
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
872
 
    }
873
625
    break;
874
626
  }
875
627
}
876
628
 
877
 
sig_atomic_t quit_now = 0;
878
 
 
879
 
/* stop main loop after sigterm has been called */
880
 
static void handle_sigterm(__attribute__((unused)) int sig){
881
 
  if(quit_now){
882
 
    return;
883
 
  }
884
 
  quit_now = 1;
885
 
  int old_errno = errno;
886
 
  if(mc.simple_poll != NULL){
887
 
    avahi_simple_poll_quit(mc.simple_poll);
888
 
  }
889
 
  errno = old_errno;
 
629
/* Combines file name and path and returns the malloced new
 
630
   string. some sane checks could/should be added */
 
631
static const char *combinepath(const char *first, const char *second){
 
632
  size_t f_len = strlen(first);
 
633
  size_t s_len = strlen(second);
 
634
  char *tmp = malloc(f_len + s_len + 2);
 
635
  if (tmp == NULL){
 
636
    return NULL;
 
637
  }
 
638
  if(f_len > 0){
 
639
    memcpy(tmp, first, f_len);
 
640
  }
 
641
  tmp[f_len] = '/';
 
642
  if(s_len > 0){
 
643
    memcpy(tmp + f_len + 1, second, s_len);
 
644
  }
 
645
  tmp[f_len + 1 + s_len] = '\0';
 
646
  return tmp;
890
647
}
891
648
 
892
 
int main(int argc, char *argv[]){
893
 
  AvahiSServiceBrowser *sb = NULL;
894
 
  int error;
895
 
  int ret;
896
 
  intmax_t tmpmax;
897
 
  int numchars;
898
 
  int exitcode = EXIT_SUCCESS;
899
 
  const char *interface = "eth0";
900
 
  struct ifreq network;
901
 
  int sd;
902
 
  uid_t uid;
903
 
  gid_t gid;
904
 
  char *connect_to = NULL;
905
 
  char tempdir[] = "/tmp/mandosXXXXXX";
906
 
  bool tempdir_created = false;
907
 
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
908
 
  const char *seckey = PATHDIR "/" SECKEY;
909
 
  const char *pubkey = PATHDIR "/" PUBKEY;
910
 
  
911
 
  /* Initialize Mandos context */
912
 
  mc = (mandos_context){ .simple_poll = NULL, .server = NULL,
913
 
                         .dh_bits = 1024, .priority = "SECURE256"
914
 
                         ":!CTYPE-X.509:+CTYPE-OPENPGP" };
915
 
  bool gnutls_initialized = false;
916
 
  bool gpgme_initialized = false;
917
 
  double delay = 2.5;
918
649
 
919
 
  struct sigaction old_sigterm_action;
920
 
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
921
 
  
922
 
  {
923
 
    struct argp_option options[] = {
924
 
      { .name = "debug", .key = 128,
925
 
        .doc = "Debug mode", .group = 3 },
926
 
      { .name = "connect", .key = 'c',
927
 
        .arg = "ADDRESS:PORT",
928
 
        .doc = "Connect directly to a specific Mandos server",
929
 
        .group = 1 },
930
 
      { .name = "interface", .key = 'i',
931
 
        .arg = "NAME",
932
 
        .doc = "Network interface that will be used to search for"
933
 
        " Mandos servers",
934
 
        .group = 1 },
935
 
      { .name = "seckey", .key = 's',
936
 
        .arg = "FILE",
937
 
        .doc = "OpenPGP secret key file base name",
938
 
        .group = 1 },
939
 
      { .name = "pubkey", .key = 'p',
940
 
        .arg = "FILE",
941
 
        .doc = "OpenPGP public key file base name",
942
 
        .group = 2 },
943
 
      { .name = "dh-bits", .key = 129,
944
 
        .arg = "BITS",
945
 
        .doc = "Bit length of the prime number used in the"
946
 
        " Diffie-Hellman key exchange",
947
 
        .group = 2 },
948
 
      { .name = "priority", .key = 130,
949
 
        .arg = "STRING",
950
 
        .doc = "GnuTLS priority string for the TLS handshake",
951
 
        .group = 1 },
952
 
      { .name = "delay", .key = 131,
953
 
        .arg = "SECONDS",
954
 
        .doc = "Maximum delay to wait for interface startup",
955
 
        .group = 2 },
956
 
      { .name = NULL }
957
 
    };
 
650
int main(AVAHI_GCC_UNUSED int argc, AVAHI_GCC_UNUSED char*argv[]) {
 
651
    AvahiServerConfig config;
 
652
    AvahiSServiceBrowser *sb = NULL;
 
653
    int error;
 
654
    int ret;
 
655
    int returncode = EXIT_SUCCESS;
 
656
    const char *interface = "eth0";
 
657
    struct ifreq network;
 
658
    int sd;
 
659
    char *connect_to = NULL;
 
660
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
 
661
    mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
662
                          .dh_bits = 2048, .priority = "SECURE256"};
958
663
    
959
 
    error_t parse_opt(int key, char *arg,
960
 
                      struct argp_state *state){
961
 
      switch(key){
962
 
      case 128:                 /* --debug */
963
 
        debug = true;
964
 
        break;
965
 
      case 'c':                 /* --connect */
966
 
        connect_to = arg;
967
 
        break;
968
 
      case 'i':                 /* --interface */
969
 
        interface = arg;
970
 
        break;
971
 
      case 's':                 /* --seckey */
972
 
        seckey = arg;
973
 
        break;
974
 
      case 'p':                 /* --pubkey */
975
 
        pubkey = arg;
976
 
        break;
977
 
      case 129:                 /* --dh-bits */
978
 
        ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
979
 
        if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
980
 
           or arg[numchars] != '\0'){
981
 
          fprintf(stderr, "Bad number of DH bits\n");
982
 
          exit(EXIT_FAILURE);
983
 
        }
984
 
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
985
 
        break;
986
 
      case 130:                 /* --priority */
987
 
        mc.priority = arg;
988
 
        break;
989
 
      case 131:                 /* --delay */
990
 
        ret = sscanf(arg, "%lf%n", &delay, &numchars);
991
 
        if(ret < 1 or arg[numchars] != '\0'){
992
 
          fprintf(stderr, "Bad delay\n");
993
 
          exit(EXIT_FAILURE);
994
 
        }
995
 
        break;
996
 
      case ARGP_KEY_ARG:
997
 
        argp_usage(state);
998
 
      case ARGP_KEY_END:
 
664
    while (true){
 
665
      static struct option long_options[] = {
 
666
        {"debug", no_argument, (int *)&debug, 1},
 
667
        {"connect", required_argument, 0, 'C'},
 
668
        {"interface", required_argument, 0, 'i'},
 
669
        {"certdir", required_argument, 0, 'd'},
 
670
        {"certkey", required_argument, 0, 'c'},
 
671
        {"certfile", required_argument, 0, 'k'},
 
672
        {"dh_bits", required_argument, 0, 'D'},
 
673
        {"priority", required_argument, 0, 'p'},
 
674
        {0, 0, 0, 0} };
 
675
      
 
676
      int option_index = 0;
 
677
      ret = getopt_long (argc, argv, "i:", long_options,
 
678
                         &option_index);
 
679
      
 
680
      if (ret == -1){
 
681
        break;
 
682
      }
 
683
      
 
684
      switch(ret){
 
685
      case 0:
 
686
        break;
 
687
      case 'i':
 
688
        interface = optarg;
 
689
        break;
 
690
      case 'C':
 
691
        connect_to = optarg;
 
692
        break;
 
693
      case 'd':
 
694
        certdir = optarg;
 
695
        break;
 
696
      case 'c':
 
697
        certfile = optarg;
 
698
        break;
 
699
      case 'k':
 
700
        certkey = optarg;
 
701
        break;
 
702
      case 'D':
 
703
        {
 
704
          long int tmp;
 
705
          errno = 0;
 
706
          tmp = strtol(optarg, NULL, 10);
 
707
          if (errno == ERANGE){
 
708
            perror("strtol");
 
709
            exit(EXIT_FAILURE);
 
710
          }
 
711
          mc.dh_bits = tmp;
 
712
        }
 
713
        break;
 
714
      case 'p':
 
715
        mc.priority = optarg;
999
716
        break;
1000
717
      default:
1001
 
        return ARGP_ERR_UNKNOWN;
1002
 
      }
1003
 
      return 0;
1004
 
    }
1005
 
    
1006
 
    struct argp argp = { .options = options, .parser = parse_opt,
1007
 
                         .args_doc = "",
1008
 
                         .doc = "Mandos client -- Get and decrypt"
1009
 
                         " passwords from a Mandos server" };
1010
 
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
1011
 
    if(ret == ARGP_ERR_UNKNOWN){
1012
 
      fprintf(stderr, "Unknown error while parsing arguments\n");
1013
 
      exitcode = EXIT_FAILURE;
1014
 
      goto end;
1015
 
    }
1016
 
  }
1017
 
  
1018
 
  if(not debug){
1019
 
    avahi_set_log_function(empty_log);
1020
 
  }
1021
 
  
1022
 
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1023
 
     from the signal handler */
1024
 
  /* Initialize the pseudo-RNG for Avahi */
1025
 
  srand((unsigned int) time(NULL));
1026
 
  mc.simple_poll = avahi_simple_poll_new();
1027
 
  if(mc.simple_poll == NULL){
1028
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1029
 
    exitcode = EXIT_FAILURE;
1030
 
    goto end;
1031
 
  }
1032
 
  
1033
 
  sigemptyset(&sigterm_action.sa_mask);
1034
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1035
 
  if(ret == -1){
1036
 
    perror("sigaddset");
1037
 
    exitcode = EXIT_FAILURE;
1038
 
    goto end;
1039
 
  }
1040
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1041
 
  if(ret == -1){
1042
 
    perror("sigaddset");
1043
 
    exitcode = EXIT_FAILURE;
1044
 
    goto end;
1045
 
  }
1046
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1047
 
  if(ret == -1){
1048
 
    perror("sigaddset");
1049
 
    exitcode = EXIT_FAILURE;
1050
 
    goto end;
1051
 
  }
1052
 
  ret = sigaction(SIGTERM, &sigterm_action, &old_sigterm_action);
1053
 
  if(ret == -1){
1054
 
    perror("sigaction");
1055
 
    exitcode = EXIT_FAILURE;
1056
 
    goto end;
1057
 
  }  
1058
 
  
1059
 
  /* If the interface is down, bring it up */
1060
 
  if(interface[0] != '\0'){
1061
 
#ifdef __linux__
1062
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1063
 
       messages to mess up the prompt */
1064
 
    ret = klogctl(8, NULL, 5);
1065
 
    bool restore_loglevel = true;
1066
 
    if(ret == -1){
1067
 
      restore_loglevel = false;
1068
 
      perror("klogctl");
1069
 
    }
1070
 
#endif  /* __linux__ */
 
718
        exit(EXIT_FAILURE);
 
719
      }
 
720
    }
 
721
    
 
722
    certfile = combinepath(certdir, certfile);
 
723
    if (certfile == NULL){
 
724
      perror("combinepath");
 
725
      returncode = EXIT_FAILURE;
 
726
      goto exit;
 
727
    }
 
728
 
 
729
    certkey = combinepath(certdir, certkey);
 
730
    if (certkey == NULL){
 
731
      perror("combinepath");
 
732
      returncode = EXIT_FAILURE;
 
733
      goto exit;
 
734
    }
 
735
    
 
736
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
737
    if(if_index == 0){
 
738
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
739
      exit(EXIT_FAILURE);
 
740
    }
 
741
    
 
742
    if(connect_to != NULL){
 
743
      /* Connect directly, do not use Zeroconf */
 
744
      /* (Mainly meant for debugging) */
 
745
      char *address = strrchr(connect_to, ':');
 
746
      if(address == NULL){
 
747
        fprintf(stderr, "No colon in address\n");
 
748
        exit(EXIT_FAILURE);
 
749
      }
 
750
      errno = 0;
 
751
      uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
 
752
      if(errno){
 
753
        perror("Bad port number");
 
754
        exit(EXIT_FAILURE);
 
755
      }
 
756
      *address = '\0';
 
757
      address = connect_to;
 
758
      ret = start_mandos_communication(address, port, if_index);
 
759
      if(ret < 0){
 
760
        exit(EXIT_FAILURE);
 
761
      } else {
 
762
        exit(EXIT_SUCCESS);
 
763
      }
 
764
    }
1071
765
    
1072
766
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1073
 
    if(sd < 0){
 
767
    if(sd < 0) {
1074
768
      perror("socket");
1075
 
      exitcode = EXIT_FAILURE;
1076
 
#ifdef __linux__
1077
 
      if(restore_loglevel){
1078
 
        ret = klogctl(7, NULL, 0);
1079
 
        if(ret == -1){
1080
 
          perror("klogctl");
1081
 
        }
1082
 
      }
1083
 
#endif  /* __linux__ */
1084
 
      goto end;
 
769
      returncode = EXIT_FAILURE;
 
770
      goto exit;
1085
771
    }
1086
 
    strcpy(network.ifr_name, interface);
 
772
    strcpy(network.ifr_name, interface);    
1087
773
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1088
774
    if(ret == -1){
 
775
      
1089
776
      perror("ioctl SIOCGIFFLAGS");
1090
 
#ifdef __linux__
1091
 
      if(restore_loglevel){
1092
 
        ret = klogctl(7, NULL, 0);
1093
 
        if(ret == -1){
1094
 
          perror("klogctl");
1095
 
        }
1096
 
      }
1097
 
#endif  /* __linux__ */
1098
 
      exitcode = EXIT_FAILURE;
1099
 
      goto end;
 
777
      returncode = EXIT_FAILURE;
 
778
      goto exit;
1100
779
    }
1101
780
    if((network.ifr_flags & IFF_UP) == 0){
1102
781
      network.ifr_flags |= IFF_UP;
1103
782
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1104
783
      if(ret == -1){
1105
784
        perror("ioctl SIOCSIFFLAGS");
1106
 
        exitcode = EXIT_FAILURE;
1107
 
#ifdef __linux__
1108
 
        if(restore_loglevel){
1109
 
          ret = klogctl(7, NULL, 0);
1110
 
          if(ret == -1){
1111
 
            perror("klogctl");
1112
 
          }
1113
 
        }
1114
 
#endif  /* __linux__ */
1115
 
        goto end;
1116
 
      }
1117
 
    }
1118
 
    /* sleep checking until interface is running */
1119
 
    for(int i=0; i < delay * 4; i++){
1120
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1121
 
      if(ret == -1){
1122
 
        perror("ioctl SIOCGIFFLAGS");
1123
 
      } else if(network.ifr_flags & IFF_RUNNING){
1124
 
        break;
1125
 
      }
1126
 
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1127
 
      ret = nanosleep(&sleeptime, NULL);
1128
 
      if(ret == -1 and errno != EINTR){
1129
 
        perror("nanosleep");
1130
 
      }
1131
 
    }
1132
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1133
 
    if(ret == -1){
1134
 
      perror("close");
1135
 
    }
1136
 
#ifdef __linux__
1137
 
    if(restore_loglevel){
1138
 
      /* Restores kernel loglevel to default */
1139
 
      ret = klogctl(7, NULL, 0);
1140
 
      if(ret == -1){
1141
 
        perror("klogctl");
1142
 
      }
1143
 
    }
1144
 
#endif  /* __linux__ */
1145
 
  }
1146
 
  
1147
 
  uid = getuid();
1148
 
  gid = getgid();
1149
 
  
1150
 
  errno = 0;
1151
 
  setgid(gid);
1152
 
  if(ret == -1){
1153
 
    perror("setgid");
1154
 
  }
1155
 
  
1156
 
  ret = setuid(uid);
1157
 
  if(ret == -1){
1158
 
    perror("setuid");
1159
 
  }
1160
 
  
1161
 
  ret = init_gnutls_global(pubkey, seckey);
1162
 
  if(ret == -1){
1163
 
    fprintf(stderr, "init_gnutls_global failed\n");
1164
 
    exitcode = EXIT_FAILURE;
1165
 
    goto end;
1166
 
  } else {
1167
 
    gnutls_initialized = true;
1168
 
  }
1169
 
  
1170
 
  if(mkdtemp(tempdir) == NULL){
1171
 
    perror("mkdtemp");
1172
 
    goto end;
1173
 
  }
1174
 
  tempdir_created = true;
1175
 
  
1176
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
1177
 
    fprintf(stderr, "init_gpgme failed\n");
1178
 
    exitcode = EXIT_FAILURE;
1179
 
    goto end;
1180
 
  } else {
1181
 
    gpgme_initialized = true;
1182
 
  }
1183
 
  
1184
 
  if(interface[0] != '\0'){
1185
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1186
 
    if(if_index == 0){
1187
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1188
 
      exitcode = EXIT_FAILURE;
1189
 
      goto end;
1190
 
    }
1191
 
  }
1192
 
  
1193
 
  if(connect_to != NULL){
1194
 
    /* Connect directly, do not use Zeroconf */
1195
 
    /* (Mainly meant for debugging) */
1196
 
    char *address = strrchr(connect_to, ':');
1197
 
    if(address == NULL){
1198
 
      fprintf(stderr, "No colon in address\n");
1199
 
      exitcode = EXIT_FAILURE;
1200
 
      goto end;
1201
 
    }
1202
 
    uint16_t port;
1203
 
    ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
1204
 
    if(ret < 1 or tmpmax != (uint16_t)tmpmax
1205
 
       or address[numchars+1] != '\0'){
1206
 
      fprintf(stderr, "Bad port number\n");
1207
 
      exitcode = EXIT_FAILURE;
1208
 
      goto end;
1209
 
    }
1210
 
    port = (uint16_t)tmpmax;
1211
 
    *address = '\0';
1212
 
    address = connect_to;
1213
 
    /* Colon in address indicates IPv6 */
1214
 
    int af;
1215
 
    if(strchr(address, ':') != NULL){
1216
 
      af = AF_INET6;
1217
 
    } else {
1218
 
      af = AF_INET;
1219
 
    }
1220
 
    ret = start_mandos_communication(address, port, if_index, af);
1221
 
    if(ret < 0){
1222
 
      exitcode = EXIT_FAILURE;
1223
 
    } else {
1224
 
      exitcode = EXIT_SUCCESS;
1225
 
    }
1226
 
    goto end;
1227
 
  }
1228
 
    
1229
 
  {
1230
 
    AvahiServerConfig config;
1231
 
    /* Do not publish any local Zeroconf records */
 
785
        returncode = EXIT_FAILURE;
 
786
        goto exit;
 
787
      }
 
788
    }
 
789
    close(sd);
 
790
    
 
791
    if (not debug){
 
792
      avahi_set_log_function(empty_log);
 
793
    }
 
794
    
 
795
    /* Initialize the psuedo-RNG */
 
796
    srand((unsigned int) time(NULL));
 
797
 
 
798
    /* Allocate main loop object */
 
799
    if (!(mc.simple_poll = avahi_simple_poll_new())) {
 
800
        fprintf(stderr, "Failed to create simple poll object.\n");
 
801
        returncode = EXIT_FAILURE;      
 
802
        goto exit;
 
803
    }
 
804
 
 
805
    /* Do not publish any local records */
1232
806
    avahi_server_config_init(&config);
1233
807
    config.publish_hinfo = 0;
1234
808
    config.publish_addresses = 0;
1235
809
    config.publish_workstation = 0;
1236
810
    config.publish_domain = 0;
1237
 
    
 
811
 
1238
812
    /* Allocate a new server */
1239
 
    mc.server = avahi_server_new(avahi_simple_poll_get
1240
 
                                 (mc.simple_poll), &config, NULL,
1241
 
                                 NULL, &error);
1242
 
    
1243
 
    /* Free the Avahi configuration data */
 
813
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
 
814
                              &config, NULL, NULL, &error);
 
815
 
 
816
    /* Free the configuration data */
1244
817
    avahi_server_config_free(&config);
1245
 
  }
1246
 
  
1247
 
  /* Check if creating the Avahi server object succeeded */
1248
 
  if(mc.server == NULL){
1249
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1250
 
            avahi_strerror(error));
1251
 
    exitcode = EXIT_FAILURE;
1252
 
    goto end;
1253
 
  }
1254
 
  
1255
 
  /* Create the Avahi service browser */
1256
 
  sb = avahi_s_service_browser_new(mc.server, if_index,
1257
 
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
1258
 
                                   NULL, 0, browse_callback, NULL);
1259
 
  if(sb == NULL){
1260
 
    fprintf(stderr, "Failed to create service browser: %s\n",
1261
 
            avahi_strerror(avahi_server_errno(mc.server)));
1262
 
    exitcode = EXIT_FAILURE;
1263
 
    goto end;
1264
 
  }
1265
 
  
1266
 
  /* Run the main loop */
1267
 
  
1268
 
  if(debug){
1269
 
    fprintf(stderr, "Starting Avahi loop search\n");
1270
 
  }
1271
 
  
1272
 
  avahi_simple_poll_loop(mc.simple_poll);
1273
 
  
1274
 
 end:
1275
 
  
1276
 
  if(debug){
1277
 
    fprintf(stderr, "%s exiting\n", argv[0]);
1278
 
  }
1279
 
  
1280
 
  /* Cleanup things */
1281
 
  if(sb != NULL)
1282
 
    avahi_s_service_browser_free(sb);
1283
 
  
1284
 
  if(mc.server != NULL)
1285
 
    avahi_server_free(mc.server);
1286
 
  
1287
 
  if(mc.simple_poll != NULL)
1288
 
    avahi_simple_poll_free(mc.simple_poll);
1289
 
  
1290
 
  if(gnutls_initialized){
1291
 
    gnutls_certificate_free_credentials(mc.cred);
1292
 
    gnutls_global_deinit();
1293
 
    gnutls_dh_params_deinit(mc.dh_params);
1294
 
  }
1295
 
  
1296
 
  if(gpgme_initialized){
1297
 
    gpgme_release(mc.ctx);
1298
 
  }
1299
 
  
1300
 
  /* Removes the temp directory used by GPGME */
1301
 
  if(tempdir_created){
1302
 
    DIR *d;
1303
 
    struct dirent *direntry;
1304
 
    d = opendir(tempdir);
1305
 
    if(d == NULL){
1306
 
      if(errno != ENOENT){
1307
 
        perror("opendir");
1308
 
      }
1309
 
    } else {
1310
 
      while(true){
1311
 
        direntry = readdir(d);
1312
 
        if(direntry == NULL){
1313
 
          break;
1314
 
        }
1315
 
        /* Skip "." and ".." */
1316
 
        if(direntry->d_name[0] == '.'
1317
 
           and (direntry->d_name[1] == '\0'
1318
 
                or (direntry->d_name[1] == '.'
1319
 
                    and direntry->d_name[2] == '\0'))){
1320
 
          continue;
1321
 
        }
1322
 
        char *fullname = NULL;
1323
 
        ret = asprintf(&fullname, "%s/%s", tempdir,
1324
 
                       direntry->d_name);
1325
 
        if(ret < 0){
1326
 
          perror("asprintf");
1327
 
          continue;
1328
 
        }
1329
 
        ret = remove(fullname);
1330
 
        if(ret == -1){
1331
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1332
 
                  strerror(errno));
1333
 
        }
1334
 
        free(fullname);
1335
 
      }
1336
 
      closedir(d);
1337
 
    }
1338
 
    ret = rmdir(tempdir);
1339
 
    if(ret == -1 and errno != ENOENT){
1340
 
      perror("rmdir");
1341
 
    }
1342
 
  }
1343
 
  
1344
 
  return exitcode;
 
818
 
 
819
    /* Check if creating the server object succeeded */
 
820
    if (!mc.server) {
 
821
        fprintf(stderr, "Failed to create server: %s\n",
 
822
                avahi_strerror(error));
 
823
        returncode = EXIT_FAILURE;
 
824
        goto exit;
 
825
    }
 
826
    
 
827
    /* Create the service browser */
 
828
    sb = avahi_s_service_browser_new(mc.server, if_index,
 
829
                                     AVAHI_PROTO_INET6,
 
830
                                     "_mandos._tcp", NULL, 0,
 
831
                                     browse_callback, &mc);
 
832
    if (!sb) {
 
833
        fprintf(stderr, "Failed to create service browser: %s\n",
 
834
                avahi_strerror(avahi_server_errno(mc.server)));
 
835
        returncode = EXIT_FAILURE;
 
836
        goto exit;
 
837
    }
 
838
    
 
839
    /* Run the main loop */
 
840
 
 
841
    if (debug){
 
842
      fprintf(stderr, "Starting avahi loop search\n");
 
843
    }
 
844
    
 
845
    avahi_simple_poll_loop(simple_poll);
 
846
    
 
847
 exit:
 
848
 
 
849
    if (debug){
 
850
      fprintf(stderr, "%s exiting\n", argv[0]);
 
851
    }
 
852
    
 
853
    /* Cleanup things */
 
854
    if (sb)
 
855
        avahi_s_service_browser_free(sb);
 
856
    
 
857
    if (mc.server)
 
858
        avahi_server_free(mc.server);
 
859
 
 
860
    if (simple_poll)
 
861
        avahi_simple_poll_free(simple_poll);
 
862
    free(certfile);
 
863
    free(certkey);
 
864
    
 
865
    return returncode;
1345
866
}