/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-09-03 05:04:40 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080903050440-7cwzxestx6pvdy1i
* Makefile (mandos.8): Add dependency on "overview.xml" and
                       "legalnotice.xml".
  (mandos-keygen.8): New target.
  (mandos-conf.5): Added dependency on "legalnotice.xml".
  (plugin-runner.8mandos): New target
  (plugins.d/password-request.8mandos): - '' -

* mandos-options.xml (priority): Make wording server/client neutral.

* plugins.d/password-request.c (main): Changed .arg fields of the argp
                                       options struct to be more
                                       consistent with the manual.

* plugins.d/password-request.xml (OVERVIEW): Moved to after "OPTIONS".
  (OPTIONS): Improved wording and names of replaceables.

Show diffs side-by-side

added added

removed removed

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