/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

Added optional parameters certdir, certkey and certfile that can be iven at start in the command line.

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