/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: 2008-12-10 01:26:02 UTC
  • mfrom: (237.1.2 mandos)
  • Revision ID: teddy@fukt.bsnet.se-20081210012602-vhz3h75xkj24t340
First version of a somewhat complete D-Bus server interface.  Also
change user/group name to "_mandos".

* debian/mandos.postinst: Rename old "mandos" user and group to
                          "_mandos"; create "_mandos" user and group
                          if none exist.
* debian/mandos-client.postinst: - '' -

* initramfs-tools-hook: Try "_mandos" before "mandos" as user and
                        group name.

* mandos (_datetime_to_dbus_struct): New; was previously local.
  (Client.started): Renamed to "last_started".  All users changed.
  (Client.started): New; boolean.
  (Client.dbus_object_path): New.
  (Client.check_command): Renamed to "checker_command".  All users
                          changed.
  (Client.__init__): Set and use "self.dbus_object_path".  Set
                     "self.started".
  (Client.start): Update "self.started".  Emit "self.PropertyChanged"
                  signals for both "started" and "last_started".
  (Client.stop): Update "self.started".  Emit "self.PropertyChanged"
                 signal for "started".
  (Client.checker_callback): Take additional "command" argument.  All
                             callers changed. Emit
                             "self.PropertyChanged" signal.
  (Client.bump_timeout): Emit "self.PropertyChanged" signal for
                         "last_checked_ok".
  (Client.start_checker): Emit "self.PropertyChanged" signal for
                          "checker_running".
  (Client.stop_checker): Emit "self.PropertyChanged" signal for
                         "checker_running".
  (Client.still_valid): Bug fix: use "getattr(self, started, False)"
                        instead of "self.started" in case this client
                        object is so new that the "started" attribute
                        has not been created yet.
  (Client.IntervalChanged, Client.CheckerIsRunning, Client.GetChecker,
  Client.GetCreated, Client.GetFingerprint, Client.GetHost,
  Client.GetInterval, Client.GetName, Client.GetStarted,
  Client.GetTimeout, Client.StateChanged, Client.TimeoutChanged):
  Removed; all callers changed.
  (Client.CheckerCompleted): Add "condition" and "command" arguments.
                             All callers changed.
  (Client.GetAllProperties, Client.PropertyChanged): New.
  (Client.StillValid): Renamed to "IsStillValid".
  (Client.StartChecker): Changed to its own function to avoid the
                         return value from "Client.start_checker()".
  (Client.Stop): Changed to its own function to avoid the return value
                 from "Client.stop()".
  (main): Try "_mandos" before "mandos" as user and group name.
          Removed inner function "remove_from_clients".  New inner
          class "MandosServer".

Show diffs side-by-side

added added

removed removed

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