/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/mandos-client.c

small stuff

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 Copyright © 2007-2008 Teddy Hogeborn and Björn
12
 
 * Påhlsson.
 
11
 * Everything else is
 
12
 * Copyright © 2008,2009 Teddy Hogeborn
 
13
 * Copyright © 2008,2009 Björn Påhlsson
13
14
 * 
14
15
 * This program is free software: you can redistribute it and/or
15
16
 * modify it under the terms of the GNU General Public License as
25
26
 * along with this program.  If not, see
26
27
 * <http://www.gnu.org/licenses/>.
27
28
 * 
28
 
 * Contact the authors at <https://www.fukt.bsnet.se/~belorn/> and
29
 
 * <https://www.fukt.bsnet.se/~teddy/>.
 
29
 * Contact the authors at <mandos@fukt.bsnet.se>.
30
30
 */
31
31
 
32
 
#define _FORTIFY_SOURCE 2
33
 
 
 
32
/* Needed by GPGME, specifically gpgme_data_seek() */
34
33
#define _LARGEFILE_SOURCE
35
34
#define _FILE_OFFSET_BITS 64
36
35
 
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, SIOCSIFFLAGS
43
 
#include <net/if.h>             // ioctl, ifreq, SIOCGIFFLAGS, IFF_UP, SIOCSIFFLAGS
44
 
 
 
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_* */
45
83
#include <avahi-core/core.h>
46
84
#include <avahi-core/lookup.h>
47
85
#include <avahi-core/log.h>
49
87
#include <avahi-common/malloc.h>
50
88
#include <avahi-common/error.h>
51
89
 
52
 
//mandos client part
53
 
#include <sys/types.h>          /* socket(), inet_pton() */
54
 
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
55
 
                                   struct in6_addr, inet_pton() */
56
 
#include <gnutls/gnutls.h>      /* All GnuTLS stuff */
57
 
#include <gnutls/openpgp.h>     /* GnuTLS with openpgp stuff */
58
 
 
59
 
#include <unistd.h>             /* close() */
60
 
#include <netinet/in.h>
61
 
#include <stdbool.h>            /* true */
62
 
#include <string.h>             /* memset */
63
 
#include <arpa/inet.h>          /* inet_pton() */
64
 
#include <iso646.h>             /* not */
65
 
 
66
 
// gpgme
67
 
#include <errno.h>              /* perror() */
68
 
#include <gpgme.h>
69
 
 
70
 
// getopt long
71
 
#include <getopt.h>
 
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_* */
72
106
 
73
107
#define BUFFER_SIZE 256
74
 
#define DH_BITS 1024
75
108
 
76
 
const char *certdir = "/conf/conf.d/cryptkeyreq/";
77
 
const char *certfile = "openpgp-client.txt";
78
 
const char *certkey = "openpgp-client-key.txt";
 
109
#define PATHDIR "/conf/conf.d/mandos"
 
110
#define SECKEY "seckey.txt"
 
111
#define PUBKEY "pubkey.txt"
79
112
 
80
113
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>";
81
117
 
 
118
/* Used for passing in values through the Avahi callback functions */
82
119
typedef struct {
83
 
  gnutls_session_t session;
 
120
  AvahiSimplePoll *simple_poll;
 
121
  AvahiServer *server;
84
122
  gnutls_certificate_credentials_t cred;
 
123
  unsigned int dh_bits;
85
124
  gnutls_dh_params_t dh_params;
86
 
} encrypted_session;
87
 
 
88
 
 
89
 
ssize_t pgp_packet_decrypt (char *packet, size_t packet_size,
90
 
                            char **new_packet, const char *homedir){
91
 
  gpgme_data_t dh_crypto, dh_plain;
 
125
  const char *priority;
92
126
  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;
93
152
  gpgme_error_t rc;
94
 
  ssize_t ret;
95
 
  ssize_t new_packet_capacity = 0;
96
 
  ssize_t new_packet_length = 0;
97
153
  gpgme_engine_info_t engine_info;
98
 
 
99
 
  if (debug){
100
 
    fprintf(stderr, "Trying to decrypt OpenPGP packet\n");
 
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");
101
193
  }
102
194
  
103
195
  /* Init GPGME */
104
196
  gpgme_check_version(NULL);
105
197
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
106
 
  if (rc != GPG_ERR_NO_ERROR){
 
198
  if(rc != GPG_ERR_NO_ERROR){
107
199
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
108
200
            gpgme_strsource(rc), gpgme_strerror(rc));
109
 
    return -1;
 
201
    return false;
110
202
  }
111
203
  
112
 
  /* Set GPGME home directory */
113
 
  rc = gpgme_get_engine_info (&engine_info);
114
 
  if (rc != GPG_ERR_NO_ERROR){
 
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){
115
207
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
116
208
            gpgme_strsource(rc), gpgme_strerror(rc));
117
 
    return -1;
 
209
    return false;
118
210
  }
119
211
  while(engine_info != NULL){
120
212
    if(engine_info->protocol == GPGME_PROTOCOL_OpenPGP){
121
213
      gpgme_set_engine_info(GPGME_PROTOCOL_OpenPGP,
122
 
                            engine_info->file_name, homedir);
 
214
                            engine_info->file_name, tempdir);
123
215
      break;
124
216
    }
125
217
    engine_info = engine_info->next;
126
218
  }
127
219
  if(engine_info == NULL){
128
 
    fprintf(stderr, "Could not set home dir to %s\n", homedir);
129
 
    return -1;
130
 
  }
131
 
  
132
 
  /* Create new GPGME data buffer from packet buffer */
133
 
  rc = gpgme_data_new_from_mem(&dh_crypto, packet, packet_size, 0);
134
 
  if (rc != GPG_ERR_NO_ERROR){
 
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){
135
261
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
136
262
            gpgme_strsource(rc), gpgme_strerror(rc));
137
263
    return -1;
139
265
  
140
266
  /* Create new empty GPGME data buffer for the plaintext */
141
267
  rc = gpgme_data_new(&dh_plain);
142
 
  if (rc != GPG_ERR_NO_ERROR){
 
268
  if(rc != GPG_ERR_NO_ERROR){
143
269
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
144
270
            gpgme_strsource(rc), gpgme_strerror(rc));
145
 
    return -1;
146
 
  }
147
 
  
148
 
  /* Create new GPGME "context" */
149
 
  rc = gpgme_new(&ctx);
150
 
  if (rc != GPG_ERR_NO_ERROR){
151
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
152
 
            gpgme_strsource(rc), gpgme_strerror(rc));
153
 
    return -1;
154
 
  }
155
 
  
156
 
  /* Decrypt data from the FILE pointer to the plaintext data
157
 
     buffer */
158
 
  rc = gpgme_op_decrypt(ctx, dh_crypto, dh_plain);
159
 
  if (rc != GPG_ERR_NO_ERROR){
 
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){
160
279
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
161
280
            gpgme_strsource(rc), gpgme_strerror(rc));
162
 
    return -1;
 
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
          }
 
307
        }
 
308
      }
 
309
    }
 
310
    goto decrypt_end;
163
311
  }
164
 
 
 
312
  
165
313
  if(debug){
166
 
    fprintf(stderr, "Decryption of OpenPGP packet succeeded\n");
167
 
  }
168
 
 
169
 
  if (debug){
170
 
    gpgme_decrypt_result_t result;
171
 
    result = gpgme_op_decrypt_result(ctx);
172
 
    if (result == NULL){
173
 
      fprintf(stderr, "gpgme_op_decrypt_result failed\n");
174
 
    } else {
175
 
      fprintf(stderr, "Unsupported algorithm: %s\n",
176
 
              result->unsupported_algorithm);
177
 
      fprintf(stderr, "Wrong key usage: %d\n",
178
 
              result->wrong_key_usage);
179
 
      if(result->file_name != NULL){
180
 
        fprintf(stderr, "File name: %s\n", result->file_name);
181
 
      }
182
 
      gpgme_recipient_t recipient;
183
 
      recipient = result->recipients;
184
 
      if(recipient){
185
 
        while(recipient != NULL){
186
 
          fprintf(stderr, "Public key algorithm: %s\n",
187
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
188
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
189
 
          fprintf(stderr, "Secret key available: %s\n",
190
 
                  recipient->status == GPG_ERR_NO_SECKEY
191
 
                  ? "No" : "Yes");
192
 
          recipient = recipient->next;
193
 
        }
194
 
      }
195
 
    }
196
 
  }
197
 
  
198
 
  /* Delete the GPGME FILE pointer cryptotext data buffer */
199
 
  gpgme_data_release(dh_crypto);
 
314
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
315
  }
200
316
  
201
317
  /* Seek back to the beginning of the GPGME plaintext data buffer */
202
 
  if (gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET) == -1){
203
 
    perror("pgpme_data_seek");
 
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;
204
322
  }
205
323
  
206
 
  *new_packet = 0;
 
324
  *plaintext = NULL;
207
325
  while(true){
208
 
    if (new_packet_length + BUFFER_SIZE > new_packet_capacity){
209
 
      *new_packet = realloc(*new_packet,
210
 
                            (unsigned int)new_packet_capacity
211
 
                            + BUFFER_SIZE);
212
 
      if (*new_packet == NULL){
213
 
        perror("realloc");
214
 
        return -1;
215
 
      }
216
 
      new_packet_capacity += BUFFER_SIZE;
 
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;
217
333
    }
218
334
    
219
 
    ret = gpgme_data_read(dh_plain, *new_packet + new_packet_length,
 
335
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
220
336
                          BUFFER_SIZE);
221
337
    /* Print the data, if any */
222
 
    if (ret == 0){
 
338
    if(ret == 0){
 
339
      /* EOF */
223
340
      break;
224
341
    }
225
342
    if(ret < 0){
226
343
      perror("gpgme_data_read");
227
 
      return -1;
228
 
    }
229
 
    new_packet_length += ret;
230
 
  }
231
 
 
232
 
  /* FIXME: check characters before printing to screen so to not print
233
 
     terminal control characters */
234
 
  /*   if(debug){ */
235
 
  /*     fprintf(stderr, "decrypted password is: "); */
236
 
  /*     fwrite(*new_packet, 1, new_packet_length, stderr); */
237
 
  /*     fprintf(stderr, "\n"); */
238
 
  /*   } */
 
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);
239
362
  
240
363
  /* Delete the GPGME plaintext data buffer */
241
364
  gpgme_data_release(dh_plain);
242
 
  return new_packet_length;
 
365
  return plaintext_length;
243
366
}
244
367
 
245
 
static const char * safer_gnutls_strerror (int value) {
246
 
  const char *ret = gnutls_strerror (value);
247
 
  if (ret == NULL)
 
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)
248
372
    ret = "(unknown)";
249
373
  return ret;
250
374
}
251
375
 
252
 
void debuggnutls(__attribute__((unused)) int level,
253
 
                 const char* string){
254
 
  fprintf(stderr, "%s", string);
 
376
/* GnuTLS log function callback */
 
377
static void debuggnutls(__attribute__((unused)) int level,
 
378
                        const char* string){
 
379
  fprintf(stderr, "GnuTLS: %s", string);
255
380
}
256
381
 
257
 
int initgnutls(encrypted_session *es){
258
 
  const char *err;
 
382
static int init_gnutls_global(mandos_context *mc,
 
383
                              const char *pubkeyfilename,
 
384
                              const char *seckeyfilename){
259
385
  int ret;
260
386
  
261
387
  if(debug){
262
388
    fprintf(stderr, "Initializing GnuTLS\n");
263
389
  }
264
 
 
265
 
  if ((ret = gnutls_global_init ())
266
 
      != GNUTLS_E_SUCCESS) {
267
 
    fprintf (stderr, "global_init: %s\n", safer_gnutls_strerror(ret));
 
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));
268
395
    return -1;
269
396
  }
270
 
 
271
 
  if (debug){
 
397
  
 
398
  if(debug){
 
399
    /* "Use a log level over 10 to enable all debugging options."
 
400
     * - GnuTLS manual
 
401
     */
272
402
    gnutls_global_set_log_level(11);
273
403
    gnutls_global_set_log_function(debuggnutls);
274
404
  }
275
405
  
276
 
  /* openpgp credentials */
277
 
  if ((ret = gnutls_certificate_allocate_credentials (&es->cred))
278
 
      != GNUTLS_E_SUCCESS) {
279
 
    fprintf (stderr, "memory error: %s\n",
280
 
             safer_gnutls_strerror(ret));
 
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();
281
415
    return -1;
282
416
  }
283
417
  
284
418
  if(debug){
285
 
    fprintf(stderr, "Attempting to use OpenPGP certificate %s"
286
 
            " and keyfile %s as GnuTLS credentials\n", certfile,
287
 
            certkey);
 
419
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
420
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
 
421
            seckeyfilename);
288
422
  }
289
423
  
290
424
  ret = gnutls_certificate_set_openpgp_key_file
291
 
    (es->cred, certfile, certkey, GNUTLS_OPENPGP_FMT_BASE64);
292
 
  if (ret != GNUTLS_E_SUCCESS) {
293
 
    fprintf
294
 
      (stderr, "Error[%d] while reading the OpenPGP key pair ('%s',"
295
 
       " '%s')\n",
296
 
       ret, certfile, certkey);
297
 
    fprintf(stdout, "The Error is: %s\n",
298
 
            safer_gnutls_strerror(ret));
299
 
    return -1;
300
 
  }
301
 
  
302
 
  //GnuTLS server initialization
303
 
  if ((ret = gnutls_dh_params_init (&es->dh_params))
304
 
      != GNUTLS_E_SUCCESS) {
305
 
    fprintf (stderr, "Error in dh parameter initialization: %s\n",
306
 
             safer_gnutls_strerror(ret));
307
 
    return -1;
308
 
  }
309
 
  
310
 
  if ((ret = gnutls_dh_params_generate2 (es->dh_params, DH_BITS))
311
 
      != GNUTLS_E_SUCCESS) {
312
 
    fprintf (stderr, "Error in prime generation: %s\n",
313
 
             safer_gnutls_strerror(ret));
314
 
    return -1;
315
 
  }
316
 
  
317
 
  gnutls_certificate_set_dh_params (es->cred, es->dh_params);
318
 
  
319
 
  // GnuTLS session creation
320
 
  if ((ret = gnutls_init (&es->session, GNUTLS_SERVER))
321
 
      != GNUTLS_E_SUCCESS){
 
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){
322
468
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
323
469
            safer_gnutls_strerror(ret));
324
470
  }
325
471
  
326
 
  if ((ret = gnutls_priority_set_direct (es->session, "NORMAL", &err))
327
 
      != GNUTLS_E_SUCCESS) {
328
 
    fprintf(stderr, "Syntax error at: %s\n", err);
329
 
    fprintf(stderr, "GnuTLS error: %s\n",
330
 
            safer_gnutls_strerror(ret));
331
 
    return -1;
 
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
    }
332
482
  }
333
483
  
334
 
  if ((ret = gnutls_credentials_set
335
 
       (es->session, GNUTLS_CRD_CERTIFICATE, es->cred))
336
 
      != GNUTLS_E_SUCCESS) {
337
 
    fprintf(stderr, "Error setting a credentials set: %s\n",
 
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",
338
488
            safer_gnutls_strerror(ret));
 
489
    gnutls_deinit(*session);
339
490
    return -1;
340
491
  }
341
492
  
342
493
  /* ignore client certificate if any. */
343
 
  gnutls_certificate_server_set_request (es->session,
344
 
                                         GNUTLS_CERT_IGNORE);
 
494
  gnutls_certificate_server_set_request(*session,
 
495
                                        GNUTLS_CERT_IGNORE);
345
496
  
346
 
  gnutls_dh_set_prime_bits (es->session, DH_BITS);
 
497
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
347
498
  
348
499
  return 0;
349
500
}
350
501
 
351
 
void empty_log(__attribute__((unused)) AvahiLogLevel level,
352
 
               __attribute__((unused)) const char *txt){}
 
502
/* Avahi log function callback */
 
503
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
 
504
                      __attribute__((unused)) const char *txt){}
353
505
 
354
 
int start_mandos_communication(const char *ip, uint16_t port,
355
 
                               unsigned int if_index){
 
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){
356
510
  int ret, tcp_sd;
357
 
  struct sockaddr_in6 to;
358
 
  encrypted_session es;
 
511
  ssize_t sret;
 
512
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
359
513
  char *buffer = NULL;
360
514
  char *decrypted_buffer;
361
515
  size_t buffer_length = 0;
362
516
  size_t buffer_capacity = 0;
363
517
  ssize_t decrypted_buffer_size;
364
 
  size_t written = 0;
 
518
  size_t written;
365
519
  int retval = 0;
366
520
  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
  }
367
527
  
368
528
  if(debug){
369
 
    fprintf(stderr, "Setting up a tcp connection to %s\n", ip);
 
529
    fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
 
530
            "\n", ip, port);
370
531
  }
371
532
  
372
533
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
374
535
    perror("socket");
375
536
    return -1;
376
537
  }
377
 
 
 
538
  
378
539
  if(debug){
379
 
    if(if_indextoname(if_index, interface) == NULL){
380
 
      if(debug){
381
 
        perror("if_indextoname");
382
 
      }
 
540
    if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
541
      perror("if_indextoname");
383
542
      return -1;
384
543
    }
385
 
    
386
544
    fprintf(stderr, "Binding to interface %s\n", interface);
387
545
  }
388
546
  
389
 
  memset(&to,0,sizeof(to));     /* Spurious warning */
390
 
  to.sin6_family = AF_INET6;
391
 
  ret = inet_pton(AF_INET6, ip, &to.sin6_addr);
392
 
  if (ret < 0 ){
 
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 ){
393
553
    perror("inet_pton");
394
554
    return -1;
395
 
  }  
 
555
  }
396
556
  if(ret == 0){
397
557
    fprintf(stderr, "Bad address: %s\n", ip);
398
558
    return -1;
399
559
  }
400
 
  to.sin6_port = htons(port);   /* Spurious warning */
 
560
  to.in6.sin6_port = htons(port); /* Spurious warnings from
 
561
                                     -Wconversion and
 
562
                                     -Wunreachable-code */
401
563
  
402
 
  to.sin6_scope_id = (uint32_t)if_index;
 
564
  to.in6.sin6_scope_id = (uint32_t)if_index;
403
565
  
404
566
  if(debug){
405
 
    fprintf(stderr, "Connection to: %s\n", ip);
 
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
    }
406
578
  }
407
579
  
408
 
  ret = connect(tcp_sd, (struct sockaddr *) &to, sizeof(to));
409
 
  if (ret < 0){
 
580
  ret = connect(tcp_sd, &to.in, sizeof(to));
 
581
  if(ret < 0){
410
582
    perror("connect");
411
583
    return -1;
412
584
  }
413
585
  
414
 
  ret = initgnutls (&es);
415
 
  if (ret != 0){
416
 
    retval = -1;
417
 
    return -1;
 
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
    }
418
608
  }
419
609
  
420
 
  gnutls_transport_set_ptr (es.session,
421
 
                            (gnutls_transport_ptr_t) tcp_sd);
422
 
  
423
610
  if(debug){
424
611
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
425
612
  }
426
613
  
427
 
  ret = gnutls_handshake (es.session);
428
 
  
429
 
  if (ret != GNUTLS_E_SUCCESS){
 
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){
430
621
    if(debug){
431
 
      fprintf(stderr, "\n*** Handshake failed ***\n");
432
 
      gnutls_perror (ret);
 
622
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
623
      gnutls_perror(ret);
433
624
    }
434
625
    retval = -1;
435
 
    goto exit;
 
626
    goto mandos_end;
436
627
  }
437
628
  
438
 
  //Retrieve OpenPGP packet that contains the wanted password
 
629
  /* Read OpenPGP packet that contains the wanted password */
439
630
  
440
631
  if(debug){
441
632
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
442
633
            ip);
443
634
  }
444
 
 
 
635
  
445
636
  while(true){
446
 
    if (buffer_length + BUFFER_SIZE > buffer_capacity){
447
 
      buffer = realloc(buffer, buffer_capacity + BUFFER_SIZE);
448
 
      if (buffer == NULL){
449
 
        perror("realloc");
450
 
        goto exit;
451
 
      }
452
 
      buffer_capacity += BUFFER_SIZE;
 
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;
453
643
    }
454
644
    
455
 
    ret = gnutls_record_recv
456
 
      (es.session, buffer+buffer_length, BUFFER_SIZE);
457
 
    if (ret == 0){
 
645
    sret = gnutls_record_recv(session, buffer+buffer_length,
 
646
                              BUFFER_SIZE);
 
647
    if(sret == 0){
458
648
      break;
459
649
    }
460
 
    if (ret < 0){
461
 
      switch(ret){
 
650
    if(sret < 0){
 
651
      switch(sret){
462
652
      case GNUTLS_E_INTERRUPTED:
463
653
      case GNUTLS_E_AGAIN:
464
654
        break;
465
655
      case GNUTLS_E_REHANDSHAKE:
466
 
        ret = gnutls_handshake (es.session);
467
 
        if (ret < 0){
468
 
          fprintf(stderr, "\n*** Handshake failed ***\n");
469
 
          gnutls_perror (ret);
 
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);
470
662
          retval = -1;
471
 
          goto exit;
 
663
          goto mandos_end;
472
664
        }
473
665
        break;
474
666
      default:
475
667
        fprintf(stderr, "Unknown error while reading data from"
476
 
                " encrypted session with mandos server\n");
 
668
                " encrypted session with Mandos server\n");
477
669
        retval = -1;
478
 
        gnutls_bye (es.session, GNUTLS_SHUT_RDWR);
479
 
        goto exit;
 
670
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
671
        goto mandos_end;
480
672
      }
481
673
    } else {
482
 
      buffer_length += (size_t) ret;
 
674
      buffer_length += (size_t) sret;
483
675
    }
484
676
  }
485
677
  
486
 
  if (buffer_length > 0){
487
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
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,
488
686
                                               buffer_length,
489
 
                                               &decrypted_buffer,
490
 
                                               certdir);
491
 
    if (decrypted_buffer_size >= 0){
492
 
      while(written < (size_t)decrypted_buffer_size){
493
 
        ret = (int)fwrite (decrypted_buffer + written, 1,
494
 
                           (size_t)decrypted_buffer_size - written,
495
 
                           stdout);
 
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);
496
694
        if(ret == 0 and ferror(stdout)){
497
695
          if(debug){
498
696
            fprintf(stderr, "Error writing encrypted data: %s\n",
507
705
    } else {
508
706
      retval = -1;
509
707
    }
510
 
  }
511
 
 
512
 
  //shutdown procedure
513
 
 
514
 
  if(debug){
515
 
    fprintf(stderr, "Closing TLS session\n");
516
 
  }
517
 
 
 
708
  } else {
 
709
    retval = -1;
 
710
  }
 
711
  
 
712
  /* Shutdown procedure */
 
713
  
 
714
 mandos_end:
518
715
  free(buffer);
519
 
  gnutls_bye (es.session, GNUTLS_SHUT_RDWR);
520
 
 exit:
521
 
  close(tcp_sd);
522
 
  gnutls_deinit (es.session);
523
 
  gnutls_certificate_free_credentials (es.cred);
524
 
  gnutls_global_deinit ();
 
716
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
717
  if(ret == -1){
 
718
    perror("close");
 
719
  }
 
720
  gnutls_deinit(session);
525
721
  return retval;
526
722
}
527
723
 
528
 
static AvahiSimplePoll *simple_poll = NULL;
529
 
static AvahiServer *server = NULL;
530
 
 
531
 
static void resolve_callback(
532
 
    AvahiSServiceResolver *r,
533
 
    AvahiIfIndex interface,
534
 
    AVAHI_GCC_UNUSED AvahiProtocol protocol,
535
 
    AvahiResolverEvent event,
536
 
    const char *name,
537
 
    const char *type,
538
 
    const char *domain,
539
 
    const char *host_name,
540
 
    const AvahiAddress *address,
541
 
    uint16_t port,
542
 
    AVAHI_GCC_UNUSED AvahiStringList *txt,
543
 
    AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
544
 
    AVAHI_GCC_UNUSED void* userdata) {
545
 
    
546
 
  assert(r);                    /* Spurious warning */
 
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);
547
740
  
548
741
  /* Called whenever a service has been resolved successfully or
549
742
     timed out */
550
743
  
551
 
  switch (event) {
 
744
  switch(event) {
552
745
  default:
553
746
  case AVAHI_RESOLVER_FAILURE:
554
 
    fprintf(stderr, "(Resolver) Failed to resolve service '%s' of"
555
 
            " type '%s' in domain '%s': %s\n", name, type, domain,
556
 
            avahi_strerror(avahi_server_errno(server)));
 
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)));
557
750
    break;
558
751
    
559
752
  case AVAHI_RESOLVER_FOUND:
561
754
      char ip[AVAHI_ADDRESS_STR_MAX];
562
755
      avahi_address_snprint(ip, sizeof(ip), address);
563
756
      if(debug){
564
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s) on"
565
 
                " port %d\n", name, host_name, ip, port);
 
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);
566
760
      }
567
 
      int ret = start_mandos_communication(ip, port,
568
 
                                           (unsigned int) interface);
569
 
      if (ret == 0){
570
 
        exit(EXIT_SUCCESS);
 
761
      int ret = start_mandos_communication(ip, port, interface, mc);
 
762
      if(ret == 0){
 
763
        avahi_simple_poll_quit(mc->simple_poll);
571
764
      }
572
765
    }
573
766
  }
574
767
  avahi_s_service_resolver_free(r);
575
768
}
576
769
 
577
 
static void browse_callback(
578
 
    AvahiSServiceBrowser *b,
579
 
    AvahiIfIndex interface,
580
 
    AvahiProtocol protocol,
581
 
    AvahiBrowserEvent event,
582
 
    const char *name,
583
 
    const char *type,
584
 
    const char *domain,
585
 
    AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
586
 
    void* userdata) {
587
 
    
588
 
    AvahiServer *s = userdata;
589
 
    assert(b);                  /* Spurious warning */
590
 
    
591
 
    /* Called whenever a new services becomes available on the LAN or
592
 
       is removed from the LAN */
593
 
    
594
 
    switch (event) {
595
 
    default:
596
 
    case AVAHI_BROWSER_FAILURE:
597
 
      
598
 
      fprintf(stderr, "(Browser) %s\n",
599
 
              avahi_strerror(avahi_server_errno(server)));
600
 
      avahi_simple_poll_quit(simple_poll);
601
 
      return;
602
 
      
603
 
    case AVAHI_BROWSER_NEW:
604
 
      /* We ignore the returned resolver object. In the callback
605
 
         function we free it. If the server is terminated before
606
 
         the callback function is called the server will free
607
 
         the resolver for us. */
608
 
      
609
 
      if (!(avahi_s_service_resolver_new(s, interface, protocol, name,
610
 
                                         type, domain,
611
 
                                         AVAHI_PROTO_INET6, 0,
612
 
                                         resolve_callback, s)))
613
 
        fprintf(stderr, "Failed to resolve service '%s': %s\n", name,
614
 
                avahi_strerror(avahi_server_errno(s)));
615
 
      break;
616
 
      
617
 
    case AVAHI_BROWSER_REMOVE:
618
 
      break;
619
 
      
620
 
    case AVAHI_BROWSER_ALL_FOR_NOW:
621
 
    case AVAHI_BROWSER_CACHE_EXHAUSTED:
622
 
      break;
 
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");
623
816
    }
624
 
}
625
 
 
626
 
/* combinds file name and path and returns the malloced new string. som sane checks could/should be added */
627
 
const char *combinepath(const char *first, const char *second){
628
 
  char *tmp;
629
 
  tmp = malloc(strlen(first) + strlen(second) + 2);
630
 
  if (tmp == NULL){
631
 
    perror("malloc");
632
 
    return NULL;
633
 
  }
634
 
  strcpy(tmp, first);
635
 
  if (first[0] != '\0' and first[strlen(first) - 1] != '/'){
636
 
    strcat(tmp, "/");
637
 
  }
638
 
  strcat(tmp, second);
639
 
  return tmp;
640
 
}
641
 
 
642
 
 
643
 
int main(AVAHI_GCC_UNUSED int argc, AVAHI_GCC_UNUSED char*argv[]) {
644
 
    AvahiServerConfig config;
 
817
    break;
 
818
  }
 
819
}
 
820
 
 
821
int main(int argc, char *argv[]){
645
822
    AvahiSServiceBrowser *sb = NULL;
646
823
    int error;
647
824
    int ret;
648
 
    int returncode = EXIT_SUCCESS;
 
825
    intmax_t tmpmax;
 
826
    int numchars;
 
827
    int exitcode = EXIT_SUCCESS;
649
828
    const char *interface = "eth0";
650
829
    struct ifreq network;
651
830
    int sd;
652
 
    
653
 
    while (true){
654
 
      static struct option long_options[] = {
655
 
        {"debug", no_argument, (int *)&debug, 1},
656
 
        {"interface", required_argument, 0, 'i'},
657
 
        {"certdir", required_argument, 0, 'd'},
658
 
        {"certkey", required_argument, 0, 'c'},
659
 
        {"certfile", required_argument, 0, 'k'},
660
 
        {0, 0, 0, 0} };
661
 
      
662
 
      int option_index = 0;
663
 
      ret = getopt_long (argc, argv, "i:", long_options,
664
 
                         &option_index);
665
 
      
666
 
      if (ret == -1){
667
 
        break;
668
 
      }
669
 
      
670
 
      switch(ret){
671
 
      case 0:
672
 
        break;
673
 
      case 'i':
674
 
        interface = optarg;
675
 
        break;
676
 
      case 'd':
677
 
        certdir = optarg;
678
 
        break;
679
 
      case 'c':
680
 
        certfile = optarg;
681
 
        break;
682
 
      case 'k':
683
 
        certkey = optarg;
684
 
        break;
685
 
      default:
686
 
        exit(EXIT_FAILURE);
687
 
      }
688
 
    }
689
 
 
690
 
    certfile = combinepath(certdir, certfile);
691
 
    if (certfile == NULL){
692
 
      returncode = EXIT_FAILURE;
693
 
      goto exit;
694
 
    }
695
 
    
696
 
    certkey = combinepath(certdir, certkey);
697
 
    if (certkey == NULL){
698
 
      returncode = EXIT_FAILURE;
699
 
      goto exit;
700
 
    }
701
 
 
702
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
703
 
    if(sd < 0) {
704
 
      perror("socket");
705
 
      returncode = EXIT_FAILURE;
706
 
      goto exit;
707
 
    }
708
 
    strcpy(network.ifr_name, interface);    
709
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
710
 
    if(ret == -1){
711
 
      
712
 
      perror("ioctl SIOCGIFFLAGS");
713
 
      returncode = EXIT_FAILURE;
714
 
      goto exit;
715
 
    }
716
 
    if((network.ifr_flags & IFF_UP) == 0){
717
 
      network.ifr_flags |= IFF_UP;
718
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
719
 
      if(ret == -1){
720
 
        perror("ioctl SIOCSIFFLAGS");
721
 
        returncode = EXIT_FAILURE;
722
 
        goto exit;
723
 
      }
724
 
    }
725
 
    close(sd);
726
 
    
727
 
    if (not debug){
 
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;
 
928
      }
 
929
      
 
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;
 
939
      }
 
940
    }
 
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
 
 
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){
728
1079
      avahi_set_log_function(empty_log);
729
1080
    }
730
1081
    
731
 
    /* Initialize the psuedo-RNG */
 
1082
    /* Initialize the pseudo-RNG for Avahi */
732
1083
    srand((unsigned int) time(NULL));
733
 
 
734
 
    /* Allocate main loop object */
735
 
    if (!(simple_poll = avahi_simple_poll_new())) {
736
 
        fprintf(stderr, "Failed to create simple poll object.\n");
737
 
        returncode = EXIT_FAILURE;      
738
 
        goto exit;
739
 
    }
740
 
 
741
 
    /* Do not publish any local records */
742
 
    avahi_server_config_init(&config);
743
 
    config.publish_hinfo = 0;
744
 
    config.publish_addresses = 0;
745
 
    config.publish_workstation = 0;
746
 
    config.publish_domain = 0;
747
 
 
748
 
    /* Allocate a new server */
749
 
    server = avahi_server_new(avahi_simple_poll_get(simple_poll),
750
 
                              &config, NULL, NULL, &error);
751
 
 
752
 
    /* Free the configuration data */
753
 
    avahi_server_config_free(&config);
754
 
 
755
 
    /* Check if creating the server object succeeded */
756
 
    if (!server) {
757
 
        fprintf(stderr, "Failed to create server: %s\n",
 
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",
758
1115
                avahi_strerror(error));
759
 
        returncode = EXIT_FAILURE;
760
 
        goto exit;
 
1116
        exitcode = EXIT_FAILURE;
 
1117
        goto end;
761
1118
    }
762
1119
    
763
 
    /* Create the service browser */
764
 
    sb = avahi_s_service_browser_new(server,
765
 
                                     (AvahiIfIndex)
766
 
                                     if_nametoindex(interface),
 
1120
    /* Create the Avahi service browser */
 
1121
    sb = avahi_s_service_browser_new(mc.server, if_index,
767
1122
                                     AVAHI_PROTO_INET6,
768
1123
                                     "_mandos._tcp", NULL, 0,
769
 
                                     browse_callback, server);
770
 
    if (!sb) {
 
1124
                                     browse_callback, &mc);
 
1125
    if(sb == NULL) {
771
1126
        fprintf(stderr, "Failed to create service browser: %s\n",
772
 
                avahi_strerror(avahi_server_errno(server)));
773
 
        returncode = EXIT_FAILURE;
774
 
        goto exit;
 
1127
                avahi_strerror(avahi_server_errno(mc.server)));
 
1128
        exitcode = EXIT_FAILURE;
 
1129
        goto end;
775
1130
    }
776
1131
    
777
1132
    /* Run the main loop */
778
 
 
779
 
    if (debug){
780
 
      fprintf(stderr, "Starting avahi loop search\n");
 
1133
    
 
1134
    if(debug){
 
1135
      fprintf(stderr, "Starting Avahi loop search\n");
781
1136
    }
782
 
    
783
 
    avahi_simple_poll_loop(simple_poll);
784
 
    
785
 
 exit:
786
1137
 
787
 
    if (debug){
 
1138
    avahi_simple_poll_loop(mc.simple_poll);
 
1139
    
 
1140
 end:
 
1141
    
 
1142
    if(debug){
788
1143
      fprintf(stderr, "%s exiting\n", argv[0]);
789
1144
    }
790
1145
    
791
1146
    /* Cleanup things */
792
 
    if (sb)
 
1147
    if(sb != NULL)
793
1148
        avahi_s_service_browser_free(sb);
794
1149
    
795
 
    if (server)
796
 
        avahi_server_free(server);
797
 
 
798
 
    if (simple_poll)
799
 
        avahi_simple_poll_free(simple_poll);
800
 
    free(certfile);
801
 
    free(certkey);
802
 
    
803
 
    return returncode;
 
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;
804
1206
}