/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 at bsnet
  • Date: 2011-12-24 23:17:02 UTC
  • Revision ID: teddy@fukt.bsnet.se-20111224231702-1ffgu6r02p0bz9co
* plugins.d/splashy.c (error_plus): Check format string.
* plugins.d/askpass-fifo.c (error_plus): - '' -
* plugins.d/plymouth.c (error_plus): - '' -
* plugins.d/password-prompt.c (error_plus): - '' -
* plugins.d/usplash.c (error_plus): - '' -

Show diffs side-by-side

added added

removed removed

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