/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

passprompt
        Using argp instead off getopt

Show diffs side-by-side

added added

removed removed

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