/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release

« back to all changes in this revision

Viewing changes to plugins.d/mandos-client.c

* plugin-runner.c (struct plugin.completed): Changed type to "volatile
                                             sig_atomic_t"; all uses
                                             changed.

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