/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: 2014-06-07 20:29:36 UTC
  • Revision ID: teddy@recompile.se-20140607202936-crh5fxrdd804oora
Fix typo in code comment.

* debian/mandos.postinst: Fix typo in comment.

Show diffs side-by-side

added added

removed removed

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