/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

Intermediate commit - this does *not* work yet.

* plugins.d/mandos-client.c (HOOKDIR): New.
  (up_interface): New.
  (runnable_hook): New.
  (main): Run network hooks with "start" argument.

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 © 2007-2008 Teddy Hogeborn & Björn Påhlsson
 
12
 * Copyright © 2008-2011 Teddy Hogeborn
 
13
 * Copyright © 2008-2011 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 <mandos@fukt.bsnet.se>.
 
29
 * Contact the authors at <mandos@recompile.se>.
29
30
 */
30
31
 
31
32
/* Needed by GPGME, specifically gpgme_data_seek() */
 
33
#ifndef _LARGEFILE_SOURCE
32
34
#define _LARGEFILE_SOURCE
 
35
#endif
 
36
#ifndef _FILE_OFFSET_BITS
33
37
#define _FILE_OFFSET_BITS 64
34
 
 
35
 
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY() */
36
 
 
37
 
#include <stdio.h>              /* fprintf(), stderr, fwrite(), stdout,
38
 
                                   ferror() */
 
38
#endif
 
39
 
 
40
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
 
41
 
 
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
 
43
                                   stdout, ferror(), remove() */
39
44
#include <stdint.h>             /* uint16_t, uint32_t */
40
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
41
 
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
42
 
                                   srand() */
43
 
#include <stdbool.h>            /* bool, true */
 
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
 
47
                                   strtof(), abort() */
 
48
#include <stdbool.h>            /* bool, false, true */
44
49
#include <string.h>             /* memset(), strcmp(), strlen(),
45
 
                                   strerror(), memcpy(), strcpy() */
46
 
#include <sys/ioctl.h>          /* ioctl */
 
50
                                   strerror(), asprintf(), strcpy() */
 
51
#include <sys/ioctl.h>          /* ioctl */
47
52
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
48
53
                                   sockaddr_in6, PF_INET6,
49
 
                                   SOCK_STREAM, INET6_ADDRSTRLEN,
50
 
                                   uid_t, gid_t */
51
 
#include <inttypes.h>           /* PRIu16 */
 
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
 
55
                                   opendir(), DIR */
 
56
#include <sys/stat.h>           /* open() */
52
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
53
 
                                   struct in6_addr, inet_pton(),
54
 
                                   connect() */
 
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() */
55
64
#include <assert.h>             /* assert() */
56
 
#include <errno.h>              /* perror(), errno */
57
 
#include <time.h>               /* time() */
 
65
#include <errno.h>              /* perror(), errno,
 
66
                                   program_invocation_short_name */
 
67
#include <time.h>               /* nanosleep(), time(), sleep() */
58
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
59
69
                                   SIOCSIFFLAGS, if_indextoname(),
60
70
                                   if_nametoindex(), IF_NAMESIZE */
 
71
#include <netinet/in.h>         /* IN6_IS_ADDR_LINKLOCAL,
 
72
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
 
73
                                */
61
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
62
 
                                   getuid(), getgid(), setuid(),
63
 
                                   setgid() */
64
 
#include <netinet/in.h>
65
 
#include <arpa/inet.h>          /* inet_pton(), htons */
66
 
#include <iso646.h>             /* not, and */
 
75
                                   getuid(), getgid(), seteuid(),
 
76
                                   setgid(), pause() */
 
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
78
#include <iso646.h>             /* not, or, and */
67
79
#include <argp.h>               /* struct argp_option, error_t, struct
68
80
                                   argp_state, struct argp,
69
81
                                   argp_parse(), ARGP_KEY_ARG,
70
82
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
 
83
#include <signal.h>             /* sigemptyset(), sigaddset(),
 
84
                                   sigaction(), SIGTERM, sig_atomic_t,
 
85
                                   raise() */
 
86
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
 
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
 
88
 
 
89
#ifdef __linux__
 
90
#include <sys/klog.h>           /* klogctl() */
 
91
#endif  /* __linux__ */
71
92
 
72
93
/* Avahi */
73
94
/* All Avahi types, constants and functions
81
102
#include <avahi-common/error.h>
82
103
 
83
104
/* GnuTLS */
84
 
#include <gnutls/gnutls.h>      /* All GnuTLS types, constants and functions
 
105
#include <gnutls/gnutls.h>      /* All GnuTLS types, constants and
 
106
                                   functions:
85
107
                                   gnutls_*
86
108
                                   init_gnutls_session(),
87
109
                                   GNUTLS_* */
88
 
#include <gnutls/openpgp.h>     /* gnutls_certificate_set_openpgp_key_file(),
 
110
#include <gnutls/openpgp.h>
 
111
                          /* gnutls_certificate_set_openpgp_key_file(),
89
112
                                   GNUTLS_OPENPGP_FMT_BASE64 */
90
113
 
91
114
/* GPGME */
92
 
#include <gpgme.h>              /* All GPGME types, constants and functions
 
115
#include <gpgme.h>              /* All GPGME types, constants and
 
116
                                   functions:
93
117
                                   gpgme_*
94
118
                                   GPGME_PROTOCOL_OpenPGP,
95
119
                                   GPG_ERR_NO_* */
96
120
 
97
121
#define BUFFER_SIZE 256
98
122
 
 
123
#define PATHDIR "/conf/conf.d/mandos"
 
124
#define SECKEY "seckey.txt"
 
125
#define PUBKEY "pubkey.txt"
 
126
#define HOOKDIR "/lib/mandos/network-hooks.d"
 
127
 
99
128
bool debug = false;
100
 
static const char *keydir = "/conf/conf.d/mandos";
101
129
static const char mandos_protocol_version[] = "1";
102
 
const char *argp_program_version = "password-request 1.0";
103
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
130
const char *argp_program_version = "mandos-client " VERSION;
 
131
const char *argp_program_bug_address = "<mandos@recompile.se>";
 
132
static const char sys_class_net[] = "/sys/class/net";
 
133
char *connect_to = NULL;
 
134
 
 
135
/* Doubly linked list that need to be circularly linked when used */
 
136
typedef struct server{
 
137
  const char *ip;
 
138
  uint16_t port;
 
139
  AvahiIfIndex if_index;
 
140
  int af;
 
141
  struct timespec last_seen;
 
142
  struct server *next;
 
143
  struct server *prev;
 
144
} server;
104
145
 
105
146
/* Used for passing in values through the Avahi callback functions */
106
147
typedef struct {
110
151
  unsigned int dh_bits;
111
152
  gnutls_dh_params_t dh_params;
112
153
  const char *priority;
 
154
  gpgme_ctx_t ctx;
 
155
  server *current_server;
113
156
} mandos_context;
114
157
 
 
158
/* global context so signal handler can reach it*/
 
159
mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
160
                      .dh_bits = 1024, .priority = "SECURE256"
 
161
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
162
                      .current_server = NULL };
 
163
 
 
164
sig_atomic_t quit_now = 0;
 
165
int signal_received = 0;
 
166
 
 
167
/* Function to use when printing errors */
 
168
void perror_plus(const char *print_text){
 
169
  fprintf(stderr, "Mandos plugin %s: ",
 
170
          program_invocation_short_name);
 
171
  perror(print_text);
 
172
}
 
173
 
115
174
/*
116
 
 * Make room in "buffer" for at least BUFFER_SIZE additional bytes.
117
 
 * "buffer_capacity" is how much is currently allocated,
 
175
 * Make additional room in "buffer" for at least BUFFER_SIZE more
 
176
 * bytes. "buffer_capacity" is how much is currently allocated,
118
177
 * "buffer_length" is how much is already used.
119
178
 */
120
 
size_t adjustbuffer(char **buffer, size_t buffer_length,
 
179
size_t incbuffer(char **buffer, size_t buffer_length,
121
180
                  size_t buffer_capacity){
122
 
  if (buffer_length + BUFFER_SIZE > buffer_capacity){
 
181
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
123
182
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
124
 
    if (buffer == NULL){
 
183
    if(buffer == NULL){
125
184
      return 0;
126
185
    }
127
186
    buffer_capacity += BUFFER_SIZE;
129
188
  return buffer_capacity;
130
189
}
131
190
 
 
191
/* Add server to set of servers to retry periodically */
 
192
int add_server(const char *ip, uint16_t port,
 
193
                 AvahiIfIndex if_index,
 
194
                 int af){
 
195
  int ret;
 
196
  server *new_server = malloc(sizeof(server));
 
197
  if(new_server == NULL){
 
198
    perror_plus("malloc");
 
199
    return -1;
 
200
  }
 
201
  *new_server = (server){ .ip = strdup(ip),
 
202
                         .port = port,
 
203
                         .if_index = if_index,
 
204
                         .af = af };
 
205
  if(new_server->ip == NULL){
 
206
    perror_plus("strdup");
 
207
    return -1;
 
208
  }
 
209
  /* Special case of first server */
 
210
  if (mc.current_server == NULL){
 
211
    new_server->next = new_server;
 
212
    new_server->prev = new_server;
 
213
    mc.current_server = new_server;
 
214
  /* Place the new server last in the list */
 
215
  } else {
 
216
    new_server->next = mc.current_server;
 
217
    new_server->prev = mc.current_server->prev;
 
218
    new_server->prev->next = new_server;
 
219
    mc.current_server->prev = new_server;
 
220
  }
 
221
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
222
  if(ret == -1){
 
223
    perror_plus("clock_gettime");
 
224
    return -1;
 
225
  }
 
226
  return 0;
 
227
}
 
228
 
132
229
/* 
133
 
 * Decrypt OpenPGP data using keyrings in HOMEDIR.
134
 
 * Returns -1 on error
 
230
 * Initialize GPGME.
135
231
 */
136
 
static ssize_t pgp_packet_decrypt (const char *cryptotext,
137
 
                                   size_t crypto_size,
138
 
                                   char **plaintext,
139
 
                                   const char *homedir){
140
 
  gpgme_data_t dh_crypto, dh_plain;
141
 
  gpgme_ctx_t ctx;
 
232
static bool init_gpgme(const char *seckey,
 
233
                       const char *pubkey, const char *tempdir){
142
234
  gpgme_error_t rc;
143
 
  ssize_t ret;
144
 
  size_t plaintext_capacity = 0;
145
 
  ssize_t plaintext_length = 0;
146
235
  gpgme_engine_info_t engine_info;
147
236
  
148
 
  if (debug){
149
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
237
  
 
238
  /*
 
239
   * Helper function to insert pub and seckey to the engine keyring.
 
240
   */
 
241
  bool import_key(const char *filename){
 
242
    int ret;
 
243
    int fd;
 
244
    gpgme_data_t pgp_data;
 
245
    
 
246
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
 
247
    if(fd == -1){
 
248
      perror_plus("open");
 
249
      return false;
 
250
    }
 
251
    
 
252
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
 
253
    if(rc != GPG_ERR_NO_ERROR){
 
254
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
255
              gpgme_strsource(rc), gpgme_strerror(rc));
 
256
      return false;
 
257
    }
 
258
    
 
259
    rc = gpgme_op_import(mc.ctx, pgp_data);
 
260
    if(rc != GPG_ERR_NO_ERROR){
 
261
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
262
              gpgme_strsource(rc), gpgme_strerror(rc));
 
263
      return false;
 
264
    }
 
265
    
 
266
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
 
267
    if(ret == -1){
 
268
      perror_plus("close");
 
269
    }
 
270
    gpgme_data_release(pgp_data);
 
271
    return true;
 
272
  }
 
273
  
 
274
  if(debug){
 
275
    fprintf(stderr, "Initializing GPGME\n");
150
276
  }
151
277
  
152
278
  /* Init GPGME */
153
279
  gpgme_check_version(NULL);
154
280
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
155
 
  if (rc != GPG_ERR_NO_ERROR){
 
281
  if(rc != GPG_ERR_NO_ERROR){
156
282
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
157
283
            gpgme_strsource(rc), gpgme_strerror(rc));
158
 
    return -1;
 
284
    return false;
159
285
  }
160
286
  
161
287
  /* Set GPGME home directory for the OpenPGP engine only */
162
 
  rc = gpgme_get_engine_info (&engine_info);
163
 
  if (rc != GPG_ERR_NO_ERROR){
 
288
  rc = gpgme_get_engine_info(&engine_info);
 
289
  if(rc != GPG_ERR_NO_ERROR){
164
290
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
165
291
            gpgme_strsource(rc), gpgme_strerror(rc));
166
 
    return -1;
 
292
    return false;
167
293
  }
168
294
  while(engine_info != NULL){
169
295
    if(engine_info->protocol == GPGME_PROTOCOL_OpenPGP){
170
296
      gpgme_set_engine_info(GPGME_PROTOCOL_OpenPGP,
171
 
                            engine_info->file_name, homedir);
 
297
                            engine_info->file_name, tempdir);
172
298
      break;
173
299
    }
174
300
    engine_info = engine_info->next;
175
301
  }
176
302
  if(engine_info == NULL){
177
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", homedir);
178
 
    return -1;
 
303
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
304
    return false;
 
305
  }
 
306
  
 
307
  /* Create new GPGME "context" */
 
308
  rc = gpgme_new(&(mc.ctx));
 
309
  if(rc != GPG_ERR_NO_ERROR){
 
310
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
311
            gpgme_strsource(rc), gpgme_strerror(rc));
 
312
    return false;
 
313
  }
 
314
  
 
315
  if(not import_key(pubkey) or not import_key(seckey)){
 
316
    return false;
 
317
  }
 
318
  
 
319
  return true;
 
320
}
 
321
 
 
322
/* 
 
323
 * Decrypt OpenPGP data.
 
324
 * Returns -1 on error
 
325
 */
 
326
static ssize_t pgp_packet_decrypt(const char *cryptotext,
 
327
                                  size_t crypto_size,
 
328
                                  char **plaintext){
 
329
  gpgme_data_t dh_crypto, dh_plain;
 
330
  gpgme_error_t rc;
 
331
  ssize_t ret;
 
332
  size_t plaintext_capacity = 0;
 
333
  ssize_t plaintext_length = 0;
 
334
  
 
335
  if(debug){
 
336
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
179
337
  }
180
338
  
181
339
  /* Create new GPGME data buffer from memory cryptotext */
182
340
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
183
341
                               0);
184
 
  if (rc != GPG_ERR_NO_ERROR){
 
342
  if(rc != GPG_ERR_NO_ERROR){
185
343
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
186
344
            gpgme_strsource(rc), gpgme_strerror(rc));
187
345
    return -1;
189
347
  
190
348
  /* Create new empty GPGME data buffer for the plaintext */
191
349
  rc = gpgme_data_new(&dh_plain);
192
 
  if (rc != GPG_ERR_NO_ERROR){
 
350
  if(rc != GPG_ERR_NO_ERROR){
193
351
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
194
352
            gpgme_strsource(rc), gpgme_strerror(rc));
195
353
    gpgme_data_release(dh_crypto);
196
354
    return -1;
197
355
  }
198
356
  
199
 
  /* Create new GPGME "context" */
200
 
  rc = gpgme_new(&ctx);
201
 
  if (rc != GPG_ERR_NO_ERROR){
202
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
203
 
            gpgme_strsource(rc), gpgme_strerror(rc));
204
 
    plaintext_length = -1;
205
 
    goto decrypt_end;
206
 
  }
207
 
  
208
357
  /* Decrypt data from the cryptotext data buffer to the plaintext
209
358
     data buffer */
210
 
  rc = gpgme_op_decrypt(ctx, dh_crypto, dh_plain);
211
 
  if (rc != GPG_ERR_NO_ERROR){
 
359
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
 
360
  if(rc != GPG_ERR_NO_ERROR){
212
361
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
213
362
            gpgme_strsource(rc), gpgme_strerror(rc));
214
363
    plaintext_length = -1;
215
 
    goto decrypt_end;
216
 
  }
217
 
  
218
 
  if(debug){
219
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
220
 
  }
221
 
  
222
 
  if (debug){
223
 
    gpgme_decrypt_result_t result;
224
 
    result = gpgme_op_decrypt_result(ctx);
225
 
    if (result == NULL){
226
 
      fprintf(stderr, "gpgme_op_decrypt_result failed\n");
227
 
    } else {
228
 
      fprintf(stderr, "Unsupported algorithm: %s\n",
229
 
              result->unsupported_algorithm);
230
 
      fprintf(stderr, "Wrong key usage: %u\n",
231
 
              result->wrong_key_usage);
232
 
      if(result->file_name != NULL){
233
 
        fprintf(stderr, "File name: %s\n", result->file_name);
234
 
      }
235
 
      gpgme_recipient_t recipient;
236
 
      recipient = result->recipients;
237
 
      if(recipient){
 
364
    if(debug){
 
365
      gpgme_decrypt_result_t result;
 
366
      result = gpgme_op_decrypt_result(mc.ctx);
 
367
      if(result == NULL){
 
368
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
369
      } else {
 
370
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
371
                result->unsupported_algorithm);
 
372
        fprintf(stderr, "Wrong key usage: %u\n",
 
373
                result->wrong_key_usage);
 
374
        if(result->file_name != NULL){
 
375
          fprintf(stderr, "File name: %s\n", result->file_name);
 
376
        }
 
377
        gpgme_recipient_t recipient;
 
378
        recipient = result->recipients;
238
379
        while(recipient != NULL){
239
380
          fprintf(stderr, "Public key algorithm: %s\n",
240
381
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
246
387
        }
247
388
      }
248
389
    }
 
390
    goto decrypt_end;
 
391
  }
 
392
  
 
393
  if(debug){
 
394
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
249
395
  }
250
396
  
251
397
  /* Seek back to the beginning of the GPGME plaintext data buffer */
252
 
  if (gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET) == -1){
253
 
    perror("pgpme_data_seek");
 
398
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
 
399
    perror_plus("gpgme_data_seek");
254
400
    plaintext_length = -1;
255
401
    goto decrypt_end;
256
402
  }
257
403
  
258
404
  *plaintext = NULL;
259
405
  while(true){
260
 
    plaintext_capacity = adjustbuffer(plaintext,
 
406
    plaintext_capacity = incbuffer(plaintext,
261
407
                                      (size_t)plaintext_length,
262
408
                                      plaintext_capacity);
263
 
    if (plaintext_capacity == 0){
264
 
        perror("adjustbuffer");
 
409
    if(plaintext_capacity == 0){
 
410
        perror_plus("incbuffer");
265
411
        plaintext_length = -1;
266
412
        goto decrypt_end;
267
413
    }
269
415
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
270
416
                          BUFFER_SIZE);
271
417
    /* Print the data, if any */
272
 
    if (ret == 0){
 
418
    if(ret == 0){
273
419
      /* EOF */
274
420
      break;
275
421
    }
276
422
    if(ret < 0){
277
 
      perror("gpgme_data_read");
 
423
      perror_plus("gpgme_data_read");
278
424
      plaintext_length = -1;
279
425
      goto decrypt_end;
280
426
    }
281
427
    plaintext_length += ret;
282
428
  }
283
 
 
 
429
  
284
430
  if(debug){
285
431
    fprintf(stderr, "Decrypted password is: ");
286
432
    for(ssize_t i = 0; i < plaintext_length; i++){
299
445
  return plaintext_length;
300
446
}
301
447
 
302
 
static const char * safer_gnutls_strerror (int value) {
303
 
  const char *ret = gnutls_strerror (value);
304
 
  if (ret == NULL)
 
448
static const char * safer_gnutls_strerror(int value){
 
449
  const char *ret = gnutls_strerror(value); /* Spurious warning from
 
450
                                               -Wunreachable-code */
 
451
  if(ret == NULL)
305
452
    ret = "(unknown)";
306
453
  return ret;
307
454
}
312
459
  fprintf(stderr, "GnuTLS: %s", string);
313
460
}
314
461
 
315
 
static int init_gnutls_global(mandos_context *mc,
316
 
                              const char *pubkeyfile,
317
 
                              const char *seckeyfile){
 
462
static int init_gnutls_global(const char *pubkeyfilename,
 
463
                              const char *seckeyfilename){
318
464
  int ret;
319
465
  
320
466
  if(debug){
322
468
  }
323
469
  
324
470
  ret = gnutls_global_init();
325
 
  if (ret != GNUTLS_E_SUCCESS) {
326
 
    fprintf (stderr, "GnuTLS global_init: %s\n",
327
 
             safer_gnutls_strerror(ret));
 
471
  if(ret != GNUTLS_E_SUCCESS){
 
472
    fprintf(stderr, "GnuTLS global_init: %s\n",
 
473
            safer_gnutls_strerror(ret));
328
474
    return -1;
329
475
  }
330
476
  
331
 
  if (debug){
 
477
  if(debug){
332
478
    /* "Use a log level over 10 to enable all debugging options."
333
479
     * - GnuTLS manual
334
480
     */
337
483
  }
338
484
  
339
485
  /* OpenPGP credentials */
340
 
  gnutls_certificate_allocate_credentials(&mc->cred);
341
 
  if (ret != GNUTLS_E_SUCCESS){
342
 
    fprintf (stderr, "GnuTLS memory error: %s\n",
343
 
             safer_gnutls_strerror(ret));
344
 
    gnutls_global_deinit ();
 
486
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
487
  if(ret != GNUTLS_E_SUCCESS){
 
488
    fprintf(stderr, "GnuTLS memory error: %s\n",
 
489
            safer_gnutls_strerror(ret));
 
490
    gnutls_global_deinit();
345
491
    return -1;
346
492
  }
347
493
  
348
494
  if(debug){
349
 
    fprintf(stderr, "Attempting to use OpenPGP certificate %s"
350
 
            " and keyfile %s as GnuTLS credentials\n", pubkeyfile,
351
 
            seckeyfile);
 
495
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
496
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
 
497
            seckeyfilename);
352
498
  }
353
499
  
354
500
  ret = gnutls_certificate_set_openpgp_key_file
355
 
    (mc->cred, pubkeyfile, seckeyfile, GNUTLS_OPENPGP_FMT_BASE64);
356
 
  if (ret != GNUTLS_E_SUCCESS) {
 
501
    (mc.cred, pubkeyfilename, seckeyfilename,
 
502
     GNUTLS_OPENPGP_FMT_BASE64);
 
503
  if(ret != GNUTLS_E_SUCCESS){
357
504
    fprintf(stderr,
358
505
            "Error[%d] while reading the OpenPGP key pair ('%s',"
359
 
            " '%s')\n", ret, pubkeyfile, seckeyfile);
360
 
    fprintf(stdout, "The GnuTLS error is: %s\n",
 
506
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
507
    fprintf(stderr, "The GnuTLS error is: %s\n",
361
508
            safer_gnutls_strerror(ret));
362
509
    goto globalfail;
363
510
  }
364
511
  
365
512
  /* GnuTLS server initialization */
366
 
  ret = gnutls_dh_params_init(&mc->dh_params);
367
 
  if (ret != GNUTLS_E_SUCCESS) {
368
 
    fprintf (stderr, "Error in GnuTLS DH parameter initialization:"
369
 
             " %s\n", safer_gnutls_strerror(ret));
370
 
    goto globalfail;
371
 
  }
372
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
373
 
  if (ret != GNUTLS_E_SUCCESS) {
374
 
    fprintf (stderr, "Error in GnuTLS prime generation: %s\n",
375
 
             safer_gnutls_strerror(ret));
376
 
    goto globalfail;
377
 
  }
378
 
  
379
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
380
 
 
 
513
  ret = gnutls_dh_params_init(&mc.dh_params);
 
514
  if(ret != GNUTLS_E_SUCCESS){
 
515
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
516
            " %s\n", safer_gnutls_strerror(ret));
 
517
    goto globalfail;
 
518
  }
 
519
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
520
  if(ret != GNUTLS_E_SUCCESS){
 
521
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
522
            safer_gnutls_strerror(ret));
 
523
    goto globalfail;
 
524
  }
 
525
  
 
526
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
 
527
  
381
528
  return 0;
382
 
 
 
529
  
383
530
 globalfail:
384
 
 
385
 
  gnutls_certificate_free_credentials(mc->cred);
 
531
  
 
532
  gnutls_certificate_free_credentials(mc.cred);
386
533
  gnutls_global_deinit();
 
534
  gnutls_dh_params_deinit(mc.dh_params);
387
535
  return -1;
388
 
 
389
536
}
390
537
 
391
 
static int init_gnutls_session(mandos_context *mc,
392
 
                               gnutls_session_t *session){
 
538
static int init_gnutls_session(gnutls_session_t *session){
393
539
  int ret;
394
540
  /* GnuTLS session creation */
395
 
  ret = gnutls_init(session, GNUTLS_SERVER);
396
 
  if (ret != GNUTLS_E_SUCCESS){
 
541
  do {
 
542
    ret = gnutls_init(session, GNUTLS_SERVER);
 
543
    if(quit_now){
 
544
      return -1;
 
545
    }
 
546
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
 
547
  if(ret != GNUTLS_E_SUCCESS){
397
548
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
398
549
            safer_gnutls_strerror(ret));
399
550
  }
400
551
  
401
552
  {
402
553
    const char *err;
403
 
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
404
 
    if (ret != GNUTLS_E_SUCCESS) {
 
554
    do {
 
555
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
556
      if(quit_now){
 
557
        gnutls_deinit(*session);
 
558
        return -1;
 
559
      }
 
560
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
 
561
    if(ret != GNUTLS_E_SUCCESS){
405
562
      fprintf(stderr, "Syntax error at: %s\n", err);
406
563
      fprintf(stderr, "GnuTLS error: %s\n",
407
564
              safer_gnutls_strerror(ret));
408
 
      gnutls_deinit (*session);
 
565
      gnutls_deinit(*session);
409
566
      return -1;
410
567
    }
411
568
  }
412
569
  
413
 
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
414
 
                               mc->cred);
415
 
  if (ret != GNUTLS_E_SUCCESS) {
 
570
  do {
 
571
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
 
572
                                 mc.cred);
 
573
    if(quit_now){
 
574
      gnutls_deinit(*session);
 
575
      return -1;
 
576
    }
 
577
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
 
578
  if(ret != GNUTLS_E_SUCCESS){
416
579
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
417
580
            safer_gnutls_strerror(ret));
418
 
    gnutls_deinit (*session);
 
581
    gnutls_deinit(*session);
419
582
    return -1;
420
583
  }
421
584
  
422
585
  /* ignore client certificate if any. */
423
 
  gnutls_certificate_server_set_request (*session,
424
 
                                         GNUTLS_CERT_IGNORE);
 
586
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
425
587
  
426
 
  gnutls_dh_set_prime_bits (*session, mc->dh_bits);
 
588
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
427
589
  
428
590
  return 0;
429
591
}
435
597
/* Called when a Mandos server is found */
436
598
static int start_mandos_communication(const char *ip, uint16_t port,
437
599
                                      AvahiIfIndex if_index,
438
 
                                      mandos_context *mc){
439
 
  int ret, tcp_sd;
440
 
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
 
600
                                      int af){
 
601
  int ret, tcp_sd = -1;
 
602
  ssize_t sret;
 
603
  union {
 
604
    struct sockaddr_in in;
 
605
    struct sockaddr_in6 in6;
 
606
  } to;
441
607
  char *buffer = NULL;
442
 
  char *decrypted_buffer;
 
608
  char *decrypted_buffer = NULL;
443
609
  size_t buffer_length = 0;
444
610
  size_t buffer_capacity = 0;
445
 
  ssize_t decrypted_buffer_size;
446
611
  size_t written;
447
 
  int retval = 0;
448
 
  char interface[IF_NAMESIZE];
 
612
  int retval = -1;
449
613
  gnutls_session_t session;
450
 
  
451
 
  ret = init_gnutls_session (mc, &session);
452
 
  if (ret != 0){
 
614
  int pf;                       /* Protocol family */
 
615
  
 
616
  errno = 0;
 
617
  
 
618
  if(quit_now){
 
619
    errno = EINTR;
 
620
    return -1;
 
621
  }
 
622
  
 
623
  switch(af){
 
624
  case AF_INET6:
 
625
    pf = PF_INET6;
 
626
    break;
 
627
  case AF_INET:
 
628
    pf = PF_INET;
 
629
    break;
 
630
  default:
 
631
    fprintf(stderr, "Bad address family: %d\n", af);
 
632
    errno = EINVAL;
 
633
    return -1;
 
634
  }
 
635
  
 
636
  ret = init_gnutls_session(&session);
 
637
  if(ret != 0){
453
638
    return -1;
454
639
  }
455
640
  
456
641
  if(debug){
457
 
    fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
 
642
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
458
643
            "\n", ip, port);
459
644
  }
460
645
  
461
 
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
462
 
  if(tcp_sd < 0) {
463
 
    perror("socket");
464
 
    return -1;
465
 
  }
466
 
 
467
 
  if(debug){
468
 
    if(if_indextoname((unsigned int)if_index, interface) == NULL){
469
 
      perror("if_indextoname");
470
 
      return -1;
471
 
    }
472
 
    fprintf(stderr, "Binding to interface %s\n", interface);
473
 
  }
474
 
  
475
 
  memset(&to,0,sizeof(to));     /* Spurious warning */
476
 
  to.in6.sin6_family = AF_INET6;
477
 
  /* It would be nice to have a way to detect if we were passed an
478
 
     IPv4 address here.   Now we assume an IPv6 address. */
479
 
  ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
480
 
  if (ret < 0 ){
481
 
    perror("inet_pton");
482
 
    return -1;
 
646
  tcp_sd = socket(pf, SOCK_STREAM, 0);
 
647
  if(tcp_sd < 0){
 
648
    int e = errno;
 
649
    perror_plus("socket");
 
650
    errno = e;
 
651
    goto mandos_end;
 
652
  }
 
653
  
 
654
  if(quit_now){
 
655
    errno = EINTR;
 
656
    goto mandos_end;
 
657
  }
 
658
  
 
659
  memset(&to, 0, sizeof(to));
 
660
  if(af == AF_INET6){
 
661
    to.in6.sin6_family = (sa_family_t)af;
 
662
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
 
663
  } else {                      /* IPv4 */
 
664
    to.in.sin_family = (sa_family_t)af;
 
665
    ret = inet_pton(af, ip, &to.in.sin_addr);
 
666
  }
 
667
  if(ret < 0 ){
 
668
    int e = errno;
 
669
    perror_plus("inet_pton");
 
670
    errno = e;
 
671
    goto mandos_end;
483
672
  }
484
673
  if(ret == 0){
 
674
    int e = errno;
485
675
    fprintf(stderr, "Bad address: %s\n", ip);
486
 
    return -1;
487
 
  }
488
 
  to.in6.sin6_port = htons(port); /* Spurious warning */
 
676
    errno = e;
 
677
    goto mandos_end;
 
678
  }
 
679
  if(af == AF_INET6){
 
680
    to.in6.sin6_port = htons(port); /* Spurious warnings from
 
681
                                       -Wconversion and
 
682
                                       -Wunreachable-code */
 
683
    
 
684
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
685
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
 
686
                              -Wunreachable-code*/
 
687
      if(if_index == AVAHI_IF_UNSPEC){
 
688
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
689
                " without a network interface\n");
 
690
        errno = EINVAL;
 
691
        goto mandos_end;
 
692
      }
 
693
      /* Set the network interface number as scope */
 
694
      to.in6.sin6_scope_id = (uint32_t)if_index;
 
695
    }
 
696
  } else {
 
697
    to.in.sin_port = htons(port); /* Spurious warnings from
 
698
                                     -Wconversion and
 
699
                                     -Wunreachable-code */
 
700
  }
489
701
  
490
 
  to.in6.sin6_scope_id = (uint32_t)if_index;
 
702
  if(quit_now){
 
703
    errno = EINTR;
 
704
    goto mandos_end;
 
705
  }
491
706
  
492
707
  if(debug){
493
 
    fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
494
 
            port);
495
 
    char addrstr[INET6_ADDRSTRLEN] = "";
496
 
    if(inet_ntop(to.in6.sin6_family, &(to.in6.sin6_addr), addrstr,
497
 
                 sizeof(addrstr)) == NULL){
498
 
      perror("inet_ntop");
 
708
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
 
709
      char interface[IF_NAMESIZE];
 
710
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
711
        perror_plus("if_indextoname");
 
712
      } else {
 
713
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
714
                ip, interface, port);
 
715
      }
 
716
    } else {
 
717
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
718
              port);
 
719
    }
 
720
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
 
721
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
 
722
    const char *pcret;
 
723
    if(af == AF_INET6){
 
724
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
725
                        sizeof(addrstr));
 
726
    } else {
 
727
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
728
                        sizeof(addrstr));
 
729
    }
 
730
    if(pcret == NULL){
 
731
      perror_plus("inet_ntop");
499
732
    } else {
500
733
      if(strcmp(addrstr, ip) != 0){
501
734
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
503
736
    }
504
737
  }
505
738
  
506
 
  ret = connect(tcp_sd, &to.in, sizeof(to));
507
 
  if (ret < 0){
508
 
    perror("connect");
509
 
    return -1;
510
 
  }
511
 
 
 
739
  if(quit_now){
 
740
    errno = EINTR;
 
741
    goto mandos_end;
 
742
  }
 
743
  
 
744
  if(af == AF_INET6){
 
745
    ret = connect(tcp_sd, &to.in6, sizeof(to));
 
746
  } else {
 
747
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
 
748
  }
 
749
  if(ret < 0){
 
750
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
751
      int e = errno;
 
752
      perror_plus("connect");
 
753
      errno = e;
 
754
    }
 
755
    goto mandos_end;
 
756
  }
 
757
  
 
758
  if(quit_now){
 
759
    errno = EINTR;
 
760
    goto mandos_end;
 
761
  }
 
762
  
512
763
  const char *out = mandos_protocol_version;
513
764
  written = 0;
514
 
  while (true){
 
765
  while(true){
515
766
    size_t out_size = strlen(out);
516
 
    ret = TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
 
767
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
517
768
                                   out_size - written));
518
 
    if (ret == -1){
519
 
      perror("write");
520
 
      retval = -1;
 
769
    if(ret == -1){
 
770
      int e = errno;
 
771
      perror_plus("write");
 
772
      errno = e;
521
773
      goto mandos_end;
522
774
    }
523
775
    written += (size_t)ret;
524
776
    if(written < out_size){
525
777
      continue;
526
778
    } else {
527
 
      if (out == mandos_protocol_version){
 
779
      if(out == mandos_protocol_version){
528
780
        written = 0;
529
781
        out = "\r\n";
530
782
      } else {
531
783
        break;
532
784
      }
533
785
    }
 
786
  
 
787
    if(quit_now){
 
788
      errno = EINTR;
 
789
      goto mandos_end;
 
790
    }
534
791
  }
535
 
 
 
792
  
536
793
  if(debug){
537
794
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
538
795
  }
539
796
  
540
 
  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) tcp_sd);
541
 
 
542
 
  do{
543
 
    ret = gnutls_handshake (session);
 
797
  if(quit_now){
 
798
    errno = EINTR;
 
799
    goto mandos_end;
 
800
  }
 
801
  
 
802
  /* Spurious warning from -Wint-to-pointer-cast */
 
803
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
 
804
  
 
805
  if(quit_now){
 
806
    errno = EINTR;
 
807
    goto mandos_end;
 
808
  }
 
809
  
 
810
  do {
 
811
    ret = gnutls_handshake(session);
 
812
    if(quit_now){
 
813
      errno = EINTR;
 
814
      goto mandos_end;
 
815
    }
544
816
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
545
817
  
546
 
  if (ret != GNUTLS_E_SUCCESS){
 
818
  if(ret != GNUTLS_E_SUCCESS){
547
819
    if(debug){
548
820
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
549
 
      gnutls_perror (ret);
 
821
      gnutls_perror(ret);
550
822
    }
551
 
    retval = -1;
 
823
    errno = EPROTO;
552
824
    goto mandos_end;
553
825
  }
554
826
  
555
827
  /* Read OpenPGP packet that contains the wanted password */
556
828
  
557
829
  if(debug){
558
 
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
 
830
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
559
831
            ip);
560
832
  }
561
 
 
 
833
  
562
834
  while(true){
563
 
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
 
835
    
 
836
    if(quit_now){
 
837
      errno = EINTR;
 
838
      goto mandos_end;
 
839
    }
 
840
    
 
841
    buffer_capacity = incbuffer(&buffer, buffer_length,
564
842
                                   buffer_capacity);
565
 
    if (buffer_capacity == 0){
566
 
      perror("adjustbuffer");
567
 
      retval = -1;
568
 
      goto mandos_end;
569
 
    }
570
 
    
571
 
    ret = gnutls_record_recv(session, buffer+buffer_length,
572
 
                             BUFFER_SIZE);
573
 
    if (ret == 0){
 
843
    if(buffer_capacity == 0){
 
844
      int e = errno;
 
845
      perror_plus("incbuffer");
 
846
      errno = e;
 
847
      goto mandos_end;
 
848
    }
 
849
    
 
850
    if(quit_now){
 
851
      errno = EINTR;
 
852
      goto mandos_end;
 
853
    }
 
854
    
 
855
    sret = gnutls_record_recv(session, buffer+buffer_length,
 
856
                              BUFFER_SIZE);
 
857
    if(sret == 0){
574
858
      break;
575
859
    }
576
 
    if (ret < 0){
577
 
      switch(ret){
 
860
    if(sret < 0){
 
861
      switch(sret){
578
862
      case GNUTLS_E_INTERRUPTED:
579
863
      case GNUTLS_E_AGAIN:
580
864
        break;
581
865
      case GNUTLS_E_REHANDSHAKE:
582
 
        do{
583
 
          ret = gnutls_handshake (session);
 
866
        do {
 
867
          ret = gnutls_handshake(session);
 
868
          
 
869
          if(quit_now){
 
870
            errno = EINTR;
 
871
            goto mandos_end;
 
872
          }
584
873
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
585
 
        if (ret < 0){
 
874
        if(ret < 0){
586
875
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
587
 
          gnutls_perror (ret);
588
 
          retval = -1;
 
876
          gnutls_perror(ret);
 
877
          errno = EPROTO;
589
878
          goto mandos_end;
590
879
        }
591
880
        break;
592
881
      default:
593
882
        fprintf(stderr, "Unknown error while reading data from"
594
883
                " encrypted session with Mandos server\n");
595
 
        retval = -1;
596
 
        gnutls_bye (session, GNUTLS_SHUT_RDWR);
 
884
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
885
        errno = EIO;
597
886
        goto mandos_end;
598
887
      }
599
888
    } else {
600
 
      buffer_length += (size_t) ret;
 
889
      buffer_length += (size_t) sret;
601
890
    }
602
891
  }
603
892
  
605
894
    fprintf(stderr, "Closing TLS session\n");
606
895
  }
607
896
  
608
 
  gnutls_bye (session, GNUTLS_SHUT_RDWR);
609
 
  
610
 
  if (buffer_length > 0){
 
897
  if(quit_now){
 
898
    errno = EINTR;
 
899
    goto mandos_end;
 
900
  }
 
901
  
 
902
  do {
 
903
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
904
    if(quit_now){
 
905
      errno = EINTR;
 
906
      goto mandos_end;
 
907
    }
 
908
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
 
909
  
 
910
  if(buffer_length > 0){
 
911
    ssize_t decrypted_buffer_size;
611
912
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
612
913
                                               buffer_length,
613
 
                                               &decrypted_buffer,
614
 
                                               keydir);
615
 
    if (decrypted_buffer_size >= 0){
 
914
                                               &decrypted_buffer);
 
915
    if(decrypted_buffer_size >= 0){
 
916
      
616
917
      written = 0;
617
918
      while(written < (size_t) decrypted_buffer_size){
618
 
        ret = (int)fwrite (decrypted_buffer + written, 1,
619
 
                           (size_t)decrypted_buffer_size - written,
620
 
                           stdout);
 
919
        if(quit_now){
 
920
          errno = EINTR;
 
921
          goto mandos_end;
 
922
        }
 
923
        
 
924
        ret = (int)fwrite(decrypted_buffer + written, 1,
 
925
                          (size_t)decrypted_buffer_size - written,
 
926
                          stdout);
621
927
        if(ret == 0 and ferror(stdout)){
 
928
          int e = errno;
622
929
          if(debug){
623
930
            fprintf(stderr, "Error writing encrypted data: %s\n",
624
931
                    strerror(errno));
625
932
          }
626
 
          retval = -1;
627
 
          break;
 
933
          errno = e;
 
934
          goto mandos_end;
628
935
        }
629
936
        written += (size_t)ret;
630
937
      }
631
 
      free(decrypted_buffer);
632
 
    } else {
633
 
      retval = -1;
 
938
      retval = 0;
634
939
    }
635
940
  }
636
941
  
637
942
  /* Shutdown procedure */
638
943
  
639
944
 mandos_end:
640
 
  free(buffer);
641
 
  close(tcp_sd);
642
 
  gnutls_deinit (session);
 
945
  {
 
946
    int e = errno;
 
947
    free(decrypted_buffer);
 
948
    free(buffer);
 
949
    if(tcp_sd >= 0){
 
950
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
951
    }
 
952
    if(ret == -1){
 
953
      if(e == 0){
 
954
        e = errno;
 
955
      }
 
956
      perror_plus("close");
 
957
    }
 
958
    gnutls_deinit(session);
 
959
    errno = e;
 
960
    if(quit_now){
 
961
      errno = EINTR;
 
962
      retval = -1;
 
963
    }
 
964
  }
643
965
  return retval;
644
966
}
645
967
 
646
968
static void resolve_callback(AvahiSServiceResolver *r,
647
969
                             AvahiIfIndex interface,
648
 
                             AVAHI_GCC_UNUSED AvahiProtocol protocol,
 
970
                             AvahiProtocol proto,
649
971
                             AvahiResolverEvent event,
650
972
                             const char *name,
651
973
                             const char *type,
656
978
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
657
979
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
658
980
                             flags,
659
 
                             void* userdata) {
660
 
  mandos_context *mc = userdata;
661
 
  assert(r);                    /* Spurious warning */
 
981
                             AVAHI_GCC_UNUSED void* userdata){
 
982
  assert(r);
662
983
  
663
984
  /* Called whenever a service has been resolved successfully or
664
985
     timed out */
665
986
  
666
 
  switch (event) {
 
987
  if(quit_now){
 
988
    return;
 
989
  }
 
990
  
 
991
  switch(event){
667
992
  default:
668
993
  case AVAHI_RESOLVER_FAILURE:
669
994
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
670
995
            " of type '%s' in domain '%s': %s\n", name, type, domain,
671
 
            avahi_strerror(avahi_server_errno(mc->server)));
 
996
            avahi_strerror(avahi_server_errno(mc.server)));
672
997
    break;
673
998
    
674
999
  case AVAHI_RESOLVER_FOUND:
677
1002
      avahi_address_snprint(ip, sizeof(ip), address);
678
1003
      if(debug){
679
1004
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
680
 
                PRIu16 ") on port %d\n", name, host_name, ip,
681
 
                interface, port);
 
1005
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
 
1006
                ip, (intmax_t)interface, port);
682
1007
      }
683
 
      int ret = start_mandos_communication(ip, port, interface, mc);
684
 
      if (ret == 0){
685
 
        avahi_simple_poll_quit(mc->simple_poll);
 
1008
      int ret = start_mandos_communication(ip, port, interface,
 
1009
                                           avahi_proto_to_af(proto));
 
1010
      if(ret == 0){
 
1011
        avahi_simple_poll_quit(mc.simple_poll);
 
1012
      } else {
 
1013
        ret = add_server(ip, port, interface,
 
1014
                         avahi_proto_to_af(proto));
686
1015
      }
687
1016
    }
688
1017
  }
689
1018
  avahi_s_service_resolver_free(r);
690
1019
}
691
1020
 
692
 
static void browse_callback( AvahiSServiceBrowser *b,
693
 
                             AvahiIfIndex interface,
694
 
                             AvahiProtocol protocol,
695
 
                             AvahiBrowserEvent event,
696
 
                             const char *name,
697
 
                             const char *type,
698
 
                             const char *domain,
699
 
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
700
 
                             flags,
701
 
                             void* userdata) {
702
 
  mandos_context *mc = userdata;
703
 
  assert(b);                    /* Spurious warning */
 
1021
static void browse_callback(AvahiSServiceBrowser *b,
 
1022
                            AvahiIfIndex interface,
 
1023
                            AvahiProtocol protocol,
 
1024
                            AvahiBrowserEvent event,
 
1025
                            const char *name,
 
1026
                            const char *type,
 
1027
                            const char *domain,
 
1028
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
 
1029
                            flags,
 
1030
                            AVAHI_GCC_UNUSED void* userdata){
 
1031
  assert(b);
704
1032
  
705
1033
  /* Called whenever a new services becomes available on the LAN or
706
1034
     is removed from the LAN */
707
1035
  
708
 
  switch (event) {
 
1036
  if(quit_now){
 
1037
    return;
 
1038
  }
 
1039
  
 
1040
  switch(event){
709
1041
  default:
710
1042
  case AVAHI_BROWSER_FAILURE:
711
1043
    
712
1044
    fprintf(stderr, "(Avahi browser) %s\n",
713
 
            avahi_strerror(avahi_server_errno(mc->server)));
714
 
    avahi_simple_poll_quit(mc->simple_poll);
 
1045
            avahi_strerror(avahi_server_errno(mc.server)));
 
1046
    avahi_simple_poll_quit(mc.simple_poll);
715
1047
    return;
716
1048
    
717
1049
  case AVAHI_BROWSER_NEW:
720
1052
       the callback function is called the Avahi server will free the
721
1053
       resolver for us. */
722
1054
    
723
 
    if (!(avahi_s_service_resolver_new(mc->server, interface,
724
 
                                       protocol, name, type, domain,
725
 
                                       AVAHI_PROTO_INET6, 0,
726
 
                                       resolve_callback, mc)))
 
1055
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
 
1056
                                    name, type, domain, protocol, 0,
 
1057
                                    resolve_callback, NULL) == NULL)
727
1058
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
728
 
              name, avahi_strerror(avahi_server_errno(mc->server)));
 
1059
              name, avahi_strerror(avahi_server_errno(mc.server)));
729
1060
    break;
730
1061
    
731
1062
  case AVAHI_BROWSER_REMOVE:
740
1071
  }
741
1072
}
742
1073
 
743
 
/* Combines file name and path and returns the malloced new
744
 
   string. some sane checks could/should be added */
745
 
static const char *combinepath(const char *first, const char *second){
746
 
  size_t f_len = strlen(first);
747
 
  size_t s_len = strlen(second);
748
 
  char *tmp = malloc(f_len + s_len + 2);
749
 
  if (tmp == NULL){
750
 
    return NULL;
751
 
  }
752
 
  if(f_len > 0){
753
 
    memcpy(tmp, first, f_len);  /* Spurious warning */
754
 
  }
755
 
  tmp[f_len] = '/';
756
 
  if(s_len > 0){
757
 
    memcpy(tmp + f_len + 1, second, s_len); /* Spurious warning */
758
 
  }
759
 
  tmp[f_len + 1 + s_len] = '\0';
760
 
  return tmp;
761
 
}
762
 
 
 
1074
/* Signal handler that stops main loop after SIGTERM */
 
1075
static void handle_sigterm(int sig){
 
1076
  if(quit_now){
 
1077
    return;
 
1078
  }
 
1079
  quit_now = 1;
 
1080
  signal_received = sig;
 
1081
  int old_errno = errno;
 
1082
  /* set main loop to exit */
 
1083
  if(mc.simple_poll != NULL){
 
1084
    avahi_simple_poll_quit(mc.simple_poll);
 
1085
  }
 
1086
  errno = old_errno;
 
1087
}
 
1088
 
 
1089
bool get_flags(const char *ifname, struct ifreq *ifr){
 
1090
  int ret;
 
1091
  
 
1092
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1093
  if(s < 0){
 
1094
    perror_plus("socket");
 
1095
    return false;
 
1096
  }
 
1097
  strcpy(ifr->ifr_name, ifname);
 
1098
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
 
1099
  if(ret == -1){
 
1100
    if(debug){
 
1101
      perror_plus("ioctl SIOCGIFFLAGS");
 
1102
    }
 
1103
    return false;
 
1104
  }
 
1105
  return true;
 
1106
}
 
1107
 
 
1108
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1109
  
 
1110
  /* Reject the loopback device */
 
1111
  if(ifr->ifr_flags & IFF_LOOPBACK){
 
1112
    if(debug){
 
1113
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1114
              ifname);
 
1115
    }
 
1116
    return false;
 
1117
  }
 
1118
  /* Accept point-to-point devices only if connect_to is specified */
 
1119
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
 
1120
    if(debug){
 
1121
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1122
              ifname);
 
1123
    }
 
1124
    return true;
 
1125
  }
 
1126
  /* Otherwise, reject non-broadcast-capable devices */
 
1127
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
 
1128
    if(debug){
 
1129
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1130
              ifname);
 
1131
    }
 
1132
    return false;
 
1133
  }
 
1134
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1135
  if(ifr->ifr_flags & IFF_NOARP){
 
1136
    if(debug){
 
1137
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1138
    }
 
1139
    return false;
 
1140
  }
 
1141
  
 
1142
  /* Accept this device */
 
1143
  if(debug){
 
1144
    fprintf(stderr, "Interface \"%s\" is good\n", ifname);
 
1145
  }
 
1146
  return true;
 
1147
}
 
1148
 
 
1149
/* 
 
1150
 * This function determines if a directory entry in /sys/class/net
 
1151
 * corresponds to an acceptable network device.
 
1152
 * (This function is passed to scandir(3) as a filter function.)
 
1153
 */
 
1154
int good_interface(const struct dirent *if_entry){
 
1155
  int ret;
 
1156
  if(if_entry->d_name[0] == '.'){
 
1157
    return 0;
 
1158
  }
 
1159
  struct ifreq ifr;
 
1160
 
 
1161
  if(not get_flags(if_entry->d_name, &ifr)){
 
1162
    return 0;
 
1163
  }
 
1164
  
 
1165
  if(not good_flags(if_entry->d_name, &ifr)){
 
1166
    return 0;
 
1167
  }
 
1168
  return 1;
 
1169
}
 
1170
 
 
1171
/* 
 
1172
 * This function determines if a directory entry in /sys/class/net
 
1173
 * corresponds to an acceptable network device which is up.
 
1174
 * (This function is passed to scandir(3) as a filter function.)
 
1175
 */
 
1176
int up_interface(const struct dirent *if_entry){
 
1177
  ssize_t ssret;
 
1178
  char *flagname = NULL;
 
1179
  if(if_entry->d_name[0] == '.'){
 
1180
    return 0;
 
1181
  }
 
1182
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
 
1183
                     if_entry->d_name);
 
1184
  if(ret < 0){
 
1185
    perror_plus("asprintf");
 
1186
    return 0;
 
1187
  }
 
1188
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
 
1189
  if(flags_fd == -1){
 
1190
    perror_plus("open");
 
1191
    free(flagname);
 
1192
    return 0;
 
1193
  }
 
1194
  free(flagname);
 
1195
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
 
1196
  /* read line from flags_fd */
 
1197
  ssize_t to_read = 2+(sizeof(ifreq_flags)*2)+1; /* "0x1003\n" */
 
1198
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
 
1199
  flagstring[(size_t)to_read] = '\0';
 
1200
  if(flagstring == NULL){
 
1201
    perror_plus("malloc");
 
1202
    close(flags_fd);
 
1203
    return 0;
 
1204
  }
 
1205
  while(to_read > 0){
 
1206
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
 
1207
                                             (size_t)to_read));
 
1208
    if(ssret == -1){
 
1209
      perror_plus("read");
 
1210
      free(flagstring);
 
1211
      close(flags_fd);
 
1212
      return 0;
 
1213
    }
 
1214
    to_read -= ssret;
 
1215
    if(ssret == 0){
 
1216
      break;
 
1217
    }
 
1218
  }
 
1219
  close(flags_fd);
 
1220
  intmax_t tmpmax;
 
1221
  char *tmp;
 
1222
  errno = 0;
 
1223
  tmpmax = strtoimax(flagstring, &tmp, 0);
 
1224
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
 
1225
                                         and not (isspace(*tmp)))
 
1226
     or tmpmax != (ifreq_flags)tmpmax){
 
1227
    if(debug){
 
1228
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1229
              flagstring, if_entry->d_name);
 
1230
    }
 
1231
    free(flagstring);
 
1232
    return 0;
 
1233
  }
 
1234
  free(flagstring);
 
1235
  ifreq_flags flags = (ifreq_flags)tmpmax;
 
1236
  /* Reject the loopback device */
 
1237
  if(flags & IFF_LOOPBACK){
 
1238
    if(debug){
 
1239
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1240
              if_entry->d_name);
 
1241
    }
 
1242
    return 0;
 
1243
  }
 
1244
 
 
1245
  /* Reject down interfaces */
 
1246
  if(not (flags & IFF_UP)){
 
1247
    return 0;
 
1248
  }
 
1249
  
 
1250
  /* Accept point-to-point devices only if connect_to is specified */
 
1251
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1252
    if(debug){
 
1253
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1254
              if_entry->d_name);
 
1255
    }
 
1256
    return 1;
 
1257
  }
 
1258
  /* Otherwise, reject non-broadcast-capable devices */
 
1259
  if(not (flags & IFF_BROADCAST)){
 
1260
    if(debug){
 
1261
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1262
              if_entry->d_name);
 
1263
    }
 
1264
    return 0;
 
1265
  }
 
1266
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1267
  if(flags & IFF_NOARP){
 
1268
    if(debug){
 
1269
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1270
              if_entry->d_name);
 
1271
    }
 
1272
    return 0;
 
1273
  }
 
1274
  /* Accept this device */
 
1275
  if(debug){
 
1276
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1277
            if_entry->d_name);
 
1278
  }
 
1279
  return 1;
 
1280
}
 
1281
 
 
1282
int notdotentries(const struct dirent *direntry){
 
1283
  /* Skip "." and ".." */
 
1284
  if(direntry->d_name[0] == '.'
 
1285
     and (direntry->d_name[1] == '\0'
 
1286
          or (direntry->d_name[1] == '.'
 
1287
              and direntry->d_name[2] == '\0'))){
 
1288
    return 0;
 
1289
  }
 
1290
  return 1;
 
1291
}
 
1292
 
 
1293
/* Is this directory entry a runnable program? */
 
1294
int runnable_hook(const struct dirent *direntry){
 
1295
  int ret;
 
1296
  struct stat st;
 
1297
  
 
1298
  if((direntry->d_name)[0] == '\0'){
 
1299
    /* Empty name? */
 
1300
    return 0;
 
1301
  }
 
1302
  
 
1303
  /* Save pointer to last character */
 
1304
  char *end = strchr(direntry->d_name, '\0')-1;
 
1305
  
 
1306
  if(*end == '~'){
 
1307
    /* Backup name~ */
 
1308
    return 0;
 
1309
  }
 
1310
  
 
1311
  if(((direntry->d_name)[0] == '#')
 
1312
     and (*end == '#')){
 
1313
    /* Temporary #name# */
 
1314
    return 0;
 
1315
  }
 
1316
  
 
1317
  /* XXX more rules here */
 
1318
  
 
1319
  ret = stat(direntry->d_name, &st);
 
1320
  if(ret == -1){
 
1321
    if(debug){
 
1322
      perror_plus("Could not stat plugin");
 
1323
    }
 
1324
    return 0;
 
1325
  }
 
1326
  if(not (st.st_mode & S_ISREG)){
 
1327
    /* Not a regular file */
 
1328
    return 0;
 
1329
  }
 
1330
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
 
1331
    /* Not executable */
 
1332
    return 0;
 
1333
  }
 
1334
  return 1;
 
1335
}
 
1336
 
 
1337
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1338
  int ret;
 
1339
  struct timespec now;
 
1340
  struct timespec waited_time;
 
1341
  intmax_t block_time;
 
1342
  
 
1343
  while(true){
 
1344
    if(mc.current_server == NULL){
 
1345
      if (debug){
 
1346
        fprintf(stderr,
 
1347
                "Wait until first server is found. No timeout!\n");
 
1348
      }
 
1349
      ret = avahi_simple_poll_iterate(s, -1);
 
1350
    } else {
 
1351
      if (debug){
 
1352
        fprintf(stderr, "Check current_server if we should run it,"
 
1353
                " or wait\n");
 
1354
      }
 
1355
      /* the current time */
 
1356
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
 
1357
      if(ret == -1){
 
1358
        perror_plus("clock_gettime");
 
1359
        return -1;
 
1360
      }
 
1361
      /* Calculating in ms how long time between now and server
 
1362
         who we visted longest time ago. Now - last seen.  */
 
1363
      waited_time.tv_sec = (now.tv_sec
 
1364
                            - mc.current_server->last_seen.tv_sec);
 
1365
      waited_time.tv_nsec = (now.tv_nsec
 
1366
                             - mc.current_server->last_seen.tv_nsec);
 
1367
      /* total time is 10s/10,000ms.
 
1368
         Converting to s from ms by dividing by 1,000,
 
1369
         and ns to ms by dividing by 1,000,000. */
 
1370
      block_time = ((retry_interval
 
1371
                     - ((intmax_t)waited_time.tv_sec * 1000))
 
1372
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
 
1373
      
 
1374
      if (debug){
 
1375
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
 
1376
      }
 
1377
      
 
1378
      if(block_time <= 0){
 
1379
        ret = start_mandos_communication(mc.current_server->ip,
 
1380
                                         mc.current_server->port,
 
1381
                                         mc.current_server->if_index,
 
1382
                                         mc.current_server->af);
 
1383
        if(ret == 0){
 
1384
          avahi_simple_poll_quit(mc.simple_poll);
 
1385
          return 0;
 
1386
        }
 
1387
        ret = clock_gettime(CLOCK_MONOTONIC,
 
1388
                            &mc.current_server->last_seen);
 
1389
        if(ret == -1){
 
1390
          perror_plus("clock_gettime");
 
1391
          return -1;
 
1392
        }
 
1393
        mc.current_server = mc.current_server->next;
 
1394
        block_time = 0;         /* Call avahi to find new Mandos
 
1395
                                   servers, but don't block */
 
1396
      }
 
1397
      
 
1398
      ret = avahi_simple_poll_iterate(s, (int)block_time);
 
1399
    }
 
1400
    if(ret != 0){
 
1401
      if (ret > 0 or errno != EINTR) {
 
1402
        return (ret != 1) ? ret : 0;
 
1403
      }
 
1404
    }
 
1405
  }
 
1406
}
763
1407
 
764
1408
int main(int argc, char *argv[]){
765
 
    AvahiSServiceBrowser *sb = NULL;
766
 
    int error;
767
 
    int ret;
768
 
    int exitcode = EXIT_SUCCESS;
769
 
    const char *interface = "eth0";
770
 
    struct ifreq network;
771
 
    int sd;
772
 
    uid_t uid;
773
 
    gid_t gid;
774
 
    char *connect_to = NULL;
775
 
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
776
 
    const char *pubkeyfile = "pubkey.txt";
777
 
    const char *seckeyfile = "seckey.txt";
778
 
    mandos_context mc = { .simple_poll = NULL, .server = NULL,
779
 
                          .dh_bits = 1024, .priority = "SECURE256"};
780
 
    bool gnutls_initalized = false;
781
 
    
782
 
    {
783
 
      struct argp_option options[] = {
784
 
        { .name = "debug", .key = 128,
785
 
          .doc = "Debug mode", .group = 3 },
786
 
        { .name = "connect", .key = 'c',
787
 
          .arg = "IP",
788
 
          .doc = "Connect directly to a sepcified mandos server",
789
 
          .group = 1 },
790
 
        { .name = "interface", .key = 'i',
791
 
          .arg = "INTERFACE",
792
 
          .doc = "Interface that Avahi will conntect through",
793
 
          .group = 1 },
794
 
        { .name = "keydir", .key = 'd',
795
 
          .arg = "KEYDIR",
796
 
          .doc = "Directory where the openpgp keyring is",
797
 
          .group = 1 },
798
 
        { .name = "seckey", .key = 's',
799
 
          .arg = "SECKEY",
800
 
          .doc = "Secret openpgp key for gnutls authentication",
801
 
          .group = 1 },
802
 
        { .name = "pubkey", .key = 'p',
803
 
          .arg = "PUBKEY",
804
 
          .doc = "Public openpgp key for gnutls authentication",
805
 
          .group = 2 },
806
 
        { .name = "dh-bits", .key = 129,
807
 
          .arg = "BITS",
808
 
          .doc = "dh-bits to use in gnutls communication",
809
 
          .group = 2 },
810
 
        { .name = "priority", .key = 130,
811
 
          .arg = "PRIORITY",
812
 
          .doc = "GNUTLS priority", .group = 1 },
813
 
        { .name = NULL }
814
 
      };
815
 
 
816
 
      
817
 
      error_t parse_opt (int key, char *arg,
818
 
                         struct argp_state *state) {
819
 
        /* Get the INPUT argument from `argp_parse', which we know is
820
 
           a pointer to our plugin list pointer. */
821
 
        switch (key) {
822
 
        case 128:
823
 
          debug = true;
824
 
          break;
825
 
        case 'c':
826
 
          connect_to = arg;
827
 
          break;
828
 
        case 'i':
829
 
          interface = arg;
830
 
          break;
831
 
        case 'd':
832
 
          keydir = arg;
833
 
          break;
834
 
        case 's':
835
 
          seckeyfile = arg;
836
 
          break;
837
 
        case 'p':
838
 
          pubkeyfile = arg;
839
 
          break;
840
 
        case 129:
841
 
          errno = 0;
842
 
          mc.dh_bits = (unsigned int) strtol(arg, NULL, 10);
843
 
          if (errno){
844
 
            perror("strtol");
845
 
            exit(EXIT_FAILURE);
846
 
          }
847
 
          break;
848
 
        case 130:
849
 
          mc.priority = arg;
850
 
          break;
851
 
        case ARGP_KEY_ARG:
852
 
          argp_usage (state);
853
 
        case ARGP_KEY_END:
854
 
          break;
855
 
        default:
856
 
          return ARGP_ERR_UNKNOWN;
857
 
        }
858
 
        return 0;
859
 
      }
860
 
 
861
 
      struct argp argp = { .options = options, .parser = parse_opt,
862
 
                           .args_doc = "",
863
 
                           .doc = "Mandos client -- Get and decrypt"
864
 
                           " passwords from mandos server" };
865
 
      ret = argp_parse (&argp, argc, argv, 0, 0, NULL);
866
 
      if (ret == ARGP_ERR_UNKNOWN){
867
 
        fprintf(stderr, "Unknown error while parsing arguments\n");
 
1409
  AvahiSServiceBrowser *sb = NULL;
 
1410
  int error;
 
1411
  int ret;
 
1412
  intmax_t tmpmax;
 
1413
  char *tmp;
 
1414
  int exitcode = EXIT_SUCCESS;
 
1415
  const char *interface = "";
 
1416
  struct ifreq network;
 
1417
  int sd = -1;
 
1418
  bool take_down_interface = false;
 
1419
  uid_t uid;
 
1420
  gid_t gid;
 
1421
  char tempdir[] = "/tmp/mandosXXXXXX";
 
1422
  bool tempdir_created = false;
 
1423
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
 
1424
  const char *seckey = PATHDIR "/" SECKEY;
 
1425
  const char *pubkey = PATHDIR "/" PUBKEY;
 
1426
  
 
1427
  bool gnutls_initialized = false;
 
1428
  bool gpgme_initialized = false;
 
1429
  float delay = 2.5f;
 
1430
  double retry_interval = 10; /* 10s between trying a server and
 
1431
                                 retrying the same server again */
 
1432
  
 
1433
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
 
1434
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
 
1435
  
 
1436
  uid = getuid();
 
1437
  gid = getgid();
 
1438
  
 
1439
  /* Lower any group privileges we might have, just to be safe */
 
1440
  errno = 0;
 
1441
  ret = setgid(gid);
 
1442
  if(ret == -1){
 
1443
    perror_plus("setgid");
 
1444
  }
 
1445
  
 
1446
  /* Lower user privileges (temporarily) */
 
1447
  errno = 0;
 
1448
  ret = seteuid(uid);
 
1449
  if(ret == -1){
 
1450
    perror_plus("seteuid");
 
1451
  }
 
1452
  
 
1453
  if(quit_now){
 
1454
    goto end;
 
1455
  }
 
1456
  
 
1457
  {
 
1458
    struct argp_option options[] = {
 
1459
      { .name = "debug", .key = 128,
 
1460
        .doc = "Debug mode", .group = 3 },
 
1461
      { .name = "connect", .key = 'c',
 
1462
        .arg = "ADDRESS:PORT",
 
1463
        .doc = "Connect directly to a specific Mandos server",
 
1464
        .group = 1 },
 
1465
      { .name = "interface", .key = 'i',
 
1466
        .arg = "NAME",
 
1467
        .doc = "Network interface that will be used to search for"
 
1468
        " Mandos servers",
 
1469
        .group = 1 },
 
1470
      { .name = "seckey", .key = 's',
 
1471
        .arg = "FILE",
 
1472
        .doc = "OpenPGP secret key file base name",
 
1473
        .group = 1 },
 
1474
      { .name = "pubkey", .key = 'p',
 
1475
        .arg = "FILE",
 
1476
        .doc = "OpenPGP public key file base name",
 
1477
        .group = 2 },
 
1478
      { .name = "dh-bits", .key = 129,
 
1479
        .arg = "BITS",
 
1480
        .doc = "Bit length of the prime number used in the"
 
1481
        " Diffie-Hellman key exchange",
 
1482
        .group = 2 },
 
1483
      { .name = "priority", .key = 130,
 
1484
        .arg = "STRING",
 
1485
        .doc = "GnuTLS priority string for the TLS handshake",
 
1486
        .group = 1 },
 
1487
      { .name = "delay", .key = 131,
 
1488
        .arg = "SECONDS",
 
1489
        .doc = "Maximum delay to wait for interface startup",
 
1490
        .group = 2 },
 
1491
      { .name = "retry", .key = 132,
 
1492
        .arg = "SECONDS",
 
1493
        .doc = "Retry interval used when denied by the mandos server",
 
1494
        .group = 2 },
 
1495
      /*
 
1496
       * These reproduce what we would get without ARGP_NO_HELP
 
1497
       */
 
1498
      { .name = "help", .key = '?',
 
1499
        .doc = "Give this help list", .group = -1 },
 
1500
      { .name = "usage", .key = -3,
 
1501
        .doc = "Give a short usage message", .group = -1 },
 
1502
      { .name = "version", .key = 'V',
 
1503
        .doc = "Print program version", .group = -1 },
 
1504
      { .name = NULL }
 
1505
    };
 
1506
    
 
1507
    error_t parse_opt(int key, char *arg,
 
1508
                      struct argp_state *state){
 
1509
      errno = 0;
 
1510
      switch(key){
 
1511
      case 128:                 /* --debug */
 
1512
        debug = true;
 
1513
        break;
 
1514
      case 'c':                 /* --connect */
 
1515
        connect_to = arg;
 
1516
        break;
 
1517
      case 'i':                 /* --interface */
 
1518
        interface = arg;
 
1519
        break;
 
1520
      case 's':                 /* --seckey */
 
1521
        seckey = arg;
 
1522
        break;
 
1523
      case 'p':                 /* --pubkey */
 
1524
        pubkey = arg;
 
1525
        break;
 
1526
      case 129:                 /* --dh-bits */
 
1527
        errno = 0;
 
1528
        tmpmax = strtoimax(arg, &tmp, 10);
 
1529
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1530
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
 
1531
          argp_error(state, "Bad number of DH bits");
 
1532
        }
 
1533
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
 
1534
        break;
 
1535
      case 130:                 /* --priority */
 
1536
        mc.priority = arg;
 
1537
        break;
 
1538
      case 131:                 /* --delay */
 
1539
        errno = 0;
 
1540
        delay = strtof(arg, &tmp);
 
1541
        if(errno != 0 or tmp == arg or *tmp != '\0'){
 
1542
          argp_error(state, "Bad delay");
 
1543
        }
 
1544
      case 132:                 /* --retry */
 
1545
        errno = 0;
 
1546
        retry_interval = strtod(arg, &tmp);
 
1547
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1548
           or (retry_interval * 1000) > INT_MAX
 
1549
           or retry_interval < 0){
 
1550
          argp_error(state, "Bad retry interval");
 
1551
        }
 
1552
        break;
 
1553
        /*
 
1554
         * These reproduce what we would get without ARGP_NO_HELP
 
1555
         */
 
1556
      case '?':                 /* --help */
 
1557
        argp_state_help(state, state->out_stream,
 
1558
                        (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
 
1559
                        & ~(unsigned int)ARGP_HELP_EXIT_OK);
 
1560
      case -3:                  /* --usage */
 
1561
        argp_state_help(state, state->out_stream,
 
1562
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
 
1563
      case 'V':                 /* --version */
 
1564
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1565
        exit(argp_err_exit_status);
 
1566
        break;
 
1567
      default:
 
1568
        return ARGP_ERR_UNKNOWN;
 
1569
      }
 
1570
      return errno;
 
1571
    }
 
1572
    
 
1573
    struct argp argp = { .options = options, .parser = parse_opt,
 
1574
                         .args_doc = "",
 
1575
                         .doc = "Mandos client -- Get and decrypt"
 
1576
                         " passwords from a Mandos server" };
 
1577
    ret = argp_parse(&argp, argc, argv,
 
1578
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
1579
    switch(ret){
 
1580
    case 0:
 
1581
      break;
 
1582
    case ENOMEM:
 
1583
    default:
 
1584
      errno = ret;
 
1585
      perror_plus("argp_parse");
 
1586
      exitcode = EX_OSERR;
 
1587
      goto end;
 
1588
    case EINVAL:
 
1589
      exitcode = EX_USAGE;
 
1590
      goto end;
 
1591
    }
 
1592
  }
 
1593
    
 
1594
  {
 
1595
    /* Work around Debian bug #633582:
 
1596
       <http://bugs.debian.org/633582> */
 
1597
    struct stat st;
 
1598
    
 
1599
    /* Re-raise priviliges */
 
1600
    errno = 0;
 
1601
    ret = seteuid(0);
 
1602
    if(ret == -1){
 
1603
      perror_plus("seteuid");
 
1604
    }
 
1605
    
 
1606
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1607
      int seckey_fd = open(seckey, O_RDONLY);
 
1608
      if(seckey_fd == -1){
 
1609
        perror_plus("open");
 
1610
      } else {
 
1611
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1612
        if(ret == -1){
 
1613
          perror_plus("fstat");
 
1614
        } else {
 
1615
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1616
            ret = fchown(seckey_fd, uid, gid);
 
1617
            if(ret == -1){
 
1618
              perror_plus("fchown");
 
1619
            }
 
1620
          }
 
1621
        }
 
1622
        TEMP_FAILURE_RETRY(close(seckey_fd));
 
1623
      }
 
1624
    }
 
1625
    
 
1626
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1627
      int pubkey_fd = open(pubkey, O_RDONLY);
 
1628
      if(pubkey_fd == -1){
 
1629
        perror_plus("open");
 
1630
      } else {
 
1631
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1632
        if(ret == -1){
 
1633
          perror_plus("fstat");
 
1634
        } else {
 
1635
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1636
            ret = fchown(pubkey_fd, uid, gid);
 
1637
            if(ret == -1){
 
1638
              perror_plus("fchown");
 
1639
            }
 
1640
          }
 
1641
        }
 
1642
        TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1643
      }
 
1644
    }
 
1645
    
 
1646
    /* Lower privileges */
 
1647
    errno = 0;
 
1648
    ret = seteuid(uid);
 
1649
    if(ret == -1){
 
1650
      perror_plus("seteuid");
 
1651
    }
 
1652
  }
 
1653
  
 
1654
  /* Find network hooks and run them */
 
1655
  {
 
1656
    struct dirent **direntries;
 
1657
    struct dirent *direntry;
 
1658
    int numhooks = scandir(HOOKDIR, &direntries, runnable_hook,
 
1659
                           alphasort);
 
1660
    int devnull = open("/dev/null", O_RDONLY);
 
1661
    for(int i = 0; i < numhooks; i++){
 
1662
      direntry = direntries[0];
 
1663
      char *fullname = NULL;
 
1664
      ret = asprintf(&fullname, "%s/%s", tempdir,
 
1665
                     direntry->d_name);
 
1666
      if(ret < 0){
 
1667
        perror_plus("asprintf");
 
1668
        continue;
 
1669
      }
 
1670
      pid_t hook_pid = fork();
 
1671
      if(hook_pid == 0){
 
1672
        /* Child */
 
1673
        dup2(devnull, STDIN_FILENO);
 
1674
        close(devnull);
 
1675
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1676
        setenv("DEVICE", interface, 1);
 
1677
        setenv("VERBOSE", debug ? "1" : "0", 1);
 
1678
        setenv("MODE", "start", 1);
 
1679
        /* setenv( XXX more here */
 
1680
        ret = execl(fullname, direntry->d_name, "start");
 
1681
        perror_plus("execl");
 
1682
      }
 
1683
      free(fullname);
 
1684
      if(quit_now){
 
1685
        goto end;
 
1686
      }
 
1687
    }
 
1688
    close(devnull);
 
1689
  }
 
1690
  
 
1691
  if(not debug){
 
1692
    avahi_set_log_function(empty_log);
 
1693
  }
 
1694
  
 
1695
  if(interface[0] == '\0'){
 
1696
    struct dirent **direntries;
 
1697
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1698
                  alphasort);
 
1699
    if(ret >= 1){
 
1700
      /* Pick the first good interface */
 
1701
      interface = strdup(direntries[0]->d_name);
 
1702
      if(debug){
 
1703
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1704
      }
 
1705
      if(interface == NULL){
 
1706
        perror_plus("malloc");
 
1707
        free(direntries);
868
1708
        exitcode = EXIT_FAILURE;
869
1709
        goto end;
870
1710
      }
871
 
    }
872
 
      
873
 
    pubkeyfile = combinepath(keydir, pubkeyfile);
874
 
    if (pubkeyfile == NULL){
875
 
      perror("combinepath");
876
 
      exitcode = EXIT_FAILURE;
877
 
      goto end;
878
 
    }
879
 
    
880
 
    seckeyfile = combinepath(keydir, seckeyfile);
881
 
    if (seckeyfile == NULL){
882
 
      perror("combinepath");
883
 
      exitcode = EXIT_FAILURE;
884
 
      goto end;
885
 
    }
886
 
 
887
 
    ret = init_gnutls_global(&mc, pubkeyfile, seckeyfile);
888
 
    if (ret == -1){
889
 
      fprintf(stderr, "init_gnutls_global failed\n");
890
 
      exitcode = EXIT_FAILURE;
891
 
      goto end;
 
1711
      free(direntries);
892
1712
    } else {
893
 
      gnutls_initalized = true;
894
 
    }
895
 
    
896
 
    /* If the interface is down, bring it up */
897
 
    {
898
 
      sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
899
 
      if(sd < 0) {
900
 
        perror("socket");
901
 
        exitcode = EXIT_FAILURE;
902
 
        goto end;
903
 
      }
904
 
      strcpy(network.ifr_name, interface); /* Spurious warning */
905
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
906
 
      if(ret == -1){
907
 
        perror("ioctl SIOCGIFFLAGS");
908
 
        exitcode = EXIT_FAILURE;
909
 
        goto end;
910
 
      }
911
 
      if((network.ifr_flags & IFF_UP) == 0){
912
 
        network.ifr_flags |= IFF_UP;
913
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
914
 
        if(ret == -1){
915
 
          perror("ioctl SIOCSIFFLAGS");
916
 
          exitcode = EXIT_FAILURE;
917
 
          goto end;
918
 
        }
919
 
      }
920
 
      close(sd);
921
 
    }
922
 
    
923
 
    uid = getuid();
924
 
    gid = getgid();
925
 
    
926
 
    ret = setuid(uid);
927
 
    if (ret == -1){
928
 
      perror("setuid");
929
 
    }
930
 
    
931
 
    setgid(gid);
932
 
    if (ret == -1){
933
 
      perror("setgid");
934
 
    }
935
 
    
 
1713
      free(direntries);
 
1714
      fprintf(stderr, "Could not find a network interface\n");
 
1715
      exitcode = EXIT_FAILURE;
 
1716
      goto end;
 
1717
    }
 
1718
  }
 
1719
  
 
1720
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
 
1721
     from the signal handler */
 
1722
  /* Initialize the pseudo-RNG for Avahi */
 
1723
  srand((unsigned int) time(NULL));
 
1724
  mc.simple_poll = avahi_simple_poll_new();
 
1725
  if(mc.simple_poll == NULL){
 
1726
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1727
    exitcode = EX_UNAVAILABLE;
 
1728
    goto end;
 
1729
  }
 
1730
  
 
1731
  sigemptyset(&sigterm_action.sa_mask);
 
1732
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
 
1733
  if(ret == -1){
 
1734
    perror_plus("sigaddset");
 
1735
    exitcode = EX_OSERR;
 
1736
    goto end;
 
1737
  }
 
1738
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
 
1739
  if(ret == -1){
 
1740
    perror_plus("sigaddset");
 
1741
    exitcode = EX_OSERR;
 
1742
    goto end;
 
1743
  }
 
1744
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
 
1745
  if(ret == -1){
 
1746
    perror_plus("sigaddset");
 
1747
    exitcode = EX_OSERR;
 
1748
    goto end;
 
1749
  }
 
1750
  /* Need to check if the handler is SIG_IGN before handling:
 
1751
     | [[info:libc:Initial Signal Actions]] |
 
1752
     | [[info:libc:Basic Signal Handling]]  |
 
1753
  */
 
1754
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
 
1755
  if(ret == -1){
 
1756
    perror_plus("sigaction");
 
1757
    return EX_OSERR;
 
1758
  }
 
1759
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1760
    ret = sigaction(SIGINT, &sigterm_action, NULL);
 
1761
    if(ret == -1){
 
1762
      perror_plus("sigaction");
 
1763
      exitcode = EX_OSERR;
 
1764
      goto end;
 
1765
    }
 
1766
  }
 
1767
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
 
1768
  if(ret == -1){
 
1769
    perror_plus("sigaction");
 
1770
    return EX_OSERR;
 
1771
  }
 
1772
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1773
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
 
1774
    if(ret == -1){
 
1775
      perror_plus("sigaction");
 
1776
      exitcode = EX_OSERR;
 
1777
      goto end;
 
1778
    }
 
1779
  }
 
1780
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
 
1781
  if(ret == -1){
 
1782
    perror_plus("sigaction");
 
1783
    return EX_OSERR;
 
1784
  }
 
1785
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1786
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
 
1787
    if(ret == -1){
 
1788
      perror_plus("sigaction");
 
1789
      exitcode = EX_OSERR;
 
1790
      goto end;
 
1791
    }
 
1792
  }
 
1793
  
 
1794
  /* If the interface is down, bring it up */
 
1795
  if(strcmp(interface, "none") != 0){
936
1796
    if_index = (AvahiIfIndex) if_nametoindex(interface);
937
1797
    if(if_index == 0){
938
1798
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
939
 
      exit(EXIT_FAILURE);
940
 
    }
941
 
    
942
 
    if(connect_to != NULL){
943
 
      /* Connect directly, do not use Zeroconf */
944
 
      /* (Mainly meant for debugging) */
945
 
      char *address = strrchr(connect_to, ':');
946
 
      if(address == NULL){
947
 
        fprintf(stderr, "No colon in address\n");
948
 
        exitcode = EXIT_FAILURE;
949
 
        goto end;
950
 
      }
951
 
      errno = 0;
952
 
      uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
953
 
      if(errno){
954
 
        perror("Bad port number");
955
 
        exitcode = EXIT_FAILURE;
956
 
        goto end;
957
 
      }
958
 
      *address = '\0';
959
 
      address = connect_to;
960
 
      ret = start_mandos_communication(address, port, if_index, &mc);
961
 
      if(ret < 0){
962
 
        exitcode = EXIT_FAILURE;
963
 
      } else {
964
 
        exitcode = EXIT_SUCCESS;
965
 
      }
966
 
      goto end;
967
 
    }
968
 
    
969
 
    if (not debug){
970
 
      avahi_set_log_function(empty_log);
971
 
    }
972
 
    
973
 
    /* Initialize the pseudo-RNG for Avahi */
974
 
    srand((unsigned int) time(NULL));
975
 
    
976
 
    /* Allocate main Avahi loop object */
977
 
    mc.simple_poll = avahi_simple_poll_new();
978
 
    if (mc.simple_poll == NULL) {
979
 
        fprintf(stderr, "Avahi: Failed to create simple poll"
980
 
                " object.\n");
981
 
        exitcode = EXIT_FAILURE;
982
 
        goto end;
983
 
    }
984
 
 
985
 
    {
986
 
      AvahiServerConfig config;
987
 
      /* Do not publish any local Zeroconf records */
988
 
      avahi_server_config_init(&config);
989
 
      config.publish_hinfo = 0;
990
 
      config.publish_addresses = 0;
991
 
      config.publish_workstation = 0;
992
 
      config.publish_domain = 0;
993
 
 
994
 
      /* Allocate a new server */
995
 
      mc.server = avahi_server_new(avahi_simple_poll_get
996
 
                                   (mc.simple_poll), &config, NULL,
997
 
                                   NULL, &error);
998
 
    
999
 
      /* Free the Avahi configuration data */
1000
 
      avahi_server_config_free(&config);
1001
 
    }
1002
 
    
1003
 
    /* Check if creating the Avahi server object succeeded */
1004
 
    if (mc.server == NULL) {
1005
 
        fprintf(stderr, "Failed to create Avahi server: %s\n",
1006
 
                avahi_strerror(error));
1007
 
        exitcode = EXIT_FAILURE;
1008
 
        goto end;
1009
 
    }
1010
 
    
1011
 
    /* Create the Avahi service browser */
1012
 
    sb = avahi_s_service_browser_new(mc.server, if_index,
1013
 
                                     AVAHI_PROTO_INET6,
1014
 
                                     "_mandos._tcp", NULL, 0,
1015
 
                                     browse_callback, &mc);
1016
 
    if (sb == NULL) {
1017
 
        fprintf(stderr, "Failed to create service browser: %s\n",
1018
 
                avahi_strerror(avahi_server_errno(mc.server)));
1019
 
        exitcode = EXIT_FAILURE;
1020
 
        goto end;
1021
 
    }
1022
 
    
1023
 
    /* Run the main loop */
1024
 
 
1025
 
    if (debug){
1026
 
      fprintf(stderr, "Starting Avahi loop search\n");
1027
 
    }
1028
 
    
1029
 
    avahi_simple_poll_loop(mc.simple_poll);
1030
 
    
 
1799
      exitcode = EX_UNAVAILABLE;
 
1800
      goto end;
 
1801
    }
 
1802
    
 
1803
    if(quit_now){
 
1804
      goto end;
 
1805
    }
 
1806
    
 
1807
    /* Re-raise priviliges */
 
1808
    errno = 0;
 
1809
    ret = seteuid(0);
 
1810
    if(ret == -1){
 
1811
      perror_plus("seteuid");
 
1812
    }
 
1813
    
 
1814
#ifdef __linux__
 
1815
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1816
       messages about the network interface to mess up the prompt */
 
1817
    ret = klogctl(8, NULL, 5);
 
1818
    bool restore_loglevel = true;
 
1819
    if(ret == -1){
 
1820
      restore_loglevel = false;
 
1821
      perror_plus("klogctl");
 
1822
    }
 
1823
#endif  /* __linux__ */
 
1824
    
 
1825
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1826
    if(sd < 0){
 
1827
      perror_plus("socket");
 
1828
      exitcode = EX_OSERR;
 
1829
#ifdef __linux__
 
1830
      if(restore_loglevel){
 
1831
        ret = klogctl(7, NULL, 0);
 
1832
        if(ret == -1){
 
1833
          perror_plus("klogctl");
 
1834
        }
 
1835
      }
 
1836
#endif  /* __linux__ */
 
1837
      /* Lower privileges */
 
1838
      errno = 0;
 
1839
      ret = seteuid(uid);
 
1840
      if(ret == -1){
 
1841
        perror_plus("seteuid");
 
1842
      }
 
1843
      goto end;
 
1844
    }
 
1845
    strcpy(network.ifr_name, interface);
 
1846
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1847
    if(ret == -1){
 
1848
      perror_plus("ioctl SIOCGIFFLAGS");
 
1849
#ifdef __linux__
 
1850
      if(restore_loglevel){
 
1851
        ret = klogctl(7, NULL, 0);
 
1852
        if(ret == -1){
 
1853
          perror_plus("klogctl");
 
1854
        }
 
1855
      }
 
1856
#endif  /* __linux__ */
 
1857
      exitcode = EX_OSERR;
 
1858
      /* Lower privileges */
 
1859
      errno = 0;
 
1860
      ret = seteuid(uid);
 
1861
      if(ret == -1){
 
1862
        perror_plus("seteuid");
 
1863
      }
 
1864
      goto end;
 
1865
    }
 
1866
    if((network.ifr_flags & IFF_UP) == 0){
 
1867
      network.ifr_flags |= IFF_UP;
 
1868
      take_down_interface = true;
 
1869
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1870
      if(ret == -1){
 
1871
        take_down_interface = false;
 
1872
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1873
        exitcode = EX_OSERR;
 
1874
#ifdef __linux__
 
1875
        if(restore_loglevel){
 
1876
          ret = klogctl(7, NULL, 0);
 
1877
          if(ret == -1){
 
1878
            perror_plus("klogctl");
 
1879
          }
 
1880
        }
 
1881
#endif  /* __linux__ */
 
1882
        /* Lower privileges */
 
1883
        errno = 0;
 
1884
        ret = seteuid(uid);
 
1885
        if(ret == -1){
 
1886
          perror_plus("seteuid");
 
1887
        }
 
1888
        goto end;
 
1889
      }
 
1890
    }
 
1891
    /* Sleep checking until interface is running.
 
1892
       Check every 0.25s, up to total time of delay */
 
1893
    for(int i=0; i < delay * 4; i++){
 
1894
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1895
      if(ret == -1){
 
1896
        perror_plus("ioctl SIOCGIFFLAGS");
 
1897
      } else if(network.ifr_flags & IFF_RUNNING){
 
1898
        break;
 
1899
      }
 
1900
      struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1901
      ret = nanosleep(&sleeptime, NULL);
 
1902
      if(ret == -1 and errno != EINTR){
 
1903
        perror_plus("nanosleep");
 
1904
      }
 
1905
    }
 
1906
    if(not take_down_interface){
 
1907
      /* We won't need the socket anymore */
 
1908
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1909
      if(ret == -1){
 
1910
        perror_plus("close");
 
1911
      }
 
1912
    }
 
1913
#ifdef __linux__
 
1914
    if(restore_loglevel){
 
1915
      /* Restores kernel loglevel to default */
 
1916
      ret = klogctl(7, NULL, 0);
 
1917
      if(ret == -1){
 
1918
        perror_plus("klogctl");
 
1919
      }
 
1920
    }
 
1921
#endif  /* __linux__ */
 
1922
    /* Lower privileges */
 
1923
    errno = 0;
 
1924
    if(take_down_interface){
 
1925
      /* Lower privileges */
 
1926
      ret = seteuid(uid);
 
1927
      if(ret == -1){
 
1928
        perror_plus("seteuid");
 
1929
      }
 
1930
    } else {
 
1931
      /* Lower privileges permanently */
 
1932
      ret = setuid(uid);
 
1933
      if(ret == -1){
 
1934
        perror_plus("setuid");
 
1935
      }
 
1936
    }
 
1937
  }
 
1938
  
 
1939
  if(quit_now){
 
1940
    goto end;
 
1941
  }
 
1942
  
 
1943
  ret = init_gnutls_global(pubkey, seckey);
 
1944
  if(ret == -1){
 
1945
    fprintf(stderr, "init_gnutls_global failed\n");
 
1946
    exitcode = EX_UNAVAILABLE;
 
1947
    goto end;
 
1948
  } else {
 
1949
    gnutls_initialized = true;
 
1950
  }
 
1951
  
 
1952
  if(quit_now){
 
1953
    goto end;
 
1954
  }
 
1955
  
 
1956
  if(mkdtemp(tempdir) == NULL){
 
1957
    perror_plus("mkdtemp");
 
1958
    goto end;
 
1959
  }
 
1960
  tempdir_created = true;
 
1961
  
 
1962
  if(quit_now){
 
1963
    goto end;
 
1964
  }
 
1965
  
 
1966
  if(not init_gpgme(pubkey, seckey, tempdir)){
 
1967
    fprintf(stderr, "init_gpgme failed\n");
 
1968
    exitcode = EX_UNAVAILABLE;
 
1969
    goto end;
 
1970
  } else {
 
1971
    gpgme_initialized = true;
 
1972
  }
 
1973
  
 
1974
  if(quit_now){
 
1975
    goto end;
 
1976
  }
 
1977
  
 
1978
  if(connect_to != NULL){
 
1979
    /* Connect directly, do not use Zeroconf */
 
1980
    /* (Mainly meant for debugging) */
 
1981
    char *address = strrchr(connect_to, ':');
 
1982
    if(address == NULL){
 
1983
      fprintf(stderr, "No colon in address\n");
 
1984
      exitcode = EX_USAGE;
 
1985
      goto end;
 
1986
    }
 
1987
    
 
1988
    if(quit_now){
 
1989
      goto end;
 
1990
    }
 
1991
    
 
1992
    uint16_t port;
 
1993
    errno = 0;
 
1994
    tmpmax = strtoimax(address+1, &tmp, 10);
 
1995
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
 
1996
       or tmpmax != (uint16_t)tmpmax){
 
1997
      fprintf(stderr, "Bad port number\n");
 
1998
      exitcode = EX_USAGE;
 
1999
      goto end;
 
2000
    }
 
2001
  
 
2002
    if(quit_now){
 
2003
      goto end;
 
2004
    }
 
2005
    
 
2006
    port = (uint16_t)tmpmax;
 
2007
    *address = '\0';
 
2008
    /* Colon in address indicates IPv6 */
 
2009
    int af;
 
2010
    if(strchr(connect_to, ':') != NULL){
 
2011
      af = AF_INET6;
 
2012
      /* Accept [] around IPv6 address - see RFC 5952 */
 
2013
      if(connect_to[0] == '[' and address[-1] == ']')
 
2014
        {
 
2015
          connect_to++;
 
2016
          address[-1] = '\0';
 
2017
        }
 
2018
    } else {
 
2019
      af = AF_INET;
 
2020
    }
 
2021
    address = connect_to;
 
2022
    
 
2023
    if(quit_now){
 
2024
      goto end;
 
2025
    }
 
2026
    
 
2027
    while(not quit_now){
 
2028
      ret = start_mandos_communication(address, port, if_index, af);
 
2029
      if(quit_now or ret == 0){
 
2030
        break;
 
2031
      }
 
2032
      if(debug){
 
2033
        fprintf(stderr, "Retrying in %d seconds\n",
 
2034
                (int)retry_interval);
 
2035
      }
 
2036
      sleep((int)retry_interval);
 
2037
    }
 
2038
    
 
2039
    if (not quit_now){
 
2040
      exitcode = EXIT_SUCCESS;
 
2041
    }
 
2042
    
 
2043
    goto end;
 
2044
  }
 
2045
  
 
2046
  if(quit_now){
 
2047
    goto end;
 
2048
  }
 
2049
  
 
2050
  {
 
2051
    AvahiServerConfig config;
 
2052
    /* Do not publish any local Zeroconf records */
 
2053
    avahi_server_config_init(&config);
 
2054
    config.publish_hinfo = 0;
 
2055
    config.publish_addresses = 0;
 
2056
    config.publish_workstation = 0;
 
2057
    config.publish_domain = 0;
 
2058
    
 
2059
    /* Allocate a new server */
 
2060
    mc.server = avahi_server_new(avahi_simple_poll_get
 
2061
                                 (mc.simple_poll), &config, NULL,
 
2062
                                 NULL, &error);
 
2063
    
 
2064
    /* Free the Avahi configuration data */
 
2065
    avahi_server_config_free(&config);
 
2066
  }
 
2067
  
 
2068
  /* Check if creating the Avahi server object succeeded */
 
2069
  if(mc.server == NULL){
 
2070
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
2071
            avahi_strerror(error));
 
2072
    exitcode = EX_UNAVAILABLE;
 
2073
    goto end;
 
2074
  }
 
2075
  
 
2076
  if(quit_now){
 
2077
    goto end;
 
2078
  }
 
2079
  
 
2080
  /* Create the Avahi service browser */
 
2081
  sb = avahi_s_service_browser_new(mc.server, if_index,
 
2082
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
 
2083
                                   NULL, 0, browse_callback, NULL);
 
2084
  if(sb == NULL){
 
2085
    fprintf(stderr, "Failed to create service browser: %s\n",
 
2086
            avahi_strerror(avahi_server_errno(mc.server)));
 
2087
    exitcode = EX_UNAVAILABLE;
 
2088
    goto end;
 
2089
  }
 
2090
  
 
2091
  if(quit_now){
 
2092
    goto end;
 
2093
  }
 
2094
  
 
2095
  /* Run the main loop */
 
2096
  
 
2097
  if(debug){
 
2098
    fprintf(stderr, "Starting Avahi loop search\n");
 
2099
  }
 
2100
 
 
2101
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
2102
                                (int)(retry_interval * 1000));
 
2103
  if(debug){
 
2104
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
2105
            (ret == 0) ? "successfully" : "with error");
 
2106
  }
 
2107
  
1031
2108
 end:
1032
 
 
1033
 
    if (debug){
1034
 
      fprintf(stderr, "%s exiting\n", argv[0]);
1035
 
    }
1036
 
    
1037
 
    /* Cleanup things */
1038
 
    if (sb != NULL)
1039
 
        avahi_s_service_browser_free(sb);
1040
 
    
1041
 
    if (mc.server != NULL)
1042
 
        avahi_server_free(mc.server);
1043
 
 
1044
 
    if (mc.simple_poll != NULL)
1045
 
        avahi_simple_poll_free(mc.simple_poll);
1046
 
    free(pubkeyfile);
1047
 
    free(seckeyfile);
1048
 
 
1049
 
    if (gnutls_initalized){
1050
 
      gnutls_certificate_free_credentials(mc.cred);
1051
 
      gnutls_global_deinit ();
1052
 
    }
1053
 
    
1054
 
    return exitcode;
 
2109
  
 
2110
  if(debug){
 
2111
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2112
  }
 
2113
  
 
2114
  /* Cleanup things */
 
2115
  if(sb != NULL)
 
2116
    avahi_s_service_browser_free(sb);
 
2117
  
 
2118
  if(mc.server != NULL)
 
2119
    avahi_server_free(mc.server);
 
2120
  
 
2121
  if(mc.simple_poll != NULL)
 
2122
    avahi_simple_poll_free(mc.simple_poll);
 
2123
  
 
2124
  if(gnutls_initialized){
 
2125
    gnutls_certificate_free_credentials(mc.cred);
 
2126
    gnutls_global_deinit();
 
2127
    gnutls_dh_params_deinit(mc.dh_params);
 
2128
  }
 
2129
  
 
2130
  if(gpgme_initialized){
 
2131
    gpgme_release(mc.ctx);
 
2132
  }
 
2133
 
 
2134
  /* Cleans up the circular linked list of Mandos servers the client
 
2135
     has seen */
 
2136
  if(mc.current_server != NULL){
 
2137
    mc.current_server->prev->next = NULL;
 
2138
    while(mc.current_server != NULL){
 
2139
      server *next = mc.current_server->next;
 
2140
      free(mc.current_server);
 
2141
      mc.current_server = next;
 
2142
    }
 
2143
  }
 
2144
  
 
2145
  /* XXX run network hooks "stop" here  */
 
2146
  
 
2147
  /* Take down the network interface */
 
2148
  if(take_down_interface){
 
2149
    /* Re-raise priviliges */
 
2150
    errno = 0;
 
2151
    ret = seteuid(0);
 
2152
    if(ret == -1){
 
2153
      perror_plus("seteuid");
 
2154
    }
 
2155
    if(geteuid() == 0){
 
2156
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
2157
      if(ret == -1){
 
2158
        perror_plus("ioctl SIOCGIFFLAGS");
 
2159
      } else if(network.ifr_flags & IFF_UP) {
 
2160
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
2161
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
2162
        if(ret == -1){
 
2163
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
2164
        }
 
2165
      }
 
2166
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2167
      if(ret == -1){
 
2168
        perror_plus("close");
 
2169
      }
 
2170
      /* Lower privileges permanently */
 
2171
      errno = 0;
 
2172
      ret = setuid(uid);
 
2173
      if(ret == -1){
 
2174
        perror_plus("setuid");
 
2175
      }
 
2176
    }
 
2177
  }
 
2178
  
 
2179
  /* Removes the GPGME temp directory and all files inside */
 
2180
  if(tempdir_created){
 
2181
    struct dirent **direntries = NULL;
 
2182
    struct dirent *direntry = NULL;
 
2183
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2184
                             alphasort);
 
2185
    if (numentries > 0){
 
2186
      for(int i = 0; i < numentries; i++){
 
2187
        direntry = direntries[i];
 
2188
        char *fullname = NULL;
 
2189
        ret = asprintf(&fullname, "%s/%s", tempdir,
 
2190
                       direntry->d_name);
 
2191
        if(ret < 0){
 
2192
          perror_plus("asprintf");
 
2193
          continue;
 
2194
        }
 
2195
        ret = remove(fullname);
 
2196
        if(ret == -1){
 
2197
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
2198
                  strerror(errno));
 
2199
        }
 
2200
        free(fullname);
 
2201
      }
 
2202
    }
 
2203
 
 
2204
    /* need to clean even if 0 because man page doesn't specify */
 
2205
    free(direntries);
 
2206
    if (numentries == -1){
 
2207
      perror_plus("scandir");
 
2208
    }
 
2209
    ret = rmdir(tempdir);
 
2210
    if(ret == -1 and errno != ENOENT){
 
2211
      perror_plus("rmdir");
 
2212
    }
 
2213
  }
 
2214
  
 
2215
  if(quit_now){
 
2216
    sigemptyset(&old_sigterm_action.sa_mask);
 
2217
    old_sigterm_action.sa_handler = SIG_DFL;
 
2218
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
 
2219
                                            &old_sigterm_action,
 
2220
                                            NULL));
 
2221
    if(ret == -1){
 
2222
      perror_plus("sigaction");
 
2223
    }
 
2224
    do {
 
2225
      ret = raise(signal_received);
 
2226
    } while(ret != 0 and errno == EINTR);
 
2227
    if(ret != 0){
 
2228
      perror_plus("raise");
 
2229
      abort();
 
2230
    }
 
2231
    TEMP_FAILURE_RETRY(pause());
 
2232
  }
 
2233
  
 
2234
  return exitcode;
1055
2235
}