/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

plugbasedclient
        Parse a single argument as a plus-separated list of options

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/*  -*- coding: utf-8 -*- */
2
2
/*
3
 
 * Mandos-client - get and decrypt data from a Mandos server
 
3
 * Mandos client - get and decrypt data from a Mandos server
4
4
 *
5
5
 * This program is partly derived from an example program for an Avahi
6
6
 * service browser, downloaded from
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2010 Teddy Hogeborn
13
 
 * Copyright © 2008-2010 Björn Påhlsson
 
12
 * Copyright © 2007-2008 Teddy Hogeborn & Björn Påhlsson
14
13
 * 
15
14
 * This program is free software: you can redistribute it and/or
16
15
 * modify it under the terms of the GNU General Public License as
30
29
 */
31
30
 
32
31
/* Needed by GPGME, specifically gpgme_data_seek() */
33
 
#ifndef _LARGEFILE_SOURCE
34
32
#define _LARGEFILE_SOURCE
35
 
#endif
36
 
#ifndef _FILE_OFFSET_BITS
37
33
#define _FILE_OFFSET_BITS 64
38
 
#endif
39
 
 
40
 
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
41
 
 
42
 
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
 
                                   stdout, ferror(), remove() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t */
45
 
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
 
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
 
                                   strtof(), abort() */
48
 
#include <stdbool.h>            /* bool, false, true */
49
 
#include <string.h>             /* memset(), strcmp(), strlen(),
50
 
                                   strerror(), asprintf(), strcpy() */
51
 
#include <sys/ioctl.h>          /* ioctl */
52
 
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
53
 
                                   sockaddr_in6, PF_INET6,
54
 
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
 
                                   opendir(), DIR */
56
 
#include <sys/stat.h>           /* open() */
57
 
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
 
                                   inet_pton(), connect() */
59
 
#include <fcntl.h>              /* open() */
60
 
#include <dirent.h>             /* opendir(), struct dirent, readdir()
61
 
                                 */
62
 
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
 
                                   strtoimax() */
64
 
#include <assert.h>             /* assert() */
65
 
#include <errno.h>              /* perror(), errno */
66
 
#include <time.h>               /* nanosleep(), time(), sleep() */
67
 
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
68
 
                                   SIOCSIFFLAGS, if_indextoname(),
69
 
                                   if_nametoindex(), IF_NAMESIZE */
70
 
#include <netinet/in.h>         /* IN6_IS_ADDR_LINKLOCAL,
71
 
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
72
 
                                */
73
 
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
74
 
                                   getuid(), getgid(), seteuid(),
75
 
                                   setgid(), pause() */
76
 
#include <arpa/inet.h>          /* inet_pton(), htons */
77
 
#include <iso646.h>             /* not, or, and */
78
 
#include <argp.h>               /* struct argp_option, error_t, struct
79
 
                                   argp_state, struct argp,
80
 
                                   argp_parse(), ARGP_KEY_ARG,
81
 
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
82
 
#include <signal.h>             /* sigemptyset(), sigaddset(),
83
 
                                   sigaction(), SIGTERM, sig_atomic_t,
84
 
                                   raise() */
85
 
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
86
 
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
87
 
 
88
 
#ifdef __linux__
89
 
#include <sys/klog.h>           /* klogctl() */
90
 
#endif  /* __linux__ */
91
 
 
92
 
/* Avahi */
93
 
/* All Avahi types, constants and functions
94
 
 Avahi*, avahi_*,
95
 
 AVAHI_* */
 
34
 
 
35
#include <stdio.h>
 
36
#include <assert.h>
 
37
#include <stdlib.h>
 
38
#include <time.h>
 
39
#include <net/if.h>             /* if_nametoindex */
 
40
#include <sys/ioctl.h>          // ioctl, ifreq, SIOCGIFFLAGS, IFF_UP, SIOCSIFFLAGS
 
41
#include <net/if.h>             // ioctl, ifreq, SIOCGIFFLAGS, IFF_UP, SIOCSIFFLAGS
 
42
 
96
43
#include <avahi-core/core.h>
97
44
#include <avahi-core/lookup.h>
98
45
#include <avahi-core/log.h>
100
47
#include <avahi-common/malloc.h>
101
48
#include <avahi-common/error.h>
102
49
 
103
 
/* GnuTLS */
104
 
#include <gnutls/gnutls.h>      /* All GnuTLS types, constants and
105
 
                                   functions:
106
 
                                   gnutls_*
107
 
                                   init_gnutls_session(),
108
 
                                   GNUTLS_* */
109
 
#include <gnutls/openpgp.h>
110
 
                          /* gnutls_certificate_set_openpgp_key_file(),
111
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
112
 
 
113
 
/* GPGME */
114
 
#include <gpgme.h>              /* All GPGME types, constants and
115
 
                                   functions:
116
 
                                   gpgme_*
117
 
                                   GPGME_PROTOCOL_OpenPGP,
118
 
                                   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>
119
70
 
120
71
#define BUFFER_SIZE 256
 
72
#define DH_BITS 1024
121
73
 
122
 
#define PATHDIR "/conf/conf.d/mandos"
123
 
#define SECKEY "seckey.txt"
124
 
#define PUBKEY "pubkey.txt"
 
74
static const char *certdir = "/conf/conf.d/mandos";
 
75
static const char *certfile = "openpgp-client.txt";
 
76
static const char *certkey = "openpgp-client-key.txt";
125
77
 
126
78
bool debug = false;
127
 
static const char mandos_protocol_version[] = "1";
128
 
const char *argp_program_version = "mandos-client " VERSION;
129
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
130
 
static const char sys_class_net[] = "/sys/class/net";
131
 
char *connect_to = NULL;
132
79
 
133
 
/* Used for passing in values through the Avahi callback functions */
134
80
typedef struct {
135
 
  AvahiSimplePoll *simple_poll;
136
 
  AvahiServer *server;
 
81
  gnutls_session_t session;
137
82
  gnutls_certificate_credentials_t cred;
138
 
  unsigned int dh_bits;
139
83
  gnutls_dh_params_t dh_params;
140
 
  const char *priority;
 
84
} encrypted_session;
 
85
 
 
86
 
 
87
static ssize_t pgp_packet_decrypt (char *packet, size_t packet_size,
 
88
                                   char **new_packet,
 
89
                                   const char *homedir){
 
90
  gpgme_data_t dh_crypto, dh_plain;
141
91
  gpgme_ctx_t ctx;
142
 
} mandos_context;
143
 
 
144
 
/* global context so signal handler can reach it*/
145
 
mandos_context mc = { .simple_poll = NULL, .server = NULL,
146
 
                      .dh_bits = 1024, .priority = "SECURE256"
147
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
148
 
 
149
 
sig_atomic_t quit_now = 0;
150
 
int signal_received = 0;
151
 
 
152
 
/*
153
 
 * Make additional room in "buffer" for at least BUFFER_SIZE more
154
 
 * bytes. "buffer_capacity" is how much is currently allocated,
155
 
 * "buffer_length" is how much is already used.
156
 
 */
157
 
size_t incbuffer(char **buffer, size_t buffer_length,
158
 
                  size_t buffer_capacity){
159
 
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
160
 
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
161
 
    if(buffer == NULL){
162
 
      return 0;
163
 
    }
164
 
    buffer_capacity += BUFFER_SIZE;
165
 
  }
166
 
  return buffer_capacity;
167
 
}
168
 
 
169
 
/* 
170
 
 * Initialize GPGME.
171
 
 */
172
 
static bool init_gpgme(const char *seckey,
173
 
                       const char *pubkey, const char *tempdir){
174
92
  gpgme_error_t rc;
 
93
  ssize_t ret;
 
94
  ssize_t new_packet_capacity = 0;
 
95
  ssize_t new_packet_length = 0;
175
96
  gpgme_engine_info_t engine_info;
176
 
  
177
 
  
178
 
  /*
179
 
   * Helper function to insert pub and seckey to the engine keyring.
180
 
   */
181
 
  bool import_key(const char *filename){
182
 
    int ret;
183
 
    int fd;
184
 
    gpgme_data_t pgp_data;
185
 
    
186
 
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
187
 
    if(fd == -1){
188
 
      perror("open");
189
 
      return false;
190
 
    }
191
 
    
192
 
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
193
 
    if(rc != GPG_ERR_NO_ERROR){
194
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
195
 
              gpgme_strsource(rc), gpgme_strerror(rc));
196
 
      return false;
197
 
    }
198
 
    
199
 
    rc = gpgme_op_import(mc.ctx, pgp_data);
200
 
    if(rc != GPG_ERR_NO_ERROR){
201
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
202
 
              gpgme_strsource(rc), gpgme_strerror(rc));
203
 
      return false;
204
 
    }
205
 
    
206
 
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
207
 
    if(ret == -1){
208
 
      perror("close");
209
 
    }
210
 
    gpgme_data_release(pgp_data);
211
 
    return true;
212
 
  }
213
 
  
214
 
  if(debug){
215
 
    fprintf(stderr, "Initializing GPGME\n");
 
97
 
 
98
  if (debug){
 
99
    fprintf(stderr, "Trying to decrypt OpenPGP packet\n");
216
100
  }
217
101
  
218
102
  /* Init GPGME */
219
103
  gpgme_check_version(NULL);
220
104
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
221
 
  if(rc != GPG_ERR_NO_ERROR){
 
105
  if (rc != GPG_ERR_NO_ERROR){
222
106
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
223
107
            gpgme_strsource(rc), gpgme_strerror(rc));
224
 
    return false;
 
108
    return -1;
225
109
  }
226
110
  
227
 
    /* Set GPGME home directory for the OpenPGP engine only */
228
 
  rc = gpgme_get_engine_info(&engine_info);
229
 
  if(rc != GPG_ERR_NO_ERROR){
 
111
  /* Set GPGME home directory */
 
112
  rc = gpgme_get_engine_info (&engine_info);
 
113
  if (rc != GPG_ERR_NO_ERROR){
230
114
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
231
115
            gpgme_strsource(rc), gpgme_strerror(rc));
232
 
    return false;
 
116
    return -1;
233
117
  }
234
118
  while(engine_info != NULL){
235
119
    if(engine_info->protocol == GPGME_PROTOCOL_OpenPGP){
236
120
      gpgme_set_engine_info(GPGME_PROTOCOL_OpenPGP,
237
 
                            engine_info->file_name, tempdir);
 
121
                            engine_info->file_name, homedir);
238
122
      break;
239
123
    }
240
124
    engine_info = engine_info->next;
241
125
  }
242
126
  if(engine_info == NULL){
243
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
244
 
    return false;
245
 
  }
246
 
  
247
 
  /* Create new GPGME "context" */
248
 
  rc = gpgme_new(&(mc.ctx));
249
 
  if(rc != GPG_ERR_NO_ERROR){
250
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
251
 
            gpgme_strsource(rc), gpgme_strerror(rc));
252
 
    return false;
253
 
  }
254
 
  
255
 
  if(not import_key(pubkey) or not import_key(seckey)){
256
 
    return false;
257
 
  }
258
 
  
259
 
  return true;
260
 
}
261
 
 
262
 
/* 
263
 
 * Decrypt OpenPGP data.
264
 
 * Returns -1 on error
265
 
 */
266
 
static ssize_t pgp_packet_decrypt(const char *cryptotext,
267
 
                                  size_t crypto_size,
268
 
                                  char **plaintext){
269
 
  gpgme_data_t dh_crypto, dh_plain;
270
 
  gpgme_error_t rc;
271
 
  ssize_t ret;
272
 
  size_t plaintext_capacity = 0;
273
 
  ssize_t plaintext_length = 0;
274
 
  
275
 
  if(debug){
276
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
277
 
  }
278
 
  
279
 
  /* Create new GPGME data buffer from memory cryptotext */
280
 
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
281
 
                               0);
282
 
  if(rc != GPG_ERR_NO_ERROR){
 
127
    fprintf(stderr, "Could not set home dir to %s\n", homedir);
 
128
    return -1;
 
129
  }
 
130
  
 
131
  /* Create new GPGME data buffer from packet buffer */
 
132
  rc = gpgme_data_new_from_mem(&dh_crypto, packet, packet_size, 0);
 
133
  if (rc != GPG_ERR_NO_ERROR){
283
134
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
284
135
            gpgme_strsource(rc), gpgme_strerror(rc));
285
136
    return -1;
287
138
  
288
139
  /* Create new empty GPGME data buffer for the plaintext */
289
140
  rc = gpgme_data_new(&dh_plain);
290
 
  if(rc != GPG_ERR_NO_ERROR){
 
141
  if (rc != GPG_ERR_NO_ERROR){
291
142
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
292
143
            gpgme_strsource(rc), gpgme_strerror(rc));
293
 
    gpgme_data_release(dh_crypto);
294
 
    return -1;
295
 
  }
296
 
  
297
 
  /* Decrypt data from the cryptotext data buffer to the plaintext
298
 
     data buffer */
299
 
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
300
 
  if(rc != GPG_ERR_NO_ERROR){
 
144
    return -1;
 
145
  }
 
146
  
 
147
  /* Create new GPGME "context" */
 
148
  rc = gpgme_new(&ctx);
 
149
  if (rc != GPG_ERR_NO_ERROR){
 
150
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
151
            gpgme_strsource(rc), gpgme_strerror(rc));
 
152
    return -1;
 
153
  }
 
154
  
 
155
  /* Decrypt data from the FILE pointer to the plaintext data
 
156
     buffer */
 
157
  rc = gpgme_op_decrypt(ctx, dh_crypto, dh_plain);
 
158
  if (rc != GPG_ERR_NO_ERROR){
301
159
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
302
160
            gpgme_strsource(rc), gpgme_strerror(rc));
303
 
    plaintext_length = -1;
304
 
    if(debug){
305
 
      gpgme_decrypt_result_t result;
306
 
      result = gpgme_op_decrypt_result(mc.ctx);
307
 
      if(result == NULL){
308
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
309
 
      } else {
310
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
311
 
                result->unsupported_algorithm);
312
 
        fprintf(stderr, "Wrong key usage: %u\n",
313
 
                result->wrong_key_usage);
314
 
        if(result->file_name != NULL){
315
 
          fprintf(stderr, "File name: %s\n", result->file_name);
316
 
        }
317
 
        gpgme_recipient_t recipient;
318
 
        recipient = result->recipients;
 
161
    return -1;
 
162
  }
 
163
 
 
164
  if(debug){
 
165
    fprintf(stderr, "Decryption of OpenPGP packet succeeded\n");
 
166
  }
 
167
 
 
168
  if (debug){
 
169
    gpgme_decrypt_result_t result;
 
170
    result = gpgme_op_decrypt_result(ctx);
 
171
    if (result == NULL){
 
172
      fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
173
    } else {
 
174
      fprintf(stderr, "Unsupported algorithm: %s\n",
 
175
              result->unsupported_algorithm);
 
176
      fprintf(stderr, "Wrong key usage: %d\n",
 
177
              result->wrong_key_usage);
 
178
      if(result->file_name != NULL){
 
179
        fprintf(stderr, "File name: %s\n", result->file_name);
 
180
      }
 
181
      gpgme_recipient_t recipient;
 
182
      recipient = result->recipients;
 
183
      if(recipient){
319
184
        while(recipient != NULL){
320
185
          fprintf(stderr, "Public key algorithm: %s\n",
321
186
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
327
192
        }
328
193
      }
329
194
    }
330
 
    goto decrypt_end;
331
195
  }
332
196
  
333
 
  if(debug){
334
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
335
 
  }
 
197
  /* Delete the GPGME FILE pointer cryptotext data buffer */
 
198
  gpgme_data_release(dh_crypto);
336
199
  
337
200
  /* Seek back to the beginning of the GPGME plaintext data buffer */
338
 
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
339
 
    perror("gpgme_data_seek");
340
 
    plaintext_length = -1;
341
 
    goto decrypt_end;
 
201
  if (gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET) == -1){
 
202
    perror("pgpme_data_seek");
342
203
  }
343
204
  
344
 
  *plaintext = NULL;
 
205
  *new_packet = 0;
345
206
  while(true){
346
 
    plaintext_capacity = incbuffer(plaintext,
347
 
                                      (size_t)plaintext_length,
348
 
                                      plaintext_capacity);
349
 
    if(plaintext_capacity == 0){
350
 
        perror("incbuffer");
351
 
        plaintext_length = -1;
352
 
        goto decrypt_end;
 
207
    if (new_packet_length + BUFFER_SIZE > new_packet_capacity){
 
208
      *new_packet = realloc(*new_packet,
 
209
                            (unsigned int)new_packet_capacity
 
210
                            + BUFFER_SIZE);
 
211
      if (*new_packet == NULL){
 
212
        perror("realloc");
 
213
        return -1;
 
214
      }
 
215
      new_packet_capacity += BUFFER_SIZE;
353
216
    }
354
217
    
355
 
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
 
218
    ret = gpgme_data_read(dh_plain, *new_packet + new_packet_length,
356
219
                          BUFFER_SIZE);
357
220
    /* Print the data, if any */
358
 
    if(ret == 0){
359
 
      /* EOF */
 
221
    if (ret == 0){
360
222
      break;
361
223
    }
362
224
    if(ret < 0){
363
225
      perror("gpgme_data_read");
364
 
      plaintext_length = -1;
365
 
      goto decrypt_end;
366
 
    }
367
 
    plaintext_length += ret;
368
 
  }
369
 
  
370
 
  if(debug){
371
 
    fprintf(stderr, "Decrypted password is: ");
372
 
    for(ssize_t i = 0; i < plaintext_length; i++){
373
 
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
374
 
    }
375
 
    fprintf(stderr, "\n");
376
 
  }
377
 
  
378
 
 decrypt_end:
379
 
  
380
 
  /* Delete the GPGME cryptotext data buffer */
381
 
  gpgme_data_release(dh_crypto);
 
226
      return -1;
 
227
    }
 
228
    new_packet_length += ret;
 
229
  }
 
230
 
 
231
  /* FIXME: check characters before printing to screen so to not print
 
232
     terminal control characters */
 
233
  /*   if(debug){ */
 
234
  /*     fprintf(stderr, "decrypted password is: "); */
 
235
  /*     fwrite(*new_packet, 1, new_packet_length, stderr); */
 
236
  /*     fprintf(stderr, "\n"); */
 
237
  /*   } */
382
238
  
383
239
  /* Delete the GPGME plaintext data buffer */
384
240
  gpgme_data_release(dh_plain);
385
 
  return plaintext_length;
 
241
  return new_packet_length;
386
242
}
387
243
 
388
 
static const char * safer_gnutls_strerror(int value){
389
 
  const char *ret = gnutls_strerror(value); /* Spurious warning from
390
 
                                               -Wunreachable-code */
391
 
  if(ret == NULL)
 
244
static const char * safer_gnutls_strerror (int value) {
 
245
  const char *ret = gnutls_strerror (value);
 
246
  if (ret == NULL)
392
247
    ret = "(unknown)";
393
248
  return ret;
394
249
}
395
250
 
396
 
/* GnuTLS log function callback */
397
251
static void debuggnutls(__attribute__((unused)) int level,
398
252
                        const char* string){
399
 
  fprintf(stderr, "GnuTLS: %s", string);
 
253
  fprintf(stderr, "%s", string);
400
254
}
401
255
 
402
 
static int init_gnutls_global(const char *pubkeyfilename,
403
 
                              const char *seckeyfilename){
 
256
static int initgnutls(encrypted_session *es){
 
257
  const char *err;
404
258
  int ret;
405
259
  
406
260
  if(debug){
407
261
    fprintf(stderr, "Initializing GnuTLS\n");
408
262
  }
409
 
  
410
 
  ret = gnutls_global_init();
411
 
  if(ret != GNUTLS_E_SUCCESS){
412
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
413
 
            safer_gnutls_strerror(ret));
 
263
 
 
264
  if ((ret = gnutls_global_init ())
 
265
      != GNUTLS_E_SUCCESS) {
 
266
    fprintf (stderr, "global_init: %s\n", safer_gnutls_strerror(ret));
414
267
    return -1;
415
268
  }
416
 
  
417
 
  if(debug){
418
 
    /* "Use a log level over 10 to enable all debugging options."
419
 
     * - GnuTLS manual
420
 
     */
 
269
 
 
270
  if (debug){
421
271
    gnutls_global_set_log_level(11);
422
272
    gnutls_global_set_log_function(debuggnutls);
423
273
  }
424
274
  
425
 
  /* OpenPGP credentials */
426
 
  gnutls_certificate_allocate_credentials(&mc.cred);
427
 
  if(ret != GNUTLS_E_SUCCESS){
428
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
429
 
                                                    from
430
 
                                                    -Wunreachable-code
431
 
                                                 */
432
 
            safer_gnutls_strerror(ret));
433
 
    gnutls_global_deinit();
 
275
  /* openpgp credentials */
 
276
  if ((ret = gnutls_certificate_allocate_credentials (&es->cred))
 
277
      != GNUTLS_E_SUCCESS) {
 
278
    fprintf (stderr, "memory error: %s\n",
 
279
             safer_gnutls_strerror(ret));
434
280
    return -1;
435
281
  }
436
282
  
437
283
  if(debug){
438
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
439
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
440
 
            seckeyfilename);
 
284
    fprintf(stderr, "Attempting to use OpenPGP certificate %s"
 
285
            " and keyfile %s as GnuTLS credentials\n", certfile,
 
286
            certkey);
441
287
  }
442
288
  
443
289
  ret = gnutls_certificate_set_openpgp_key_file
444
 
    (mc.cred, pubkeyfilename, seckeyfilename,
445
 
     GNUTLS_OPENPGP_FMT_BASE64);
446
 
  if(ret != GNUTLS_E_SUCCESS){
447
 
    fprintf(stderr,
448
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
449
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
450
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
451
 
            safer_gnutls_strerror(ret));
452
 
    goto globalfail;
453
 
  }
454
 
  
455
 
  /* GnuTLS server initialization */
456
 
  ret = gnutls_dh_params_init(&mc.dh_params);
457
 
  if(ret != GNUTLS_E_SUCCESS){
458
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
459
 
            " %s\n", safer_gnutls_strerror(ret));
460
 
    goto globalfail;
461
 
  }
462
 
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
463
 
  if(ret != GNUTLS_E_SUCCESS){
464
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
465
 
            safer_gnutls_strerror(ret));
466
 
    goto globalfail;
467
 
  }
468
 
  
469
 
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
470
 
  
471
 
  return 0;
472
 
  
473
 
 globalfail:
474
 
  
475
 
  gnutls_certificate_free_credentials(mc.cred);
476
 
  gnutls_global_deinit();
477
 
  gnutls_dh_params_deinit(mc.dh_params);
478
 
  return -1;
479
 
}
480
 
 
481
 
static int init_gnutls_session(gnutls_session_t *session){
482
 
  int ret;
483
 
  /* GnuTLS session creation */
484
 
  do {
485
 
    ret = gnutls_init(session, GNUTLS_SERVER);
486
 
    if(quit_now){
487
 
      return -1;
488
 
    }
489
 
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
490
 
  if(ret != GNUTLS_E_SUCCESS){
 
290
    (es->cred, certfile, certkey, GNUTLS_OPENPGP_FMT_BASE64);
 
291
  if (ret != GNUTLS_E_SUCCESS) {
 
292
    fprintf
 
293
      (stderr, "Error[%d] while reading the OpenPGP key pair ('%s',"
 
294
       " '%s')\n",
 
295
       ret, certfile, certkey);
 
296
    fprintf(stdout, "The Error is: %s\n",
 
297
            safer_gnutls_strerror(ret));
 
298
    return -1;
 
299
  }
 
300
  
 
301
  //GnuTLS server initialization
 
302
  if ((ret = gnutls_dh_params_init (&es->dh_params))
 
303
      != GNUTLS_E_SUCCESS) {
 
304
    fprintf (stderr, "Error in dh parameter initialization: %s\n",
 
305
             safer_gnutls_strerror(ret));
 
306
    return -1;
 
307
  }
 
308
  
 
309
  if ((ret = gnutls_dh_params_generate2 (es->dh_params, DH_BITS))
 
310
      != GNUTLS_E_SUCCESS) {
 
311
    fprintf (stderr, "Error in prime generation: %s\n",
 
312
             safer_gnutls_strerror(ret));
 
313
    return -1;
 
314
  }
 
315
  
 
316
  gnutls_certificate_set_dh_params (es->cred, es->dh_params);
 
317
  
 
318
  // GnuTLS session creation
 
319
  if ((ret = gnutls_init (&es->session, GNUTLS_SERVER))
 
320
      != GNUTLS_E_SUCCESS){
491
321
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
492
322
            safer_gnutls_strerror(ret));
493
323
  }
494
324
  
495
 
  {
496
 
    const char *err;
497
 
    do {
498
 
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
499
 
      if(quit_now){
500
 
        gnutls_deinit(*session);
501
 
        return -1;
502
 
      }
503
 
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
504
 
    if(ret != GNUTLS_E_SUCCESS){
505
 
      fprintf(stderr, "Syntax error at: %s\n", err);
506
 
      fprintf(stderr, "GnuTLS error: %s\n",
507
 
              safer_gnutls_strerror(ret));
508
 
      gnutls_deinit(*session);
509
 
      return -1;
510
 
    }
 
325
  if ((ret = gnutls_priority_set_direct (es->session, "NORMAL", &err))
 
326
      != GNUTLS_E_SUCCESS) {
 
327
    fprintf(stderr, "Syntax error at: %s\n", err);
 
328
    fprintf(stderr, "GnuTLS error: %s\n",
 
329
            safer_gnutls_strerror(ret));
 
330
    return -1;
511
331
  }
512
332
  
513
 
  do {
514
 
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
515
 
                                 mc.cred);
516
 
    if(quit_now){
517
 
      gnutls_deinit(*session);
518
 
      return -1;
519
 
    }
520
 
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
521
 
  if(ret != GNUTLS_E_SUCCESS){
522
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
333
  if ((ret = gnutls_credentials_set
 
334
       (es->session, GNUTLS_CRD_CERTIFICATE, es->cred))
 
335
      != GNUTLS_E_SUCCESS) {
 
336
    fprintf(stderr, "Error setting a credentials set: %s\n",
523
337
            safer_gnutls_strerror(ret));
524
 
    gnutls_deinit(*session);
525
338
    return -1;
526
339
  }
527
340
  
528
341
  /* ignore client certificate if any. */
529
 
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
 
342
  gnutls_certificate_server_set_request (es->session,
 
343
                                         GNUTLS_CERT_IGNORE);
530
344
  
531
 
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
345
  gnutls_dh_set_prime_bits (es->session, DH_BITS);
532
346
  
533
347
  return 0;
534
348
}
535
349
 
536
 
/* Avahi log function callback */
537
350
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
538
351
                      __attribute__((unused)) const char *txt){}
539
352
 
540
 
/* Called when a Mandos server is found */
541
353
static int start_mandos_communication(const char *ip, uint16_t port,
542
 
                                      AvahiIfIndex if_index,
543
 
                                      int af){
544
 
  int ret, tcp_sd = -1;
545
 
  ssize_t sret;
546
 
  union {
547
 
    struct sockaddr_in in;
548
 
    struct sockaddr_in6 in6;
549
 
  } to;
 
354
                                      AvahiIfIndex if_index){
 
355
  int ret, tcp_sd;
 
356
  struct sockaddr_in6 to;
 
357
  encrypted_session es;
550
358
  char *buffer = NULL;
551
 
  char *decrypted_buffer = NULL;
 
359
  char *decrypted_buffer;
552
360
  size_t buffer_length = 0;
553
361
  size_t buffer_capacity = 0;
554
 
  size_t written;
555
 
  int retval = -1;
556
 
  gnutls_session_t session;
557
 
  int pf;                       /* Protocol family */
558
 
  
559
 
  errno = 0;
560
 
  
561
 
  if(quit_now){
562
 
    errno = EINTR;
563
 
    return -1;
564
 
  }
565
 
  
566
 
  switch(af){
567
 
  case AF_INET6:
568
 
    pf = PF_INET6;
569
 
    break;
570
 
  case AF_INET:
571
 
    pf = PF_INET;
572
 
    break;
573
 
  default:
574
 
    fprintf(stderr, "Bad address family: %d\n", af);
575
 
    errno = EINVAL;
576
 
    return -1;
577
 
  }
578
 
  
579
 
  ret = init_gnutls_session(&session);
580
 
  if(ret != 0){
581
 
    return -1;
582
 
  }
 
362
  ssize_t decrypted_buffer_size;
 
363
  size_t written = 0;
 
364
  int retval = 0;
 
365
  char interface[IF_NAMESIZE];
583
366
  
584
367
  if(debug){
585
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
586
 
            "\n", ip, port);
 
368
    fprintf(stderr, "Setting up a tcp connection to %s, port %d\n",
 
369
            ip, port);
587
370
  }
588
371
  
589
 
  tcp_sd = socket(pf, SOCK_STREAM, 0);
590
 
  if(tcp_sd < 0){
591
 
    int e = errno;
 
372
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
 
373
  if(tcp_sd < 0) {
592
374
    perror("socket");
593
 
    errno = e;
594
 
    goto mandos_end;
595
 
  }
596
 
  
597
 
  if(quit_now){
598
 
    errno = EINTR;
599
 
    goto mandos_end;
600
 
  }
601
 
  
602
 
  memset(&to, 0, sizeof(to));
603
 
  if(af == AF_INET6){
604
 
    to.in6.sin6_family = (sa_family_t)af;
605
 
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
606
 
  } else {                      /* IPv4 */
607
 
    to.in.sin_family = (sa_family_t)af;
608
 
    ret = inet_pton(af, ip, &to.in.sin_addr);
609
 
  }
610
 
  if(ret < 0 ){
611
 
    int e = errno;
 
375
    return -1;
 
376
  }
 
377
 
 
378
  if(debug){
 
379
    if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
380
      if(debug){
 
381
        perror("if_indextoname");
 
382
      }
 
383
      return -1;
 
384
    }
 
385
    
 
386
    fprintf(stderr, "Binding to interface %s\n", interface);
 
387
  }
 
388
  
 
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 ){
612
393
    perror("inet_pton");
613
 
    errno = e;
614
 
    goto mandos_end;
615
 
  }
 
394
    return -1;
 
395
  }  
616
396
  if(ret == 0){
617
 
    int e = errno;
618
397
    fprintf(stderr, "Bad address: %s\n", ip);
619
 
    errno = e;
620
 
    goto mandos_end;
621
 
  }
622
 
  if(af == AF_INET6){
623
 
    to.in6.sin6_port = htons(port); /* Spurious warnings from
624
 
                                       -Wconversion and
625
 
                                       -Wunreachable-code */
626
 
    
627
 
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
628
 
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
629
 
                              -Wunreachable-code*/
630
 
      if(if_index == AVAHI_IF_UNSPEC){
631
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
632
 
                " without a network interface\n");
633
 
        errno = EINVAL;
634
 
        goto mandos_end;
635
 
      }
636
 
      /* Set the network interface number as scope */
637
 
      to.in6.sin6_scope_id = (uint32_t)if_index;
638
 
    }
639
 
  } else {
640
 
    to.in.sin_port = htons(port); /* Spurious warnings from
641
 
                                     -Wconversion and
642
 
                                     -Wunreachable-code */
643
 
  }
 
398
    return -1;
 
399
  }
 
400
  to.sin6_port = htons(port);   /* Spurious warning */
644
401
  
645
 
  if(quit_now){
646
 
    errno = EINTR;
647
 
    goto mandos_end;
648
 
  }
 
402
  to.sin6_scope_id = (uint32_t)if_index;
649
403
  
650
404
  if(debug){
651
 
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
652
 
      char interface[IF_NAMESIZE];
653
 
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
654
 
        perror("if_indextoname");
655
 
      } else {
656
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
657
 
                ip, interface, port);
658
 
      }
659
 
    } else {
660
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
661
 
              port);
662
 
    }
663
 
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
664
 
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
665
 
    const char *pcret;
666
 
    if(af == AF_INET6){
667
 
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
668
 
                        sizeof(addrstr));
669
 
    } else {
670
 
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
671
 
                        sizeof(addrstr));
672
 
    }
673
 
    if(pcret == NULL){
674
 
      perror("inet_ntop");
675
 
    } else {
676
 
      if(strcmp(addrstr, ip) != 0){
677
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
678
 
      }
679
 
    }
680
 
  }
681
 
  
682
 
  if(quit_now){
683
 
    errno = EINTR;
684
 
    goto mandos_end;
685
 
  }
686
 
  
687
 
  if(af == AF_INET6){
688
 
    ret = connect(tcp_sd, &to.in6, sizeof(to));
689
 
  } else {
690
 
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
691
 
  }
692
 
  if(ret < 0){
693
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
694
 
      int e = errno;
695
 
      perror("connect");
696
 
      errno = e;
697
 
    }
698
 
    goto mandos_end;
699
 
  }
700
 
  
701
 
  if(quit_now){
702
 
    errno = EINTR;
703
 
    goto mandos_end;
704
 
  }
705
 
  
706
 
  const char *out = mandos_protocol_version;
707
 
  written = 0;
708
 
  while(true){
709
 
    size_t out_size = strlen(out);
710
 
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
711
 
                                   out_size - written));
712
 
    if(ret == -1){
713
 
      int e = errno;
714
 
      perror("write");
715
 
      errno = e;
716
 
      goto mandos_end;
717
 
    }
718
 
    written += (size_t)ret;
719
 
    if(written < out_size){
720
 
      continue;
721
 
    } else {
722
 
      if(out == mandos_protocol_version){
723
 
        written = 0;
724
 
        out = "\r\n";
725
 
      } else {
726
 
        break;
727
 
      }
728
 
    }
729
 
  
730
 
    if(quit_now){
731
 
      errno = EINTR;
732
 
      goto mandos_end;
733
 
    }
734
 
  }
 
405
    fprintf(stderr, "Connection to: %s, port %d\n", ip, port);
 
406
/*     char addrstr[INET6_ADDRSTRLEN]; */
 
407
/*     if(inet_ntop(to.sin6_family, &(to.sin6_addr), addrstr, */
 
408
/*               sizeof(addrstr)) == NULL){ */
 
409
/*       perror("inet_ntop"); */
 
410
/*     } else { */
 
411
/*       fprintf(stderr, "Really connecting to: %s, port %d\n", */
 
412
/*            addrstr, ntohs(to.sin6_port)); */
 
413
/*     } */
 
414
  }
 
415
  
 
416
  ret = connect(tcp_sd, (struct sockaddr *) &to, sizeof(to));
 
417
  if (ret < 0){
 
418
    perror("connect");
 
419
    return -1;
 
420
  }
 
421
  
 
422
  ret = initgnutls (&es);
 
423
  if (ret != 0){
 
424
    retval = -1;
 
425
    return -1;
 
426
  }
 
427
  
 
428
  gnutls_transport_set_ptr (es.session,
 
429
                            (gnutls_transport_ptr_t) tcp_sd);
735
430
  
736
431
  if(debug){
737
432
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
738
433
  }
739
434
  
740
 
  if(quit_now){
741
 
    errno = EINTR;
742
 
    goto mandos_end;
743
 
  }
744
 
  
745
 
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
746
 
  
747
 
  if(quit_now){
748
 
    errno = EINTR;
749
 
    goto mandos_end;
750
 
  }
751
 
  
752
 
  do {
753
 
    ret = gnutls_handshake(session);
754
 
    if(quit_now){
755
 
      errno = EINTR;
756
 
      goto mandos_end;
757
 
    }
758
 
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
759
 
  
760
 
  if(ret != GNUTLS_E_SUCCESS){
 
435
  ret = gnutls_handshake (es.session);
 
436
  
 
437
  if (ret != GNUTLS_E_SUCCESS){
761
438
    if(debug){
762
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
763
 
      gnutls_perror(ret);
 
439
      fprintf(stderr, "\n*** Handshake failed ***\n");
 
440
      gnutls_perror (ret);
764
441
    }
765
 
    errno = EPROTO;
766
 
    goto mandos_end;
 
442
    retval = -1;
 
443
    goto exit;
767
444
  }
768
445
  
769
 
  /* Read OpenPGP packet that contains the wanted password */
 
446
  //Retrieve OpenPGP packet that contains the wanted password
770
447
  
771
448
  if(debug){
772
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
449
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
773
450
            ip);
774
451
  }
775
 
  
 
452
 
776
453
  while(true){
777
 
    
778
 
    if(quit_now){
779
 
      errno = EINTR;
780
 
      goto mandos_end;
781
 
    }
782
 
    
783
 
    buffer_capacity = incbuffer(&buffer, buffer_length,
784
 
                                   buffer_capacity);
785
 
    if(buffer_capacity == 0){
786
 
      int e = errno;
787
 
      perror("incbuffer");
788
 
      errno = e;
789
 
      goto mandos_end;
790
 
    }
791
 
    
792
 
    if(quit_now){
793
 
      errno = EINTR;
794
 
      goto mandos_end;
795
 
    }
796
 
    
797
 
    sret = gnutls_record_recv(session, buffer+buffer_length,
798
 
                              BUFFER_SIZE);
799
 
    if(sret == 0){
 
454
    if (buffer_length + BUFFER_SIZE > buffer_capacity){
 
455
      buffer = realloc(buffer, buffer_capacity + BUFFER_SIZE);
 
456
      if (buffer == NULL){
 
457
        perror("realloc");
 
458
        goto exit;
 
459
      }
 
460
      buffer_capacity += BUFFER_SIZE;
 
461
    }
 
462
    
 
463
    ret = gnutls_record_recv
 
464
      (es.session, buffer+buffer_length, BUFFER_SIZE);
 
465
    if (ret == 0){
800
466
      break;
801
467
    }
802
 
    if(sret < 0){
803
 
      switch(sret){
 
468
    if (ret < 0){
 
469
      switch(ret){
804
470
      case GNUTLS_E_INTERRUPTED:
805
471
      case GNUTLS_E_AGAIN:
806
472
        break;
807
473
      case GNUTLS_E_REHANDSHAKE:
808
 
        do {
809
 
          ret = gnutls_handshake(session);
810
 
          
811
 
          if(quit_now){
812
 
            errno = EINTR;
813
 
            goto mandos_end;
814
 
          }
815
 
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
816
 
        if(ret < 0){
817
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
818
 
          gnutls_perror(ret);
819
 
          errno = EPROTO;
820
 
          goto mandos_end;
 
474
        ret = gnutls_handshake (es.session);
 
475
        if (ret < 0){
 
476
          fprintf(stderr, "\n*** Handshake failed ***\n");
 
477
          gnutls_perror (ret);
 
478
          retval = -1;
 
479
          goto exit;
821
480
        }
822
481
        break;
823
482
      default:
824
483
        fprintf(stderr, "Unknown error while reading data from"
825
 
                " encrypted session with Mandos server\n");
826
 
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
827
 
        errno = EIO;
828
 
        goto mandos_end;
 
484
                " encrypted session with mandos server\n");
 
485
        retval = -1;
 
486
        gnutls_bye (es.session, GNUTLS_SHUT_RDWR);
 
487
        goto exit;
829
488
      }
830
489
    } else {
831
 
      buffer_length += (size_t) sret;
832
 
    }
833
 
  }
834
 
  
835
 
  if(debug){
836
 
    fprintf(stderr, "Closing TLS session\n");
837
 
  }
838
 
  
839
 
  if(quit_now){
840
 
    errno = EINTR;
841
 
    goto mandos_end;
842
 
  }
843
 
  
844
 
  do {
845
 
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
846
 
    if(quit_now){
847
 
      errno = EINTR;
848
 
      goto mandos_end;
849
 
    }
850
 
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
851
 
  
852
 
  if(buffer_length > 0){
853
 
    ssize_t decrypted_buffer_size;
 
490
      buffer_length += (size_t) ret;
 
491
    }
 
492
  }
 
493
  
 
494
  if (buffer_length > 0){
854
495
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
855
496
                                               buffer_length,
856
 
                                               &decrypted_buffer);
857
 
    if(decrypted_buffer_size >= 0){
858
 
      
859
 
      written = 0;
 
497
                                               &decrypted_buffer,
 
498
                                               certdir);
 
499
    if (decrypted_buffer_size >= 0){
860
500
      while(written < (size_t) decrypted_buffer_size){
861
 
        if(quit_now){
862
 
          errno = EINTR;
863
 
          goto mandos_end;
864
 
        }
865
 
        
866
 
        ret = (int)fwrite(decrypted_buffer + written, 1,
867
 
                          (size_t)decrypted_buffer_size - written,
868
 
                          stdout);
 
501
        ret = (int)fwrite (decrypted_buffer + written, 1,
 
502
                           (size_t)decrypted_buffer_size - written,
 
503
                           stdout);
869
504
        if(ret == 0 and ferror(stdout)){
870
 
          int e = errno;
871
505
          if(debug){
872
506
            fprintf(stderr, "Error writing encrypted data: %s\n",
873
507
                    strerror(errno));
874
508
          }
875
 
          errno = e;
876
 
          goto mandos_end;
 
509
          retval = -1;
 
510
          break;
877
511
        }
878
512
        written += (size_t)ret;
879
513
      }
880
 
      retval = 0;
881
 
    }
882
 
  }
883
 
  
884
 
  /* Shutdown procedure */
885
 
  
886
 
 mandos_end:
887
 
  {
888
 
    int e = errno;
889
 
    free(decrypted_buffer);
890
 
    free(buffer);
891
 
    if(tcp_sd >= 0){
892
 
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
893
 
    }
894
 
    if(ret == -1){
895
 
      if(e == 0){
896
 
        e = errno;
897
 
      }
898
 
      perror("close");
899
 
    }
900
 
    gnutls_deinit(session);
901
 
    if(quit_now){
902
 
      e = EINTR;
 
514
      free(decrypted_buffer);
 
515
    } else {
903
516
      retval = -1;
904
517
    }
905
 
    errno = e;
906
 
  }
 
518
  }
 
519
 
 
520
  //shutdown procedure
 
521
 
 
522
  if(debug){
 
523
    fprintf(stderr, "Closing TLS session\n");
 
524
  }
 
525
 
 
526
  free(buffer);
 
527
  gnutls_bye (es.session, GNUTLS_SHUT_RDWR);
 
528
 exit:
 
529
  close(tcp_sd);
 
530
  gnutls_deinit (es.session);
 
531
  gnutls_certificate_free_credentials (es.cred);
 
532
  gnutls_global_deinit ();
907
533
  return retval;
908
534
}
909
535
 
910
 
static void resolve_callback(AvahiSServiceResolver *r,
911
 
                             AvahiIfIndex interface,
912
 
                             AvahiProtocol proto,
913
 
                             AvahiResolverEvent event,
914
 
                             const char *name,
915
 
                             const char *type,
916
 
                             const char *domain,
917
 
                             const char *host_name,
918
 
                             const AvahiAddress *address,
919
 
                             uint16_t port,
920
 
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
921
 
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
922
 
                             flags,
923
 
                             AVAHI_GCC_UNUSED void* userdata){
924
 
  assert(r);
 
536
static AvahiSimplePoll *simple_poll = NULL;
 
537
static AvahiServer *server = NULL;
 
538
 
 
539
static void resolve_callback(
 
540
    AvahiSServiceResolver *r,
 
541
    AvahiIfIndex interface,
 
542
    AVAHI_GCC_UNUSED AvahiProtocol protocol,
 
543
    AvahiResolverEvent event,
 
544
    const char *name,
 
545
    const char *type,
 
546
    const char *domain,
 
547
    const char *host_name,
 
548
    const AvahiAddress *address,
 
549
    uint16_t port,
 
550
    AVAHI_GCC_UNUSED AvahiStringList *txt,
 
551
    AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
 
552
    AVAHI_GCC_UNUSED void* userdata) {
 
553
    
 
554
  assert(r);                    /* Spurious warning */
925
555
  
926
556
  /* Called whenever a service has been resolved successfully or
927
557
     timed out */
928
558
  
929
 
  if(quit_now){
930
 
    return;
931
 
  }
932
 
  
933
 
  switch(event){
 
559
  switch (event) {
934
560
  default:
935
561
  case AVAHI_RESOLVER_FAILURE:
936
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
937
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
938
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
562
    fprintf(stderr, "(Resolver) Failed to resolve service '%s' of"
 
563
            " type '%s' in domain '%s': %s\n", name, type, domain,
 
564
            avahi_strerror(avahi_server_errno(server)));
939
565
    break;
940
566
    
941
567
  case AVAHI_RESOLVER_FOUND:
943
569
      char ip[AVAHI_ADDRESS_STR_MAX];
944
570
      avahi_address_snprint(ip, sizeof(ip), address);
945
571
      if(debug){
946
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
947
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
948
 
                ip, (intmax_t)interface, port);
 
572
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s) on"
 
573
                " port %d\n", name, host_name, ip, port);
949
574
      }
950
 
      int ret = start_mandos_communication(ip, port, interface,
951
 
                                           avahi_proto_to_af(proto));
952
 
      if(ret == 0){
953
 
        avahi_simple_poll_quit(mc.simple_poll);
 
575
      int ret = start_mandos_communication(ip, port, interface);
 
576
      if (ret == 0){
 
577
        exit(EXIT_SUCCESS);
954
578
      }
955
579
    }
956
580
  }
957
581
  avahi_s_service_resolver_free(r);
958
582
}
959
583
 
960
 
static void browse_callback(AvahiSServiceBrowser *b,
961
 
                            AvahiIfIndex interface,
962
 
                            AvahiProtocol protocol,
963
 
                            AvahiBrowserEvent event,
964
 
                            const char *name,
965
 
                            const char *type,
966
 
                            const char *domain,
967
 
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
968
 
                            flags,
969
 
                            AVAHI_GCC_UNUSED void* userdata){
970
 
  assert(b);
971
 
  
972
 
  /* Called whenever a new services becomes available on the LAN or
973
 
     is removed from the LAN */
974
 
  
975
 
  if(quit_now){
976
 
    return;
977
 
  }
978
 
  
979
 
  switch(event){
980
 
  default:
981
 
  case AVAHI_BROWSER_FAILURE:
982
 
    
983
 
    fprintf(stderr, "(Avahi browser) %s\n",
984
 
            avahi_strerror(avahi_server_errno(mc.server)));
985
 
    avahi_simple_poll_quit(mc.simple_poll);
986
 
    return;
987
 
    
988
 
  case AVAHI_BROWSER_NEW:
989
 
    /* We ignore the returned Avahi resolver object. In the callback
990
 
       function we free it. If the Avahi server is terminated before
991
 
       the callback function is called the Avahi server will free the
992
 
       resolver for us. */
993
 
    
994
 
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
995
 
                                    name, type, domain, protocol, 0,
996
 
                                    resolve_callback, NULL) == NULL)
997
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
998
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
999
 
    break;
1000
 
    
1001
 
  case AVAHI_BROWSER_REMOVE:
1002
 
    break;
1003
 
    
1004
 
  case AVAHI_BROWSER_ALL_FOR_NOW:
1005
 
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1006
 
    if(debug){
1007
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
1008
 
    }
1009
 
    break;
1010
 
  }
1011
 
}
1012
 
 
1013
 
/* stop main loop after sigterm has been called */
1014
 
static void handle_sigterm(int sig){
1015
 
  if(quit_now){
1016
 
    return;
1017
 
  }
1018
 
  quit_now = 1;
1019
 
  signal_received = sig;
1020
 
  int old_errno = errno;
1021
 
  if(mc.simple_poll != NULL){
1022
 
    avahi_simple_poll_quit(mc.simple_poll);
1023
 
  }
1024
 
  errno = old_errno;
1025
 
}
1026
 
 
1027
 
/* 
1028
 
 * This function determines if a directory entry in /sys/class/net
1029
 
 * corresponds to an acceptable network device.
1030
 
 * (This function is passed to scandir(3) as a filter function.)
1031
 
 */
1032
 
int good_interface(const struct dirent *if_entry){
1033
 
  ssize_t ssret;
1034
 
  char *flagname = NULL;
1035
 
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
1036
 
                     if_entry->d_name);
1037
 
  if(ret < 0){
1038
 
    perror("asprintf");
1039
 
    return 0;
1040
 
  }
1041
 
  if(if_entry->d_name[0] == '.'){
1042
 
    return 0;
1043
 
  }
1044
 
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
1045
 
  if(flags_fd == -1){
1046
 
    perror("open");
1047
 
    return 0;
1048
 
  }
1049
 
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
1050
 
  /* read line from flags_fd */
1051
 
  ssize_t to_read = (sizeof(ifreq_flags)*2)+3; /* "0x1003\n" */
1052
 
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
1053
 
  flagstring[(size_t)to_read] = '\0';
1054
 
  if(flagstring == NULL){
1055
 
    perror("malloc");
1056
 
    close(flags_fd);
1057
 
    return 0;
1058
 
  }
1059
 
  while(to_read > 0){
1060
 
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
1061
 
                                             (size_t)to_read));
1062
 
    if(ssret == -1){
1063
 
      perror("read");
1064
 
      free(flagstring);
1065
 
      close(flags_fd);
1066
 
      return 0;
1067
 
    }
1068
 
    to_read -= ssret;
1069
 
    if(ssret == 0){
1070
 
      break;
1071
 
    }
1072
 
  }
1073
 
  close(flags_fd);
1074
 
  intmax_t tmpmax;
1075
 
  char *tmp;
1076
 
  errno = 0;
1077
 
  tmpmax = strtoimax(flagstring, &tmp, 0);
1078
 
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
1079
 
                                         and not (isspace(*tmp)))
1080
 
     or tmpmax != (ifreq_flags)tmpmax){
1081
 
    if(debug){
1082
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1083
 
              flagstring, if_entry->d_name);
1084
 
    }
1085
 
    free(flagstring);
1086
 
    return 0;
1087
 
  }
1088
 
  free(flagstring);
1089
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
1090
 
  /* Reject the loopback device */
1091
 
  if(flags & IFF_LOOPBACK){
1092
 
    if(debug){
1093
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1094
 
              if_entry->d_name);
1095
 
    }
1096
 
    return 0;
1097
 
  }
1098
 
  /* Accept point-to-point devices only if connect_to is specified */
1099
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1100
 
    if(debug){
1101
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1102
 
              if_entry->d_name);
1103
 
    }
1104
 
    return 1;
1105
 
  }
1106
 
  /* Otherwise, reject non-broadcast-capable devices */
1107
 
  if(not (flags & IFF_BROADCAST)){
1108
 
    if(debug){
1109
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1110
 
              if_entry->d_name);
1111
 
    }
1112
 
    return 0;
1113
 
  }
1114
 
  /* Accept this device */
1115
 
  if(debug){
1116
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1117
 
            if_entry->d_name);
1118
 
  }
1119
 
  return 1;
1120
 
}
1121
 
 
1122
 
int main(int argc, char *argv[]){
1123
 
  AvahiSServiceBrowser *sb = NULL;
1124
 
  int error;
1125
 
  int ret;
1126
 
  intmax_t tmpmax;
1127
 
  char *tmp;
1128
 
  int exitcode = EXIT_SUCCESS;
1129
 
  const char *interface = "";
1130
 
  struct ifreq network;
1131
 
  int sd = -1;
1132
 
  bool take_down_interface = false;
1133
 
  uid_t uid;
1134
 
  gid_t gid;
1135
 
  char tempdir[] = "/tmp/mandosXXXXXX";
1136
 
  bool tempdir_created = false;
1137
 
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1138
 
  const char *seckey = PATHDIR "/" SECKEY;
1139
 
  const char *pubkey = PATHDIR "/" PUBKEY;
1140
 
  
1141
 
  bool gnutls_initialized = false;
1142
 
  bool gpgme_initialized = false;
1143
 
  float delay = 2.5f;
1144
 
  
1145
 
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1146
 
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1147
 
  
1148
 
  uid = getuid();
1149
 
  gid = getgid();
1150
 
  
1151
 
  /* Lower any group privileges we might have, just to be safe */
1152
 
  errno = 0;
1153
 
  ret = setgid(gid);
1154
 
  if(ret == -1){
1155
 
    perror("setgid");
1156
 
  }
1157
 
  
1158
 
  /* Lower user privileges (temporarily) */
1159
 
  errno = 0;
1160
 
  ret = seteuid(uid);
1161
 
  if(ret == -1){
1162
 
    perror("seteuid");
1163
 
  }
1164
 
  
1165
 
  if(quit_now){
1166
 
    goto end;
1167
 
  }
1168
 
  
1169
 
  {
1170
 
    struct argp_option options[] = {
1171
 
      { .name = "debug", .key = 128,
1172
 
        .doc = "Debug mode", .group = 3 },
1173
 
      { .name = "connect", .key = 'c',
1174
 
        .arg = "ADDRESS:PORT",
1175
 
        .doc = "Connect directly to a specific Mandos server",
1176
 
        .group = 1 },
1177
 
      { .name = "interface", .key = 'i',
1178
 
        .arg = "NAME",
1179
 
        .doc = "Network interface that will be used to search for"
1180
 
        " Mandos servers",
1181
 
        .group = 1 },
1182
 
      { .name = "seckey", .key = 's',
1183
 
        .arg = "FILE",
1184
 
        .doc = "OpenPGP secret key file base name",
1185
 
        .group = 1 },
1186
 
      { .name = "pubkey", .key = 'p',
1187
 
        .arg = "FILE",
1188
 
        .doc = "OpenPGP public key file base name",
1189
 
        .group = 2 },
1190
 
      { .name = "dh-bits", .key = 129,
1191
 
        .arg = "BITS",
1192
 
        .doc = "Bit length of the prime number used in the"
1193
 
        " Diffie-Hellman key exchange",
1194
 
        .group = 2 },
1195
 
      { .name = "priority", .key = 130,
1196
 
        .arg = "STRING",
1197
 
        .doc = "GnuTLS priority string for the TLS handshake",
1198
 
        .group = 1 },
1199
 
      { .name = "delay", .key = 131,
1200
 
        .arg = "SECONDS",
1201
 
        .doc = "Maximum delay to wait for interface startup",
1202
 
        .group = 2 },
1203
 
      /*
1204
 
       * These reproduce what we would get without ARGP_NO_HELP
1205
 
       */
1206
 
      { .name = "help", .key = '?',
1207
 
        .doc = "Give this help list", .group = -1 },
1208
 
      { .name = "usage", .key = -3,
1209
 
        .doc = "Give a short usage message", .group = -1 },
1210
 
      { .name = "version", .key = 'V',
1211
 
        .doc = "Print program version", .group = -1 },
1212
 
      { .name = NULL }
1213
 
    };
1214
 
    
1215
 
    error_t parse_opt(int key, char *arg,
1216
 
                      struct argp_state *state){
1217
 
      errno = 0;
1218
 
      switch(key){
1219
 
      case 128:                 /* --debug */
1220
 
        debug = true;
1221
 
        break;
1222
 
      case 'c':                 /* --connect */
1223
 
        connect_to = arg;
1224
 
        break;
1225
 
      case 'i':                 /* --interface */
1226
 
        interface = arg;
1227
 
        break;
1228
 
      case 's':                 /* --seckey */
1229
 
        seckey = arg;
1230
 
        break;
1231
 
      case 'p':                 /* --pubkey */
1232
 
        pubkey = arg;
1233
 
        break;
1234
 
      case 129:                 /* --dh-bits */
1235
 
        errno = 0;
1236
 
        tmpmax = strtoimax(arg, &tmp, 10);
1237
 
        if(errno != 0 or tmp == arg or *tmp != '\0'
1238
 
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
1239
 
          argp_error(state, "Bad number of DH bits");
1240
 
        }
1241
 
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1242
 
        break;
1243
 
      case 130:                 /* --priority */
1244
 
        mc.priority = arg;
1245
 
        break;
1246
 
      case 131:                 /* --delay */
1247
 
        errno = 0;
1248
 
        delay = strtof(arg, &tmp);
1249
 
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1250
 
          argp_error(state, "Bad delay");
1251
 
        }
1252
 
        break;
1253
 
        /*
1254
 
         * These reproduce what we would get without ARGP_NO_HELP
1255
 
         */
1256
 
      case '?':                 /* --help */
1257
 
        argp_state_help(state, state->out_stream,
1258
 
                        (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
1259
 
                        & ~(unsigned int)ARGP_HELP_EXIT_OK);
1260
 
      case -3:                  /* --usage */
1261
 
        argp_state_help(state, state->out_stream,
1262
 
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1263
 
      case 'V':                 /* --version */
1264
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
1265
 
        exit(argp_err_exit_status);
1266
 
        break;
1267
 
      default:
1268
 
        return ARGP_ERR_UNKNOWN;
1269
 
      }
1270
 
      return errno;
1271
 
    }
1272
 
    
1273
 
    struct argp argp = { .options = options, .parser = parse_opt,
1274
 
                         .args_doc = "",
1275
 
                         .doc = "Mandos client -- Get and decrypt"
1276
 
                         " passwords from a Mandos server" };
1277
 
    ret = argp_parse(&argp, argc, argv,
1278
 
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
1279
 
    switch(ret){
1280
 
    case 0:
1281
 
      break;
1282
 
    case ENOMEM:
 
584
static void browse_callback(
 
585
    AvahiSServiceBrowser *b,
 
586
    AvahiIfIndex interface,
 
587
    AvahiProtocol protocol,
 
588
    AvahiBrowserEvent event,
 
589
    const char *name,
 
590
    const char *type,
 
591
    const char *domain,
 
592
    AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
 
593
    void* userdata) {
 
594
    
 
595
    AvahiServer *s = userdata;
 
596
    assert(b);                  /* Spurious warning */
 
597
    
 
598
    /* Called whenever a new services becomes available on the LAN or
 
599
       is removed from the LAN */
 
600
    
 
601
    switch (event) {
1283
602
    default:
1284
 
      errno = ret;
1285
 
      perror("argp_parse");
1286
 
      exitcode = EX_OSERR;
1287
 
      goto end;
1288
 
    case EINVAL:
1289
 
      exitcode = EX_USAGE;
1290
 
      goto end;
1291
 
    }
1292
 
  }
1293
 
  
1294
 
  if(not debug){
1295
 
    avahi_set_log_function(empty_log);
1296
 
  }
1297
 
 
1298
 
  if(interface[0] == '\0'){
1299
 
    struct dirent **direntries;
1300
 
    ret = scandir(sys_class_net, &direntries, good_interface,
1301
 
                  alphasort);
1302
 
    if(ret >= 1){
1303
 
      /* Pick the first good interface */
1304
 
      interface = strdup(direntries[0]->d_name);
1305
 
      if(debug){
1306
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1307
 
      }
1308
 
      if(interface == NULL){
1309
 
        perror("malloc");
1310
 
        free(direntries);
1311
 
        exitcode = EXIT_FAILURE;
1312
 
        goto end;
1313
 
      }
1314
 
      free(direntries);
1315
 
    } else {
1316
 
      free(direntries);
1317
 
      fprintf(stderr, "Could not find a network interface\n");
1318
 
      exitcode = EXIT_FAILURE;
1319
 
      goto end;
1320
 
    }
1321
 
  }
1322
 
  
1323
 
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1324
 
     from the signal handler */
1325
 
  /* Initialize the pseudo-RNG for Avahi */
1326
 
  srand((unsigned int) time(NULL));
1327
 
  mc.simple_poll = avahi_simple_poll_new();
1328
 
  if(mc.simple_poll == NULL){
1329
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1330
 
    exitcode = EX_UNAVAILABLE;
1331
 
    goto end;
1332
 
  }
1333
 
  
1334
 
  sigemptyset(&sigterm_action.sa_mask);
1335
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1336
 
  if(ret == -1){
1337
 
    perror("sigaddset");
1338
 
    exitcode = EX_OSERR;
1339
 
    goto end;
1340
 
  }
1341
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1342
 
  if(ret == -1){
1343
 
    perror("sigaddset");
1344
 
    exitcode = EX_OSERR;
1345
 
    goto end;
1346
 
  }
1347
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1348
 
  if(ret == -1){
1349
 
    perror("sigaddset");
1350
 
    exitcode = EX_OSERR;
1351
 
    goto end;
1352
 
  }
1353
 
  /* Need to check if the handler is SIG_IGN before handling:
1354
 
     | [[info:libc:Initial Signal Actions]] |
1355
 
     | [[info:libc:Basic Signal Handling]]  |
1356
 
  */
1357
 
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1358
 
  if(ret == -1){
1359
 
    perror("sigaction");
1360
 
    return EX_OSERR;
1361
 
  }
1362
 
  if(old_sigterm_action.sa_handler != SIG_IGN){
1363
 
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1364
 
    if(ret == -1){
1365
 
      perror("sigaction");
1366
 
      exitcode = EX_OSERR;
1367
 
      goto end;
1368
 
    }
1369
 
  }
1370
 
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1371
 
  if(ret == -1){
1372
 
    perror("sigaction");
1373
 
    return EX_OSERR;
1374
 
  }
1375
 
  if(old_sigterm_action.sa_handler != SIG_IGN){
1376
 
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1377
 
    if(ret == -1){
1378
 
      perror("sigaction");
1379
 
      exitcode = EX_OSERR;
1380
 
      goto end;
1381
 
    }
1382
 
  }
1383
 
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1384
 
  if(ret == -1){
1385
 
    perror("sigaction");
1386
 
    return EX_OSERR;
1387
 
  }
1388
 
  if(old_sigterm_action.sa_handler != SIG_IGN){
1389
 
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1390
 
    if(ret == -1){
1391
 
      perror("sigaction");
1392
 
      exitcode = EX_OSERR;
1393
 
      goto end;
1394
 
    }
1395
 
  }
1396
 
  
1397
 
  /* If the interface is down, bring it up */
1398
 
  if(strcmp(interface, "none") != 0){
 
603
    case AVAHI_BROWSER_FAILURE:
 
604
      
 
605
      fprintf(stderr, "(Browser) %s\n",
 
606
              avahi_strerror(avahi_server_errno(server)));
 
607
      avahi_simple_poll_quit(simple_poll);
 
608
      return;
 
609
      
 
610
    case AVAHI_BROWSER_NEW:
 
611
      /* We ignore the returned resolver object. In the callback
 
612
         function we free it. If the server is terminated before
 
613
         the callback function is called the server will free
 
614
         the resolver for us. */
 
615
      
 
616
      if (!(avahi_s_service_resolver_new(s, interface, protocol, name,
 
617
                                         type, domain,
 
618
                                         AVAHI_PROTO_INET6, 0,
 
619
                                         resolve_callback, s)))
 
620
        fprintf(stderr, "Failed to resolve service '%s': %s\n", name,
 
621
                avahi_strerror(avahi_server_errno(s)));
 
622
      break;
 
623
      
 
624
    case AVAHI_BROWSER_REMOVE:
 
625
      break;
 
626
      
 
627
    case AVAHI_BROWSER_ALL_FOR_NOW:
 
628
    case AVAHI_BROWSER_CACHE_EXHAUSTED:
 
629
      break;
 
630
    }
 
631
}
 
632
 
 
633
/* Combines file name and path and returns the malloced new
 
634
   string. some sane checks could/should be added */
 
635
static const char *combinepath(const char *first, const char *second){
 
636
  size_t f_len = strlen(first);
 
637
  size_t s_len = strlen(second);
 
638
  char *tmp = malloc(f_len + s_len + 2);
 
639
  if (tmp == NULL){
 
640
    return NULL;
 
641
  }
 
642
  if(f_len > 0){
 
643
    memcpy(tmp, first, f_len);
 
644
  }
 
645
  tmp[f_len] = '/';
 
646
  if(s_len > 0){
 
647
    memcpy(tmp + f_len + 1, second, s_len);
 
648
  }
 
649
  tmp[f_len + 1 + s_len] = '\0';
 
650
  return tmp;
 
651
}
 
652
 
 
653
 
 
654
int main(AVAHI_GCC_UNUSED int argc, AVAHI_GCC_UNUSED char*argv[]) {
 
655
    AvahiServerConfig config;
 
656
    AvahiSServiceBrowser *sb = NULL;
 
657
    int error;
 
658
    int ret;
 
659
    int returncode = EXIT_SUCCESS;
 
660
    const char *interface = "eth0";
 
661
    struct ifreq network;
 
662
    int sd;
 
663
    char *connect_to = NULL;
 
664
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
 
665
    
 
666
    while (true){
 
667
      static struct option long_options[] = {
 
668
        {"debug", no_argument, (int *)&debug, 1},
 
669
        {"connect", required_argument, 0, 'C'},
 
670
        {"interface", required_argument, 0, 'i'},
 
671
        {"certdir", required_argument, 0, 'd'},
 
672
        {"certkey", required_argument, 0, 'c'},
 
673
        {"certfile", required_argument, 0, 'k'},
 
674
        {0, 0, 0, 0} };
 
675
      
 
676
      int option_index = 0;
 
677
      ret = getopt_long (argc, argv, "i:", long_options,
 
678
                         &option_index);
 
679
      
 
680
      if (ret == -1){
 
681
        break;
 
682
      }
 
683
      
 
684
      switch(ret){
 
685
      case 0:
 
686
        break;
 
687
      case 'i':
 
688
        interface = optarg;
 
689
        break;
 
690
      case 'C':
 
691
        connect_to = optarg;
 
692
        break;
 
693
      case 'd':
 
694
        certdir = optarg;
 
695
        break;
 
696
      case 'c':
 
697
        certfile = optarg;
 
698
        break;
 
699
      case 'k':
 
700
        certkey = optarg;
 
701
        break;
 
702
      default:
 
703
        exit(EXIT_FAILURE);
 
704
      }
 
705
    }
 
706
    
 
707
    certfile = combinepath(certdir, certfile);
 
708
    if (certfile == NULL){
 
709
      perror("combinepath");
 
710
      returncode = EXIT_FAILURE;
 
711
      goto exit;
 
712
    }
 
713
 
 
714
    certkey = combinepath(certdir, certkey);
 
715
    if (certkey == NULL){
 
716
      perror("combinepath");
 
717
      returncode = EXIT_FAILURE;
 
718
      goto exit;
 
719
    }
 
720
    
1399
721
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1400
722
    if(if_index == 0){
1401
723
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1402
 
      exitcode = EX_UNAVAILABLE;
1403
 
      goto end;
1404
 
    }
1405
 
    
1406
 
    if(quit_now){
1407
 
      goto end;
1408
 
    }
1409
 
    
1410
 
    /* Re-raise priviliges */
1411
 
    errno = 0;
1412
 
    ret = seteuid(0);
1413
 
    if(ret == -1){
1414
 
      perror("seteuid");
1415
 
    }
1416
 
    
1417
 
#ifdef __linux__
1418
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1419
 
       messages about the network interface to mess up the prompt */
1420
 
    ret = klogctl(8, NULL, 5);
1421
 
    bool restore_loglevel = true;
1422
 
    if(ret == -1){
1423
 
      restore_loglevel = false;
1424
 
      perror("klogctl");
1425
 
    }
1426
 
#endif  /* __linux__ */
 
724
      exit(EXIT_FAILURE);
 
725
    }
 
726
    
 
727
    if(connect_to != NULL){
 
728
      /* Connect directly, do not use Zeroconf */
 
729
      /* (Mainly meant for debugging) */
 
730
      char *address = strrchr(connect_to, ':');
 
731
      if(address == NULL){
 
732
        fprintf(stderr, "No colon in address\n");
 
733
        exit(EXIT_FAILURE);
 
734
      }
 
735
      errno = 0;
 
736
      uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
 
737
      if(errno){
 
738
        perror("Bad port number");
 
739
        exit(EXIT_FAILURE);
 
740
      }
 
741
      *address = '\0';
 
742
      address = connect_to;
 
743
      ret = start_mandos_communication(address, port, if_index);
 
744
      if(ret < 0){
 
745
        exit(EXIT_FAILURE);
 
746
      } else {
 
747
        exit(EXIT_SUCCESS);
 
748
      }
 
749
    }
1427
750
    
1428
751
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1429
 
    if(sd < 0){
 
752
    if(sd < 0) {
1430
753
      perror("socket");
1431
 
      exitcode = EX_OSERR;
1432
 
#ifdef __linux__
1433
 
      if(restore_loglevel){
1434
 
        ret = klogctl(7, NULL, 0);
1435
 
        if(ret == -1){
1436
 
          perror("klogctl");
1437
 
        }
1438
 
      }
1439
 
#endif  /* __linux__ */
1440
 
      /* Lower privileges */
1441
 
      errno = 0;
1442
 
      ret = seteuid(uid);
1443
 
      if(ret == -1){
1444
 
        perror("seteuid");
1445
 
      }
1446
 
      goto end;
 
754
      returncode = EXIT_FAILURE;
 
755
      goto exit;
1447
756
    }
1448
 
    strcpy(network.ifr_name, interface);
 
757
    strcpy(network.ifr_name, interface);    
1449
758
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1450
759
    if(ret == -1){
 
760
      
1451
761
      perror("ioctl SIOCGIFFLAGS");
1452
 
#ifdef __linux__
1453
 
      if(restore_loglevel){
1454
 
        ret = klogctl(7, NULL, 0);
1455
 
        if(ret == -1){
1456
 
          perror("klogctl");
1457
 
        }
1458
 
      }
1459
 
#endif  /* __linux__ */
1460
 
      exitcode = EX_OSERR;
1461
 
      /* Lower privileges */
1462
 
      errno = 0;
1463
 
      ret = seteuid(uid);
1464
 
      if(ret == -1){
1465
 
        perror("seteuid");
1466
 
      }
1467
 
      goto end;
 
762
      returncode = EXIT_FAILURE;
 
763
      goto exit;
1468
764
    }
1469
765
    if((network.ifr_flags & IFF_UP) == 0){
1470
766
      network.ifr_flags |= IFF_UP;
1471
 
      take_down_interface = true;
1472
767
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1473
768
      if(ret == -1){
1474
 
        take_down_interface = false;
1475
 
        perror("ioctl SIOCSIFFLAGS +IFF_UP");
1476
 
        exitcode = EX_OSERR;
1477
 
#ifdef __linux__
1478
 
        if(restore_loglevel){
1479
 
          ret = klogctl(7, NULL, 0);
1480
 
          if(ret == -1){
1481
 
            perror("klogctl");
1482
 
          }
1483
 
        }
1484
 
#endif  /* __linux__ */
1485
 
        /* Lower privileges */
1486
 
        errno = 0;
1487
 
        ret = seteuid(uid);
1488
 
        if(ret == -1){
1489
 
          perror("seteuid");
1490
 
        }
1491
 
        goto end;
1492
 
      }
1493
 
    }
1494
 
    /* sleep checking until interface is running */
1495
 
    for(int i=0; i < delay * 4; i++){
1496
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1497
 
      if(ret == -1){
1498
 
        perror("ioctl SIOCGIFFLAGS");
1499
 
      } else if(network.ifr_flags & IFF_RUNNING){
1500
 
        break;
1501
 
      }
1502
 
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1503
 
      ret = nanosleep(&sleeptime, NULL);
1504
 
      if(ret == -1 and errno != EINTR){
1505
 
        perror("nanosleep");
1506
 
      }
1507
 
    }
1508
 
    if(not take_down_interface){
1509
 
      /* We won't need the socket anymore */
1510
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1511
 
      if(ret == -1){
1512
 
        perror("close");
1513
 
      }
1514
 
    }
1515
 
#ifdef __linux__
1516
 
    if(restore_loglevel){
1517
 
      /* Restores kernel loglevel to default */
1518
 
      ret = klogctl(7, NULL, 0);
1519
 
      if(ret == -1){
1520
 
        perror("klogctl");
1521
 
      }
1522
 
    }
1523
 
#endif  /* __linux__ */
1524
 
    /* Lower privileges */
1525
 
    errno = 0;
1526
 
    if(take_down_interface){
1527
 
      /* Lower privileges */
1528
 
      ret = seteuid(uid);
1529
 
      if(ret == -1){
1530
 
        perror("seteuid");
1531
 
      }
1532
 
    } else {
1533
 
      /* Lower privileges permanently */
1534
 
      ret = setuid(uid);
1535
 
      if(ret == -1){
1536
 
        perror("setuid");
1537
 
      }
1538
 
    }
1539
 
  }
1540
 
  
1541
 
  if(quit_now){
1542
 
    goto end;
1543
 
  }
1544
 
  
1545
 
  ret = init_gnutls_global(pubkey, seckey);
1546
 
  if(ret == -1){
1547
 
    fprintf(stderr, "init_gnutls_global failed\n");
1548
 
    exitcode = EX_UNAVAILABLE;
1549
 
    goto end;
1550
 
  } else {
1551
 
    gnutls_initialized = true;
1552
 
  }
1553
 
  
1554
 
  if(quit_now){
1555
 
    goto end;
1556
 
  }
1557
 
  
1558
 
  tempdir_created = true;
1559
 
  if(mkdtemp(tempdir) == NULL){
1560
 
    tempdir_created = false;
1561
 
    perror("mkdtemp");
1562
 
    goto end;
1563
 
  }
1564
 
  
1565
 
  if(quit_now){
1566
 
    goto end;
1567
 
  }
1568
 
  
1569
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
1570
 
    fprintf(stderr, "init_gpgme failed\n");
1571
 
    exitcode = EX_UNAVAILABLE;
1572
 
    goto end;
1573
 
  } else {
1574
 
    gpgme_initialized = true;
1575
 
  }
1576
 
  
1577
 
  if(quit_now){
1578
 
    goto end;
1579
 
  }
1580
 
  
1581
 
  if(connect_to != NULL){
1582
 
    /* Connect directly, do not use Zeroconf */
1583
 
    /* (Mainly meant for debugging) */
1584
 
    char *address = strrchr(connect_to, ':');
1585
 
    if(address == NULL){
1586
 
      fprintf(stderr, "No colon in address\n");
1587
 
      exitcode = EX_USAGE;
1588
 
      goto end;
1589
 
    }
1590
 
    
1591
 
    if(quit_now){
1592
 
      goto end;
1593
 
    }
1594
 
    
1595
 
    uint16_t port;
1596
 
    errno = 0;
1597
 
    tmpmax = strtoimax(address+1, &tmp, 10);
1598
 
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1599
 
       or tmpmax != (uint16_t)tmpmax){
1600
 
      fprintf(stderr, "Bad port number\n");
1601
 
      exitcode = EX_USAGE;
1602
 
      goto end;
1603
 
    }
1604
 
  
1605
 
    if(quit_now){
1606
 
      goto end;
1607
 
    }
1608
 
    
1609
 
    port = (uint16_t)tmpmax;
1610
 
    *address = '\0';
1611
 
    address = connect_to;
1612
 
    /* Colon in address indicates IPv6 */
1613
 
    int af;
1614
 
    if(strchr(address, ':') != NULL){
1615
 
      af = AF_INET6;
1616
 
    } else {
1617
 
      af = AF_INET;
1618
 
    }
1619
 
    
1620
 
    if(quit_now){
1621
 
      goto end;
1622
 
    }
1623
 
 
1624
 
    while(not quit_now){
1625
 
      ret = start_mandos_communication(address, port, if_index, af);
1626
 
      if(quit_now or ret == 0){
1627
 
        break;
1628
 
      }
1629
 
      sleep(15);
1630
 
    };
1631
 
 
1632
 
    if (not quit_now){
1633
 
      exitcode = EXIT_SUCCESS;
1634
 
    }
1635
 
 
1636
 
    goto end;
1637
 
  }
1638
 
  
1639
 
  if(quit_now){
1640
 
    goto end;
1641
 
  }
1642
 
  
1643
 
  {
1644
 
    AvahiServerConfig config;
1645
 
    /* Do not publish any local Zeroconf records */
 
769
        perror("ioctl SIOCSIFFLAGS");
 
770
        returncode = EXIT_FAILURE;
 
771
        goto exit;
 
772
      }
 
773
    }
 
774
    close(sd);
 
775
    
 
776
    if (not debug){
 
777
      avahi_set_log_function(empty_log);
 
778
    }
 
779
    
 
780
    /* Initialize the psuedo-RNG */
 
781
    srand((unsigned int) time(NULL));
 
782
 
 
783
    /* Allocate main loop object */
 
784
    if (!(simple_poll = avahi_simple_poll_new())) {
 
785
        fprintf(stderr, "Failed to create simple poll object.\n");
 
786
        returncode = EXIT_FAILURE;      
 
787
        goto exit;
 
788
    }
 
789
 
 
790
    /* Do not publish any local records */
1646
791
    avahi_server_config_init(&config);
1647
792
    config.publish_hinfo = 0;
1648
793
    config.publish_addresses = 0;
1649
794
    config.publish_workstation = 0;
1650
795
    config.publish_domain = 0;
1651
 
    
 
796
 
1652
797
    /* Allocate a new server */
1653
 
    mc.server = avahi_server_new(avahi_simple_poll_get
1654
 
                                 (mc.simple_poll), &config, NULL,
1655
 
                                 NULL, &error);
1656
 
    
1657
 
    /* Free the Avahi configuration data */
 
798
    server = avahi_server_new(avahi_simple_poll_get(simple_poll),
 
799
                              &config, NULL, NULL, &error);
 
800
 
 
801
    /* Free the configuration data */
1658
802
    avahi_server_config_free(&config);
1659
 
  }
1660
 
  
1661
 
  /* Check if creating the Avahi server object succeeded */
1662
 
  if(mc.server == NULL){
1663
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1664
 
            avahi_strerror(error));
1665
 
    exitcode = EX_UNAVAILABLE;
1666
 
    goto end;
1667
 
  }
1668
 
  
1669
 
  if(quit_now){
1670
 
    goto end;
1671
 
  }
1672
 
  
1673
 
  /* Create the Avahi service browser */
1674
 
  sb = avahi_s_service_browser_new(mc.server, if_index,
1675
 
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1676
 
                                   NULL, 0, browse_callback, NULL);
1677
 
  if(sb == NULL){
1678
 
    fprintf(stderr, "Failed to create service browser: %s\n",
1679
 
            avahi_strerror(avahi_server_errno(mc.server)));
1680
 
    exitcode = EX_UNAVAILABLE;
1681
 
    goto end;
1682
 
  }
1683
 
  
1684
 
  if(quit_now){
1685
 
    goto end;
1686
 
  }
1687
 
  
1688
 
  /* Run the main loop */
1689
 
  
1690
 
  if(debug){
1691
 
    fprintf(stderr, "Starting Avahi loop search\n");
1692
 
  }
1693
 
  
1694
 
  avahi_simple_poll_loop(mc.simple_poll);
1695
 
  
1696
 
 end:
1697
 
  
1698
 
  if(debug){
1699
 
    fprintf(stderr, "%s exiting\n", argv[0]);
1700
 
  }
1701
 
  
1702
 
  /* Cleanup things */
1703
 
  if(sb != NULL)
1704
 
    avahi_s_service_browser_free(sb);
1705
 
  
1706
 
  if(mc.server != NULL)
1707
 
    avahi_server_free(mc.server);
1708
 
  
1709
 
  if(mc.simple_poll != NULL)
1710
 
    avahi_simple_poll_free(mc.simple_poll);
1711
 
  
1712
 
  if(gnutls_initialized){
1713
 
    gnutls_certificate_free_credentials(mc.cred);
1714
 
    gnutls_global_deinit();
1715
 
    gnutls_dh_params_deinit(mc.dh_params);
1716
 
  }
1717
 
  
1718
 
  if(gpgme_initialized){
1719
 
    gpgme_release(mc.ctx);
1720
 
  }
1721
 
  
1722
 
  /* Take down the network interface */
1723
 
  if(take_down_interface){
1724
 
    /* Re-raise priviliges */
1725
 
    errno = 0;
1726
 
    ret = seteuid(0);
1727
 
    if(ret == -1){
1728
 
      perror("seteuid");
1729
 
    }
1730
 
    if(geteuid() == 0){
1731
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1732
 
      if(ret == -1){
1733
 
        perror("ioctl SIOCGIFFLAGS");
1734
 
      } else if(network.ifr_flags & IFF_UP) {
1735
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1736
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1737
 
        if(ret == -1){
1738
 
          perror("ioctl SIOCSIFFLAGS -IFF_UP");
1739
 
        }
1740
 
      }
1741
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1742
 
      if(ret == -1){
1743
 
        perror("close");
1744
 
      }
1745
 
      /* Lower privileges permanently */
1746
 
      errno = 0;
1747
 
      ret = setuid(uid);
1748
 
      if(ret == -1){
1749
 
        perror("setuid");
1750
 
      }
1751
 
    }
1752
 
  }
1753
 
  
1754
 
  /* Removes the temp directory used by GPGME */
1755
 
  if(tempdir_created){
1756
 
    DIR *d;
1757
 
    struct dirent *direntry;
1758
 
    d = opendir(tempdir);
1759
 
    if(d == NULL){
1760
 
      if(errno != ENOENT){
1761
 
        perror("opendir");
1762
 
      }
1763
 
    } else {
1764
 
      while(true){
1765
 
        direntry = readdir(d);
1766
 
        if(direntry == NULL){
1767
 
          break;
1768
 
        }
1769
 
        /* Skip "." and ".." */
1770
 
        if(direntry->d_name[0] == '.'
1771
 
           and (direntry->d_name[1] == '\0'
1772
 
                or (direntry->d_name[1] == '.'
1773
 
                    and direntry->d_name[2] == '\0'))){
1774
 
          continue;
1775
 
        }
1776
 
        char *fullname = NULL;
1777
 
        ret = asprintf(&fullname, "%s/%s", tempdir,
1778
 
                       direntry->d_name);
1779
 
        if(ret < 0){
1780
 
          perror("asprintf");
1781
 
          continue;
1782
 
        }
1783
 
        ret = remove(fullname);
1784
 
        if(ret == -1){
1785
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1786
 
                  strerror(errno));
1787
 
        }
1788
 
        free(fullname);
1789
 
      }
1790
 
      closedir(d);
1791
 
    }
1792
 
    ret = rmdir(tempdir);
1793
 
    if(ret == -1 and errno != ENOENT){
1794
 
      perror("rmdir");
1795
 
    }
1796
 
  }
1797
 
  
1798
 
  if(quit_now){
1799
 
    sigemptyset(&old_sigterm_action.sa_mask);
1800
 
    old_sigterm_action.sa_handler = SIG_DFL;
1801
 
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
1802
 
                                            &old_sigterm_action,
1803
 
                                            NULL));
1804
 
    if(ret == -1){
1805
 
      perror("sigaction");
1806
 
    }
1807
 
    do {
1808
 
      ret = raise(signal_received);
1809
 
    } while(ret != 0 and errno == EINTR);
1810
 
    if(ret != 0){
1811
 
      perror("raise");
1812
 
      abort();
1813
 
    }
1814
 
    TEMP_FAILURE_RETRY(pause());
1815
 
  }
1816
 
  
1817
 
  return exitcode;
 
803
 
 
804
    /* Check if creating the server object succeeded */
 
805
    if (!server) {
 
806
        fprintf(stderr, "Failed to create server: %s\n",
 
807
                avahi_strerror(error));
 
808
        returncode = EXIT_FAILURE;
 
809
        goto exit;
 
810
    }
 
811
    
 
812
    /* Create the service browser */
 
813
    sb = avahi_s_service_browser_new(server, if_index,
 
814
                                     AVAHI_PROTO_INET6,
 
815
                                     "_mandos._tcp", NULL, 0,
 
816
                                     browse_callback, server);
 
817
    if (!sb) {
 
818
        fprintf(stderr, "Failed to create service browser: %s\n",
 
819
                avahi_strerror(avahi_server_errno(server)));
 
820
        returncode = EXIT_FAILURE;
 
821
        goto exit;
 
822
    }
 
823
    
 
824
    /* Run the main loop */
 
825
 
 
826
    if (debug){
 
827
      fprintf(stderr, "Starting avahi loop search\n");
 
828
    }
 
829
    
 
830
    avahi_simple_poll_loop(simple_poll);
 
831
    
 
832
 exit:
 
833
 
 
834
    if (debug){
 
835
      fprintf(stderr, "%s exiting\n", argv[0]);
 
836
    }
 
837
    
 
838
    /* Cleanup things */
 
839
    if (sb)
 
840
        avahi_s_service_browser_free(sb);
 
841
    
 
842
    if (server)
 
843
        avahi_server_free(server);
 
844
 
 
845
    if (simple_poll)
 
846
        avahi_simple_poll_free(simple_poll);
 
847
    free(certfile);
 
848
    free(certkey);
 
849
    
 
850
    return returncode;
1818
851
}