/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

  • Committer: Teddy Hogeborn
  • Date: 2008-08-07 21:45:41 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080807214541-pyg8itw6kphz1dy5
* plugbasedclient.c: Renamed to "mandos-client.c".  All users changed.

* plugins.d/mandosclient.c: Renamed to "plugins.d/password-request.c".
                            All users changed.

* plugins.d/passprompt.c: Renamed to "plugins.d/password-prompt.c".
                          All users changed.

* server.conf: Renamed to "mandos.conf".  All users changed.

* server.py: Renamed to "mandos".
  (daemon): Have default values for arguments. Caller changed.

* Makefile (distclean, mostlyclean, maintainer-clean): New aliases for
                                                       "clean".
  (check, run-client, run-server): New.

* network-protocol.txt: New.

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