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

  • Committer: Teddy Hogeborn
  • Date: 2008-08-03 16:05:52 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080803160552-mvqy5klry3wn57x1
* plugins.d/mandosclient.c (initgnutls): Moved "err" variable into its
                                         own code block.
  (start_mandos_communication): Moved call to "initgnutls" to
                                beginning.  Renamed label "exit" to
                                "mandos_end".  Bug fix: set return
                                code if failure to realloc buffer.
                                Close TLS session as early as
                                possible.
  (resolve_callback): Also print interface number when debugging.
  (main): Moved "debug_int" and "config" into their own respective
          code blocks.

Show diffs side-by-side

added added

removed removed

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