/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: 2009-10-22 00:05:01 UTC
  • Revision ID: teddy@fukt.bsnet.se-20091022000501-g792e99q5g1wkyet
Merge from release branch.

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