/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

  • Committer: Teddy Hogeborn
  • Date: 2012-06-16 22:38:54 UTC
  • Revision ID: teddy@recompile.se-20120616223854-mfxkg6fgqr56sma5
* plugins.d/mandos-client (mandos_context): Removed "simple_poll"
                                            member.
  (simple_poll): New global variable.  All users changed.

Show diffs side-by-side

added added

removed removed

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