/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/password-request.c

changed from using strtok to strsep

Show diffs side-by-side

added added

removed removed

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