/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/mandosclient.c

  • Committer: Teddy Hogeborn
  • Date: 2008-07-31 19:48:05 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080731194805-mseis21dxwrdfqhk
* plugins.d/mandosclient.c (start_mandos_communication): Changed
                                                        "if_index" to
                                                        be of type
                                                        "AvahiIfIndex".
                                                        All callers
                                                        changed.
 (main): Add default values to "interface" and "if_index".  Only
         change if_index from default if "interface" was given.

* server.py (IPv6_TCPServer.server_bind): Bug fix: test if interface
                                          is empty, not if equal to
                                          avahi.IF_UNSPEC.
  (if_nametoindex): Bug fix; typo: assign to _func[0], not func[0].
  (main): Bug fix: Do not set service.interface unless the interface
          setting has been given.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/*  -*- coding: utf-8 -*- */
2
2
/*
3
 
 * Mandos-client - get and decrypt data from a Mandos server
 
3
 * Mandos client - get and decrypt data from a Mandos server
4
4
 *
5
5
 * This program is partly derived from an example program for an Avahi
6
6
 * service browser, downloaded from
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2011 Teddy Hogeborn
13
 
 * Copyright © 2008-2011 Björn Påhlsson
 
12
 * Copyright © 2007-2008 Teddy Hogeborn & Björn Påhlsson
14
13
 * 
15
14
 * This program is free software: you can redistribute it and/or
16
15
 * modify it under the terms of the GNU General Public License as
26
25
 * along with this program.  If not, see
27
26
 * <http://www.gnu.org/licenses/>.
28
27
 * 
29
 
 * Contact the authors at <mandos@fukt.bsnet.se>.
 
28
 * Contact the authors at <https://www.fukt.bsnet.se/~belorn/> and
 
29
 * <https://www.fukt.bsnet.se/~teddy/>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
33
 
#ifndef _LARGEFILE_SOURCE
34
33
#define _LARGEFILE_SOURCE
35
 
#endif
36
 
#ifndef _FILE_OFFSET_BITS
37
34
#define _FILE_OFFSET_BITS 64
38
 
#endif
39
 
 
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() */
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
 
#include <time.h>               /* nanosleep(), time(), sleep() */
67
 
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
68
 
                                   SIOCSIFFLAGS, if_indextoname(),
69
 
                                   if_nametoindex(), IF_NAMESIZE */
70
 
#include <netinet/in.h>         /* IN6_IS_ADDR_LINKLOCAL,
71
 
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
72
 
                                */
73
 
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
74
 
                                   getuid(), getgid(), seteuid(),
75
 
                                   setgid(), pause() */
76
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
77
 
#include <iso646.h>             /* not, or, and */
78
 
#include <argp.h>               /* struct argp_option, error_t, struct
79
 
                                   argp_state, struct argp,
80
 
                                   argp_parse(), ARGP_KEY_ARG,
81
 
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
82
 
#include <signal.h>             /* sigemptyset(), sigaddset(),
83
 
                                   sigaction(), SIGTERM, sig_atomic_t,
84
 
                                   raise() */
85
 
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
86
 
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
87
 
 
88
 
#ifdef __linux__
89
 
#include <sys/klog.h>           /* klogctl() */
90
 
#endif  /* __linux__ */
91
 
 
92
 
/* Avahi */
93
 
/* All Avahi types, constants and functions
94
 
 Avahi*, avahi_*,
95
 
 AVAHI_* */
 
35
 
 
36
#include <stdio.h>
 
37
#include <assert.h>
 
38
#include <stdlib.h>
 
39
#include <time.h>
 
40
#include <net/if.h>             /* if_nametoindex */
 
41
 
96
42
#include <avahi-core/core.h>
97
43
#include <avahi-core/lookup.h>
98
44
#include <avahi-core/log.h>
100
46
#include <avahi-common/malloc.h>
101
47
#include <avahi-common/error.h>
102
48
 
103
 
/* GnuTLS */
104
 
#include <gnutls/gnutls.h>      /* All GnuTLS types, constants and
105
 
                                   functions:
106
 
                                   gnutls_*
107
 
                                   init_gnutls_session(),
108
 
                                   GNUTLS_* */
109
 
#include <gnutls/openpgp.h>
110
 
                          /* gnutls_certificate_set_openpgp_key_file(),
111
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
112
 
 
113
 
/* GPGME */
114
 
#include <gpgme.h>              /* All GPGME types, constants and
115
 
                                   functions:
116
 
                                   gpgme_*
117
 
                                   GPGME_PROTOCOL_OpenPGP,
118
 
                                   GPG_ERR_NO_* */
119
 
 
 
49
//mandos client part
 
50
#include <sys/types.h>          /* socket(), inet_pton() */
 
51
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
 
52
                                   struct in6_addr, inet_pton() */
 
53
#include <gnutls/gnutls.h>      /* All GnuTLS stuff */
 
54
#include <gnutls/openpgp.h>     /* GnuTLS with openpgp stuff */
 
55
 
 
56
#include <unistd.h>             /* close() */
 
57
#include <netinet/in.h>
 
58
#include <stdbool.h>            /* true */
 
59
#include <string.h>             /* memset */
 
60
#include <arpa/inet.h>          /* inet_pton() */
 
61
#include <iso646.h>             /* not */
 
62
 
 
63
// gpgme
 
64
#include <errno.h>              /* perror() */
 
65
#include <gpgme.h>
 
66
 
 
67
// getopt long
 
68
#include <getopt.h>
 
69
 
 
70
#ifndef CERT_ROOT
 
71
#define CERT_ROOT "/conf/conf.d/cryptkeyreq/"
 
72
#endif
 
73
#define CERTFILE CERT_ROOT "openpgp-client.txt"
 
74
#define KEYFILE CERT_ROOT "openpgp-client-key.txt"
120
75
#define BUFFER_SIZE 256
121
 
 
122
 
#define PATHDIR "/conf/conf.d/mandos"
123
 
#define SECKEY "seckey.txt"
124
 
#define PUBKEY "pubkey.txt"
 
76
#define DH_BITS 1024
125
77
 
126
78
bool debug = false;
127
 
static const char mandos_protocol_version[] = "1";
128
 
const char *argp_program_version = "mandos-client " VERSION;
129
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
130
 
static const char sys_class_net[] = "/sys/class/net";
131
 
char *connect_to = NULL;
132
79
 
133
 
/* Used for passing in values through the Avahi callback functions */
134
80
typedef struct {
135
 
  AvahiSimplePoll *simple_poll;
136
 
  AvahiServer *server;
 
81
  gnutls_session_t session;
137
82
  gnutls_certificate_credentials_t cred;
138
 
  unsigned int dh_bits;
139
83
  gnutls_dh_params_t dh_params;
140
 
  const char *priority;
 
84
} encrypted_session;
 
85
 
 
86
 
 
87
ssize_t pgp_packet_decrypt (char *packet, size_t packet_size,
 
88
                            char **new_packet, const char *homedir){
 
89
  gpgme_data_t dh_crypto, dh_plain;
141
90
  gpgme_ctx_t ctx;
142
 
} mandos_context;
143
 
 
144
 
/* global context so signal handler can reach it*/
145
 
mandos_context mc = { .simple_poll = NULL, .server = NULL,
146
 
                      .dh_bits = 1024, .priority = "SECURE256"
147
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
148
 
 
149
 
sig_atomic_t quit_now = 0;
150
 
int signal_received = 0;
151
 
 
152
 
/*
153
 
 * Make additional room in "buffer" for at least BUFFER_SIZE more
154
 
 * bytes. "buffer_capacity" is how much is currently allocated,
155
 
 * "buffer_length" is how much is already used.
156
 
 */
157
 
size_t incbuffer(char **buffer, size_t buffer_length,
158
 
                  size_t buffer_capacity){
159
 
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
160
 
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
161
 
    if(buffer == NULL){
162
 
      return 0;
163
 
    }
164
 
    buffer_capacity += BUFFER_SIZE;
165
 
  }
166
 
  return buffer_capacity;
167
 
}
168
 
 
169
 
/* 
170
 
 * Initialize GPGME.
171
 
 */
172
 
static bool init_gpgme(const char *seckey,
173
 
                       const char *pubkey, const char *tempdir){
174
91
  gpgme_error_t rc;
 
92
  ssize_t ret;
 
93
  ssize_t new_packet_capacity = 0;
 
94
  ssize_t new_packet_length = 0;
175
95
  gpgme_engine_info_t engine_info;
176
 
  
177
 
  
178
 
  /*
179
 
   * Helper function to insert pub and seckey to the engine keyring.
180
 
   */
181
 
  bool import_key(const char *filename){
182
 
    int ret;
183
 
    int fd;
184
 
    gpgme_data_t pgp_data;
185
 
    
186
 
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
187
 
    if(fd == -1){
188
 
      perror("open");
189
 
      return false;
190
 
    }
191
 
    
192
 
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
193
 
    if(rc != GPG_ERR_NO_ERROR){
194
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
195
 
              gpgme_strsource(rc), gpgme_strerror(rc));
196
 
      return false;
197
 
    }
198
 
    
199
 
    rc = gpgme_op_import(mc.ctx, pgp_data);
200
 
    if(rc != GPG_ERR_NO_ERROR){
201
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
202
 
              gpgme_strsource(rc), gpgme_strerror(rc));
203
 
      return false;
204
 
    }
205
 
    
206
 
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
207
 
    if(ret == -1){
208
 
      perror("close");
209
 
    }
210
 
    gpgme_data_release(pgp_data);
211
 
    return true;
212
 
  }
213
 
  
214
 
  if(debug){
215
 
    fprintf(stderr, "Initializing GPGME\n");
 
96
 
 
97
  if (debug){
 
98
    fprintf(stderr, "Trying to decrypt OpenPGP packet\n");
216
99
  }
217
100
  
218
101
  /* Init GPGME */
219
102
  gpgme_check_version(NULL);
220
 
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
221
 
  if(rc != GPG_ERR_NO_ERROR){
222
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
223
 
            gpgme_strsource(rc), gpgme_strerror(rc));
224
 
    return false;
225
 
  }
 
103
  gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
226
104
  
227
 
    /* Set GPGME home directory for the OpenPGP engine only */
228
 
  rc = gpgme_get_engine_info(&engine_info);
229
 
  if(rc != GPG_ERR_NO_ERROR){
 
105
  /* Set GPGME home directory */
 
106
  rc = gpgme_get_engine_info (&engine_info);
 
107
  if (rc != GPG_ERR_NO_ERROR){
230
108
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
231
109
            gpgme_strsource(rc), gpgme_strerror(rc));
232
 
    return false;
 
110
    return -1;
233
111
  }
234
112
  while(engine_info != NULL){
235
113
    if(engine_info->protocol == GPGME_PROTOCOL_OpenPGP){
236
114
      gpgme_set_engine_info(GPGME_PROTOCOL_OpenPGP,
237
 
                            engine_info->file_name, tempdir);
 
115
                            engine_info->file_name, homedir);
238
116
      break;
239
117
    }
240
118
    engine_info = engine_info->next;
241
119
  }
242
120
  if(engine_info == NULL){
243
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
244
 
    return false;
245
 
  }
246
 
  
247
 
  /* Create new GPGME "context" */
248
 
  rc = gpgme_new(&(mc.ctx));
249
 
  if(rc != GPG_ERR_NO_ERROR){
250
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
251
 
            gpgme_strsource(rc), gpgme_strerror(rc));
252
 
    return false;
253
 
  }
254
 
  
255
 
  if(not import_key(pubkey) or not import_key(seckey)){
256
 
    return false;
257
 
  }
258
 
  
259
 
  return true;
260
 
}
261
 
 
262
 
/* 
263
 
 * Decrypt OpenPGP data.
264
 
 * Returns -1 on error
265
 
 */
266
 
static ssize_t pgp_packet_decrypt(const char *cryptotext,
267
 
                                  size_t crypto_size,
268
 
                                  char **plaintext){
269
 
  gpgme_data_t dh_crypto, dh_plain;
270
 
  gpgme_error_t rc;
271
 
  ssize_t ret;
272
 
  size_t plaintext_capacity = 0;
273
 
  ssize_t plaintext_length = 0;
274
 
  
275
 
  if(debug){
276
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
277
 
  }
278
 
  
279
 
  /* Create new GPGME data buffer from memory cryptotext */
280
 
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
281
 
                               0);
282
 
  if(rc != GPG_ERR_NO_ERROR){
 
121
    fprintf(stderr, "Could not set home dir to %s\n", homedir);
 
122
    return -1;
 
123
  }
 
124
  
 
125
  /* Create new GPGME data buffer from packet buffer */
 
126
  rc = gpgme_data_new_from_mem(&dh_crypto, packet, packet_size, 0);
 
127
  if (rc != GPG_ERR_NO_ERROR){
283
128
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
284
129
            gpgme_strsource(rc), gpgme_strerror(rc));
285
130
    return -1;
287
132
  
288
133
  /* Create new empty GPGME data buffer for the plaintext */
289
134
  rc = gpgme_data_new(&dh_plain);
290
 
  if(rc != GPG_ERR_NO_ERROR){
 
135
  if (rc != GPG_ERR_NO_ERROR){
291
136
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
292
137
            gpgme_strsource(rc), gpgme_strerror(rc));
293
 
    gpgme_data_release(dh_crypto);
294
 
    return -1;
295
 
  }
296
 
  
297
 
  /* Decrypt data from the cryptotext data buffer to the plaintext
298
 
     data buffer */
299
 
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
300
 
  if(rc != GPG_ERR_NO_ERROR){
 
138
    return -1;
 
139
  }
 
140
  
 
141
  /* Create new GPGME "context" */
 
142
  rc = gpgme_new(&ctx);
 
143
  if (rc != GPG_ERR_NO_ERROR){
 
144
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
145
            gpgme_strsource(rc), gpgme_strerror(rc));
 
146
    return -1;
 
147
  }
 
148
  
 
149
  /* Decrypt data from the FILE pointer to the plaintext data
 
150
     buffer */
 
151
  rc = gpgme_op_decrypt(ctx, dh_crypto, dh_plain);
 
152
  if (rc != GPG_ERR_NO_ERROR){
301
153
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
302
154
            gpgme_strsource(rc), gpgme_strerror(rc));
303
 
    plaintext_length = -1;
304
 
    if(debug){
305
 
      gpgme_decrypt_result_t result;
306
 
      result = gpgme_op_decrypt_result(mc.ctx);
307
 
      if(result == NULL){
308
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
309
 
      } else {
310
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
311
 
                result->unsupported_algorithm);
312
 
        fprintf(stderr, "Wrong key usage: %u\n",
313
 
                result->wrong_key_usage);
314
 
        if(result->file_name != NULL){
315
 
          fprintf(stderr, "File name: %s\n", result->file_name);
316
 
        }
317
 
        gpgme_recipient_t recipient;
318
 
        recipient = result->recipients;
 
155
    return -1;
 
156
  }
 
157
 
 
158
  if(debug){
 
159
    fprintf(stderr, "Decryption of OpenPGP packet succeeded\n");
 
160
  }
 
161
 
 
162
  if (debug){
 
163
    gpgme_decrypt_result_t result;
 
164
    result = gpgme_op_decrypt_result(ctx);
 
165
    if (result == NULL){
 
166
      fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
167
    } else {
 
168
      fprintf(stderr, "Unsupported algorithm: %s\n",
 
169
              result->unsupported_algorithm);
 
170
      fprintf(stderr, "Wrong key usage: %d\n",
 
171
              result->wrong_key_usage);
 
172
      if(result->file_name != NULL){
 
173
        fprintf(stderr, "File name: %s\n", result->file_name);
 
174
      }
 
175
      gpgme_recipient_t recipient;
 
176
      recipient = result->recipients;
 
177
      if(recipient){
319
178
        while(recipient != NULL){
320
179
          fprintf(stderr, "Public key algorithm: %s\n",
321
180
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
327
186
        }
328
187
      }
329
188
    }
330
 
    goto decrypt_end;
331
189
  }
332
190
  
333
 
  if(debug){
334
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
335
 
  }
 
191
  /* Delete the GPGME FILE pointer cryptotext data buffer */
 
192
  gpgme_data_release(dh_crypto);
336
193
  
337
194
  /* Seek back to the beginning of the GPGME plaintext data buffer */
338
 
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
339
 
    perror("gpgme_data_seek");
340
 
    plaintext_length = -1;
341
 
    goto decrypt_end;
342
 
  }
343
 
  
344
 
  *plaintext = NULL;
 
195
  gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET);
 
196
 
 
197
  *new_packet = 0;
345
198
  while(true){
346
 
    plaintext_capacity = incbuffer(plaintext,
347
 
                                      (size_t)plaintext_length,
348
 
                                      plaintext_capacity);
349
 
    if(plaintext_capacity == 0){
350
 
        perror("incbuffer");
351
 
        plaintext_length = -1;
352
 
        goto decrypt_end;
 
199
    if (new_packet_length + BUFFER_SIZE > new_packet_capacity){
 
200
      *new_packet = realloc(*new_packet,
 
201
                            (unsigned int)new_packet_capacity
 
202
                            + BUFFER_SIZE);
 
203
      if (*new_packet == NULL){
 
204
        perror("realloc");
 
205
        return -1;
 
206
      }
 
207
      new_packet_capacity += BUFFER_SIZE;
353
208
    }
354
209
    
355
 
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
 
210
    ret = gpgme_data_read(dh_plain, *new_packet + new_packet_length,
356
211
                          BUFFER_SIZE);
357
212
    /* Print the data, if any */
358
 
    if(ret == 0){
359
 
      /* EOF */
 
213
    if (ret == 0){
360
214
      break;
361
215
    }
362
216
    if(ret < 0){
363
217
      perror("gpgme_data_read");
364
 
      plaintext_length = -1;
365
 
      goto decrypt_end;
366
 
    }
367
 
    plaintext_length += ret;
368
 
  }
369
 
  
370
 
  if(debug){
371
 
    fprintf(stderr, "Decrypted password is: ");
372
 
    for(ssize_t i = 0; i < plaintext_length; i++){
373
 
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
374
 
    }
375
 
    fprintf(stderr, "\n");
376
 
  }
377
 
  
378
 
 decrypt_end:
379
 
  
380
 
  /* Delete the GPGME cryptotext data buffer */
381
 
  gpgme_data_release(dh_crypto);
 
218
      return -1;
 
219
    }
 
220
    new_packet_length += ret;
 
221
  }
 
222
 
 
223
  /* FIXME: check characters before printing to screen so to not print
 
224
     terminal control characters */
 
225
  /*   if(debug){ */
 
226
  /*     fprintf(stderr, "decrypted password is: "); */
 
227
  /*     fwrite(*new_packet, 1, new_packet_length, stderr); */
 
228
  /*     fprintf(stderr, "\n"); */
 
229
  /*   } */
382
230
  
383
231
  /* Delete the GPGME plaintext data buffer */
384
232
  gpgme_data_release(dh_plain);
385
 
  return plaintext_length;
 
233
  return new_packet_length;
386
234
}
387
235
 
388
 
static const char * safer_gnutls_strerror(int value){
389
 
  const char *ret = gnutls_strerror(value); /* Spurious warning from
390
 
                                               -Wunreachable-code */
391
 
  if(ret == NULL)
 
236
static const char * safer_gnutls_strerror (int value) {
 
237
  const char *ret = gnutls_strerror (value);
 
238
  if (ret == NULL)
392
239
    ret = "(unknown)";
393
240
  return ret;
394
241
}
395
242
 
396
 
/* GnuTLS log function callback */
397
 
static void debuggnutls(__attribute__((unused)) int level,
398
 
                        const char* string){
399
 
  fprintf(stderr, "GnuTLS: %s", string);
 
243
void debuggnutls(__attribute__((unused)) int level,
 
244
                 const char* string){
 
245
  fprintf(stderr, "%s", string);
400
246
}
401
247
 
402
 
static int init_gnutls_global(const char *pubkeyfilename,
403
 
                              const char *seckeyfilename){
 
248
int initgnutls(encrypted_session *es){
 
249
  const char *err;
404
250
  int ret;
405
251
  
406
252
  if(debug){
407
253
    fprintf(stderr, "Initializing GnuTLS\n");
408
254
  }
409
255
  
410
 
  ret = gnutls_global_init();
411
 
  if(ret != GNUTLS_E_SUCCESS){
412
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
413
 
            safer_gnutls_strerror(ret));
 
256
  if ((ret = gnutls_global_init ())
 
257
      != GNUTLS_E_SUCCESS) {
 
258
    fprintf (stderr, "global_init: %s\n", safer_gnutls_strerror(ret));
414
259
    return -1;
415
260
  }
416
 
  
417
 
  if(debug){
418
 
    /* "Use a log level over 10 to enable all debugging options."
419
 
     * - GnuTLS manual
420
 
     */
 
261
 
 
262
  if (debug){
421
263
    gnutls_global_set_log_level(11);
422
264
    gnutls_global_set_log_function(debuggnutls);
423
265
  }
424
266
  
425
 
  /* OpenPGP credentials */
426
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
427
 
  if(ret != GNUTLS_E_SUCCESS){
428
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
429
 
            safer_gnutls_strerror(ret));
430
 
    gnutls_global_deinit();
 
267
  /* openpgp credentials */
 
268
  if ((ret = gnutls_certificate_allocate_credentials (&es->cred))
 
269
      != GNUTLS_E_SUCCESS) {
 
270
    fprintf (stderr, "memory error: %s\n",
 
271
             safer_gnutls_strerror(ret));
431
272
    return -1;
432
273
  }
433
274
  
434
275
  if(debug){
435
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
436
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
437
 
            seckeyfilename);
 
276
    fprintf(stderr, "Attempting to use OpenPGP certificate %s"
 
277
            " and keyfile %s as GnuTLS credentials\n", CERTFILE,
 
278
            KEYFILE);
438
279
  }
439
280
  
440
281
  ret = gnutls_certificate_set_openpgp_key_file
441
 
    (mc.cred, pubkeyfilename, seckeyfilename,
442
 
     GNUTLS_OPENPGP_FMT_BASE64);
443
 
  if(ret != GNUTLS_E_SUCCESS){
444
 
    fprintf(stderr,
445
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
446
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
447
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
448
 
            safer_gnutls_strerror(ret));
449
 
    goto globalfail;
450
 
  }
451
 
  
452
 
  /* GnuTLS server initialization */
453
 
  ret = gnutls_dh_params_init(&mc.dh_params);
454
 
  if(ret != GNUTLS_E_SUCCESS){
455
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
456
 
            " %s\n", safer_gnutls_strerror(ret));
457
 
    goto globalfail;
458
 
  }
459
 
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
460
 
  if(ret != GNUTLS_E_SUCCESS){
461
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
462
 
            safer_gnutls_strerror(ret));
463
 
    goto globalfail;
464
 
  }
465
 
  
466
 
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
467
 
  
468
 
  return 0;
469
 
  
470
 
 globalfail:
471
 
  
472
 
  gnutls_certificate_free_credentials(mc.cred);
473
 
  gnutls_global_deinit();
474
 
  gnutls_dh_params_deinit(mc.dh_params);
475
 
  return -1;
476
 
}
477
 
 
478
 
static int init_gnutls_session(gnutls_session_t *session){
479
 
  int ret;
480
 
  /* GnuTLS session creation */
481
 
  do {
482
 
    ret = gnutls_init(session, GNUTLS_SERVER);
483
 
    if(quit_now){
484
 
      return -1;
485
 
    }
486
 
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
487
 
  if(ret != GNUTLS_E_SUCCESS){
 
282
    (es->cred, CERTFILE, KEYFILE, GNUTLS_OPENPGP_FMT_BASE64);
 
283
  if (ret != GNUTLS_E_SUCCESS) {
 
284
    fprintf
 
285
      (stderr, "Error[%d] while reading the OpenPGP key pair ('%s',"
 
286
       " '%s')\n",
 
287
       ret, CERTFILE, KEYFILE);
 
288
    fprintf(stdout, "The Error is: %s\n",
 
289
            safer_gnutls_strerror(ret));
 
290
    return -1;
 
291
  }
 
292
  
 
293
  //GnuTLS server initialization
 
294
  if ((ret = gnutls_dh_params_init (&es->dh_params))
 
295
      != GNUTLS_E_SUCCESS) {
 
296
    fprintf (stderr, "Error in dh parameter initialization: %s\n",
 
297
             safer_gnutls_strerror(ret));
 
298
    return -1;
 
299
  }
 
300
  
 
301
  if ((ret = gnutls_dh_params_generate2 (es->dh_params, DH_BITS))
 
302
      != GNUTLS_E_SUCCESS) {
 
303
    fprintf (stderr, "Error in prime generation: %s\n",
 
304
             safer_gnutls_strerror(ret));
 
305
    return -1;
 
306
  }
 
307
  
 
308
  gnutls_certificate_set_dh_params (es->cred, es->dh_params);
 
309
  
 
310
  // GnuTLS session creation
 
311
  if ((ret = gnutls_init (&es->session, GNUTLS_SERVER))
 
312
      != GNUTLS_E_SUCCESS){
488
313
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
489
314
            safer_gnutls_strerror(ret));
490
315
  }
491
316
  
492
 
  {
493
 
    const char *err;
494
 
    do {
495
 
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
496
 
      if(quit_now){
497
 
        gnutls_deinit(*session);
498
 
        return -1;
499
 
      }
500
 
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
501
 
    if(ret != GNUTLS_E_SUCCESS){
502
 
      fprintf(stderr, "Syntax error at: %s\n", err);
503
 
      fprintf(stderr, "GnuTLS error: %s\n",
504
 
              safer_gnutls_strerror(ret));
505
 
      gnutls_deinit(*session);
506
 
      return -1;
507
 
    }
 
317
  if ((ret = gnutls_priority_set_direct (es->session, "NORMAL", &err))
 
318
      != GNUTLS_E_SUCCESS) {
 
319
    fprintf(stderr, "Syntax error at: %s\n", err);
 
320
    fprintf(stderr, "GnuTLS error: %s\n",
 
321
            safer_gnutls_strerror(ret));
 
322
    return -1;
508
323
  }
509
324
  
510
 
  do {
511
 
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
512
 
                                 mc.cred);
513
 
    if(quit_now){
514
 
      gnutls_deinit(*session);
515
 
      return -1;
516
 
    }
517
 
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
518
 
  if(ret != GNUTLS_E_SUCCESS){
519
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
325
  if ((ret = gnutls_credentials_set
 
326
       (es->session, GNUTLS_CRD_CERTIFICATE, es->cred))
 
327
      != GNUTLS_E_SUCCESS) {
 
328
    fprintf(stderr, "Error setting a credentials set: %s\n",
520
329
            safer_gnutls_strerror(ret));
521
 
    gnutls_deinit(*session);
522
330
    return -1;
523
331
  }
524
332
  
525
333
  /* ignore client certificate if any. */
526
 
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
 
334
  gnutls_certificate_server_set_request (es->session,
 
335
                                         GNUTLS_CERT_IGNORE);
527
336
  
528
 
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
337
  gnutls_dh_set_prime_bits (es->session, DH_BITS);
529
338
  
530
339
  return 0;
531
340
}
532
341
 
533
 
/* Avahi log function callback */
534
 
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
535
 
                      __attribute__((unused)) const char *txt){}
 
342
void empty_log(__attribute__((unused)) AvahiLogLevel level,
 
343
               __attribute__((unused)) const char *txt){}
536
344
 
537
 
/* Called when a Mandos server is found */
538
 
static int start_mandos_communication(const char *ip, uint16_t port,
539
 
                                      AvahiIfIndex if_index,
540
 
                                      int af){
541
 
  int ret, tcp_sd = -1;
542
 
  ssize_t sret;
543
 
  union {
544
 
    struct sockaddr_in in;
545
 
    struct sockaddr_in6 in6;
546
 
  } to;
 
345
int start_mandos_communication(const char *ip, uint16_t port,
 
346
                               AvahiIfIndex if_index){
 
347
  int ret, tcp_sd;
 
348
  struct sockaddr_in6 to;
 
349
  encrypted_session es;
547
350
  char *buffer = NULL;
548
 
  char *decrypted_buffer = NULL;
 
351
  char *decrypted_buffer;
549
352
  size_t buffer_length = 0;
550
353
  size_t buffer_capacity = 0;
551
 
  size_t written;
552
 
  int retval = -1;
553
 
  gnutls_session_t session;
554
 
  int pf;                       /* Protocol family */
555
 
  
556
 
  errno = 0;
557
 
  
558
 
  if(quit_now){
559
 
    errno = EINTR;
560
 
    return -1;
561
 
  }
562
 
  
563
 
  switch(af){
564
 
  case AF_INET6:
565
 
    pf = PF_INET6;
566
 
    break;
567
 
  case AF_INET:
568
 
    pf = PF_INET;
569
 
    break;
570
 
  default:
571
 
    fprintf(stderr, "Bad address family: %d\n", af);
572
 
    errno = EINVAL;
573
 
    return -1;
574
 
  }
575
 
  
576
 
  ret = init_gnutls_session(&session);
577
 
  if(ret != 0){
578
 
    return -1;
579
 
  }
 
354
  ssize_t decrypted_buffer_size;
 
355
  size_t written = 0;
 
356
  int retval = 0;
 
357
  char interface[IF_NAMESIZE];
580
358
  
581
359
  if(debug){
582
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
583
 
            "\n", ip, port);
 
360
    fprintf(stderr, "Setting up a tcp connection to %s, port %d\n",
 
361
            ip, port);
584
362
  }
585
363
  
586
 
  tcp_sd = socket(pf, SOCK_STREAM, 0);
587
 
  if(tcp_sd < 0){
588
 
    int e = errno;
 
364
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
 
365
  if(tcp_sd < 0) {
589
366
    perror("socket");
590
 
    errno = e;
591
 
    goto mandos_end;
592
 
  }
593
 
  
594
 
  if(quit_now){
595
 
    errno = EINTR;
596
 
    goto mandos_end;
597
 
  }
598
 
  
599
 
  memset(&to, 0, sizeof(to));
600
 
  if(af == AF_INET6){
601
 
    to.in6.sin6_family = (sa_family_t)af;
602
 
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
603
 
  } else {                      /* IPv4 */
604
 
    to.in.sin_family = (sa_family_t)af;
605
 
    ret = inet_pton(af, ip, &to.in.sin_addr);
606
 
  }
607
 
  if(ret < 0 ){
608
 
    int e = errno;
 
367
    return -1;
 
368
  }
 
369
  
 
370
  if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
371
    if(debug){
 
372
      perror("if_indextoname");
 
373
    }
 
374
    return -1;
 
375
  }
 
376
  
 
377
  if(debug){
 
378
    fprintf(stderr, "Binding to interface %s\n", interface);
 
379
  }
 
380
  
 
381
  memset(&to,0,sizeof(to));     /* Spurious warning */
 
382
  to.sin6_family = AF_INET6;
 
383
  ret = inet_pton(AF_INET6, ip, &to.sin6_addr);
 
384
  if (ret < 0 ){
609
385
    perror("inet_pton");
610
 
    errno = e;
611
 
    goto mandos_end;
612
 
  }
 
386
    return -1;
 
387
  }  
613
388
  if(ret == 0){
614
 
    int e = errno;
615
389
    fprintf(stderr, "Bad address: %s\n", ip);
616
 
    errno = e;
617
 
    goto mandos_end;
618
 
  }
619
 
  if(af == AF_INET6){
620
 
    to.in6.sin6_port = htons(port); /* Spurious warnings from
621
 
                                       -Wconversion and
622
 
                                       -Wunreachable-code */
623
 
    
624
 
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
625
 
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
626
 
                              -Wunreachable-code*/
627
 
      if(if_index == AVAHI_IF_UNSPEC){
628
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
629
 
                " without a network interface\n");
630
 
        errno = EINVAL;
631
 
        goto mandos_end;
632
 
      }
633
 
      /* Set the network interface number as scope */
634
 
      to.in6.sin6_scope_id = (uint32_t)if_index;
635
 
    }
636
 
  } else {
637
 
    to.in.sin_port = htons(port); /* Spurious warnings from
638
 
                                     -Wconversion and
639
 
                                     -Wunreachable-code */
640
 
  }
 
390
    return -1;
 
391
  }
 
392
  to.sin6_port = htons(port);   /* Spurious warning */
641
393
  
642
 
  if(quit_now){
643
 
    errno = EINTR;
644
 
    goto mandos_end;
645
 
  }
 
394
  to.sin6_scope_id = (uint32_t)if_index;
646
395
  
647
396
  if(debug){
648
 
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
649
 
      char interface[IF_NAMESIZE];
650
 
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
651
 
        perror("if_indextoname");
652
 
      } else {
653
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
654
 
                ip, interface, port);
655
 
      }
656
 
    } else {
657
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
658
 
              port);
659
 
    }
660
 
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
661
 
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
662
 
    const char *pcret;
663
 
    if(af == AF_INET6){
664
 
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
665
 
                        sizeof(addrstr));
666
 
    } else {
667
 
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
668
 
                        sizeof(addrstr));
669
 
    }
670
 
    if(pcret == NULL){
671
 
      perror("inet_ntop");
672
 
    } else {
673
 
      if(strcmp(addrstr, ip) != 0){
674
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
675
 
      }
676
 
    }
677
 
  }
678
 
  
679
 
  if(quit_now){
680
 
    errno = EINTR;
681
 
    goto mandos_end;
682
 
  }
683
 
  
684
 
  if(af == AF_INET6){
685
 
    ret = connect(tcp_sd, &to.in6, sizeof(to));
686
 
  } else {
687
 
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
688
 
  }
689
 
  if(ret < 0){
690
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
691
 
      int e = errno;
692
 
      perror("connect");
693
 
      errno = e;
694
 
    }
695
 
    goto mandos_end;
696
 
  }
697
 
  
698
 
  if(quit_now){
699
 
    errno = EINTR;
700
 
    goto mandos_end;
701
 
  }
702
 
  
703
 
  const char *out = mandos_protocol_version;
704
 
  written = 0;
705
 
  while(true){
706
 
    size_t out_size = strlen(out);
707
 
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
708
 
                                   out_size - written));
709
 
    if(ret == -1){
710
 
      int e = errno;
711
 
      perror("write");
712
 
      errno = e;
713
 
      goto mandos_end;
714
 
    }
715
 
    written += (size_t)ret;
716
 
    if(written < out_size){
717
 
      continue;
718
 
    } else {
719
 
      if(out == mandos_protocol_version){
720
 
        written = 0;
721
 
        out = "\r\n";
722
 
      } else {
723
 
        break;
724
 
      }
725
 
    }
726
 
  
727
 
    if(quit_now){
728
 
      errno = EINTR;
729
 
      goto mandos_end;
730
 
    }
731
 
  }
 
397
    fprintf(stderr, "Connection to: %s, port %d\n", ip, port);
 
398
/*     char addrstr[INET6_ADDRSTRLEN]; */
 
399
/*     if(inet_ntop(to.sin6_family, &(to.sin6_addr), addrstr, */
 
400
/*               sizeof(addrstr)) == NULL){ */
 
401
/*       perror("inet_ntop"); */
 
402
/*     } else { */
 
403
/*       fprintf(stderr, "Really connecting to: %s, port %d\n", */
 
404
/*            addrstr, ntohs(to.sin6_port)); */
 
405
/*     } */
 
406
  }
 
407
  
 
408
  ret = connect(tcp_sd, (struct sockaddr *) &to, sizeof(to));
 
409
  if (ret < 0){
 
410
    perror("connect");
 
411
    return -1;
 
412
  }
 
413
  
 
414
  ret = initgnutls (&es);
 
415
  if (ret != 0){
 
416
    retval = -1;
 
417
    return -1;
 
418
  }
 
419
  
 
420
  gnutls_transport_set_ptr (es.session,
 
421
                            (gnutls_transport_ptr_t) tcp_sd);
732
422
  
733
423
  if(debug){
734
424
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
735
425
  }
736
426
  
737
 
  if(quit_now){
738
 
    errno = EINTR;
739
 
    goto mandos_end;
740
 
  }
741
 
  
742
 
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
743
 
  
744
 
  if(quit_now){
745
 
    errno = EINTR;
746
 
    goto mandos_end;
747
 
  }
748
 
  
749
 
  do {
750
 
    ret = gnutls_handshake(session);
751
 
    if(quit_now){
752
 
      errno = EINTR;
753
 
      goto mandos_end;
754
 
    }
755
 
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
756
 
  
757
 
  if(ret != GNUTLS_E_SUCCESS){
 
427
  ret = gnutls_handshake (es.session);
 
428
  
 
429
  if (ret != GNUTLS_E_SUCCESS){
758
430
    if(debug){
759
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
760
 
      gnutls_perror(ret);
 
431
      fprintf(stderr, "\n*** Handshake failed ***\n");
 
432
      gnutls_perror (ret);
761
433
    }
762
 
    errno = EPROTO;
763
 
    goto mandos_end;
 
434
    retval = -1;
 
435
    goto exit;
764
436
  }
765
437
  
766
 
  /* Read OpenPGP packet that contains the wanted password */
 
438
  //Retrieve OpenPGP packet that contains the wanted password
767
439
  
768
440
  if(debug){
769
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
441
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
770
442
            ip);
771
443
  }
772
 
  
 
444
 
773
445
  while(true){
774
 
    
775
 
    if(quit_now){
776
 
      errno = EINTR;
777
 
      goto mandos_end;
778
 
    }
779
 
    
780
 
    buffer_capacity = incbuffer(&buffer, buffer_length,
781
 
                                   buffer_capacity);
782
 
    if(buffer_capacity == 0){
783
 
      int e = errno;
784
 
      perror("incbuffer");
785
 
      errno = e;
786
 
      goto mandos_end;
787
 
    }
788
 
    
789
 
    if(quit_now){
790
 
      errno = EINTR;
791
 
      goto mandos_end;
792
 
    }
793
 
    
794
 
    sret = gnutls_record_recv(session, buffer+buffer_length,
795
 
                              BUFFER_SIZE);
796
 
    if(sret == 0){
 
446
    if (buffer_length + BUFFER_SIZE > buffer_capacity){
 
447
      buffer = realloc(buffer, buffer_capacity + BUFFER_SIZE);
 
448
      if (buffer == NULL){
 
449
        perror("realloc");
 
450
        goto exit;
 
451
      }
 
452
      buffer_capacity += BUFFER_SIZE;
 
453
    }
 
454
    
 
455
    ret = gnutls_record_recv
 
456
      (es.session, buffer+buffer_length, BUFFER_SIZE);
 
457
    if (ret == 0){
797
458
      break;
798
459
    }
799
 
    if(sret < 0){
800
 
      switch(sret){
 
460
    if (ret < 0){
 
461
      switch(ret){
801
462
      case GNUTLS_E_INTERRUPTED:
802
463
      case GNUTLS_E_AGAIN:
803
464
        break;
804
465
      case GNUTLS_E_REHANDSHAKE:
805
 
        do {
806
 
          ret = gnutls_handshake(session);
807
 
          
808
 
          if(quit_now){
809
 
            errno = EINTR;
810
 
            goto mandos_end;
811
 
          }
812
 
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
813
 
        if(ret < 0){
814
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
815
 
          gnutls_perror(ret);
816
 
          errno = EPROTO;
817
 
          goto mandos_end;
 
466
        ret = gnutls_handshake (es.session);
 
467
        if (ret < 0){
 
468
          fprintf(stderr, "\n*** Handshake failed ***\n");
 
469
          gnutls_perror (ret);
 
470
          retval = -1;
 
471
          goto exit;
818
472
        }
819
473
        break;
820
474
      default:
821
475
        fprintf(stderr, "Unknown error while reading data from"
822
 
                " encrypted session with Mandos server\n");
823
 
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
824
 
        errno = EIO;
825
 
        goto mandos_end;
 
476
                " encrypted session with mandos server\n");
 
477
        retval = -1;
 
478
        gnutls_bye (es.session, GNUTLS_SHUT_RDWR);
 
479
        goto exit;
826
480
      }
827
481
    } else {
828
 
      buffer_length += (size_t) sret;
829
 
    }
830
 
  }
831
 
  
832
 
  if(debug){
833
 
    fprintf(stderr, "Closing TLS session\n");
834
 
  }
835
 
  
836
 
  if(quit_now){
837
 
    errno = EINTR;
838
 
    goto mandos_end;
839
 
  }
840
 
  
841
 
  do {
842
 
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
843
 
    if(quit_now){
844
 
      errno = EINTR;
845
 
      goto mandos_end;
846
 
    }
847
 
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
848
 
  
849
 
  if(buffer_length > 0){
850
 
    ssize_t decrypted_buffer_size;
 
482
      buffer_length += (size_t) ret;
 
483
    }
 
484
  }
 
485
  
 
486
  if (buffer_length > 0){
851
487
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
852
488
                                               buffer_length,
853
 
                                               &decrypted_buffer);
854
 
    if(decrypted_buffer_size >= 0){
855
 
      
856
 
      written = 0;
 
489
                                               &decrypted_buffer,
 
490
                                               CERT_ROOT);
 
491
    if (decrypted_buffer_size >= 0){
857
492
      while(written < (size_t) decrypted_buffer_size){
858
 
        if(quit_now){
859
 
          errno = EINTR;
860
 
          goto mandos_end;
861
 
        }
862
 
        
863
 
        ret = (int)fwrite(decrypted_buffer + written, 1,
864
 
                          (size_t)decrypted_buffer_size - written,
865
 
                          stdout);
 
493
        ret = (int)fwrite (decrypted_buffer + written, 1,
 
494
                           (size_t)decrypted_buffer_size - written,
 
495
                           stdout);
866
496
        if(ret == 0 and ferror(stdout)){
867
 
          int e = errno;
868
497
          if(debug){
869
498
            fprintf(stderr, "Error writing encrypted data: %s\n",
870
499
                    strerror(errno));
871
500
          }
872
 
          errno = e;
873
 
          goto mandos_end;
 
501
          retval = -1;
 
502
          break;
874
503
        }
875
504
        written += (size_t)ret;
876
505
      }
877
 
      retval = 0;
878
 
    }
879
 
  }
880
 
  
881
 
  /* Shutdown procedure */
882
 
  
883
 
 mandos_end:
884
 
  {
885
 
    int e = errno;
886
 
    free(decrypted_buffer);
887
 
    free(buffer);
888
 
    if(tcp_sd >= 0){
889
 
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
890
 
    }
891
 
    if(ret == -1){
892
 
      if(e == 0){
893
 
        e = errno;
894
 
      }
895
 
      perror("close");
896
 
    }
897
 
    gnutls_deinit(session);
898
 
    if(quit_now){
899
 
      e = EINTR;
 
506
      free(decrypted_buffer);
 
507
    } else {
900
508
      retval = -1;
901
509
    }
902
 
    errno = e;
903
 
  }
 
510
  }
 
511
 
 
512
  //shutdown procedure
 
513
 
 
514
  if(debug){
 
515
    fprintf(stderr, "Closing TLS session\n");
 
516
  }
 
517
 
 
518
  free(buffer);
 
519
  gnutls_bye (es.session, GNUTLS_SHUT_RDWR);
 
520
 exit:
 
521
  close(tcp_sd);
 
522
  gnutls_deinit (es.session);
 
523
  gnutls_certificate_free_credentials (es.cred);
 
524
  gnutls_global_deinit ();
904
525
  return retval;
905
526
}
906
527
 
907
 
static void resolve_callback(AvahiSServiceResolver *r,
908
 
                             AvahiIfIndex interface,
909
 
                             AvahiProtocol proto,
910
 
                             AvahiResolverEvent event,
911
 
                             const char *name,
912
 
                             const char *type,
913
 
                             const char *domain,
914
 
                             const char *host_name,
915
 
                             const AvahiAddress *address,
916
 
                             uint16_t port,
917
 
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
918
 
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
919
 
                             flags,
920
 
                             AVAHI_GCC_UNUSED void* userdata){
921
 
  assert(r);
 
528
static AvahiSimplePoll *simple_poll = NULL;
 
529
static AvahiServer *server = NULL;
 
530
 
 
531
static void resolve_callback(
 
532
    AvahiSServiceResolver *r,
 
533
    AvahiIfIndex interface,
 
534
    AVAHI_GCC_UNUSED AvahiProtocol protocol,
 
535
    AvahiResolverEvent event,
 
536
    const char *name,
 
537
    const char *type,
 
538
    const char *domain,
 
539
    const char *host_name,
 
540
    const AvahiAddress *address,
 
541
    uint16_t port,
 
542
    AVAHI_GCC_UNUSED AvahiStringList *txt,
 
543
    AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
 
544
    AVAHI_GCC_UNUSED void* userdata) {
 
545
    
 
546
  assert(r);                    /* Spurious warning */
922
547
  
923
548
  /* Called whenever a service has been resolved successfully or
924
549
     timed out */
925
550
  
926
 
  if(quit_now){
927
 
    return;
928
 
  }
929
 
  
930
 
  switch(event){
 
551
  switch (event) {
931
552
  default:
932
553
  case AVAHI_RESOLVER_FAILURE:
933
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
934
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
935
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
554
    fprintf(stderr, "(Resolver) Failed to resolve service '%s' of"
 
555
            " type '%s' in domain '%s': %s\n", name, type, domain,
 
556
            avahi_strerror(avahi_server_errno(server)));
936
557
    break;
937
558
    
938
559
  case AVAHI_RESOLVER_FOUND:
940
561
      char ip[AVAHI_ADDRESS_STR_MAX];
941
562
      avahi_address_snprint(ip, sizeof(ip), address);
942
563
      if(debug){
943
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
944
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
945
 
                ip, (intmax_t)interface, port);
 
564
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s) on"
 
565
                " port %d\n", name, host_name, ip, port);
946
566
      }
947
 
      int ret = start_mandos_communication(ip, port, interface,
948
 
                                           avahi_proto_to_af(proto));
949
 
      if(ret == 0){
950
 
        avahi_simple_poll_quit(mc.simple_poll);
 
567
      int ret = start_mandos_communication(ip, port, interface);
 
568
      if (ret == 0){
 
569
        exit(EXIT_SUCCESS);
951
570
      }
952
571
    }
953
572
  }
954
573
  avahi_s_service_resolver_free(r);
955
574
}
956
575
 
957
 
static void browse_callback(AvahiSServiceBrowser *b,
958
 
                            AvahiIfIndex interface,
959
 
                            AvahiProtocol protocol,
960
 
                            AvahiBrowserEvent event,
961
 
                            const char *name,
962
 
                            const char *type,
963
 
                            const char *domain,
964
 
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
965
 
                            flags,
966
 
                            AVAHI_GCC_UNUSED void* userdata){
967
 
  assert(b);
968
 
  
969
 
  /* Called whenever a new services becomes available on the LAN or
970
 
     is removed from the LAN */
971
 
  
972
 
  if(quit_now){
973
 
    return;
974
 
  }
975
 
  
976
 
  switch(event){
977
 
  default:
978
 
  case AVAHI_BROWSER_FAILURE:
979
 
    
980
 
    fprintf(stderr, "(Avahi browser) %s\n",
981
 
            avahi_strerror(avahi_server_errno(mc.server)));
982
 
    avahi_simple_poll_quit(mc.simple_poll);
983
 
    return;
984
 
    
985
 
  case AVAHI_BROWSER_NEW:
986
 
    /* We ignore the returned Avahi resolver object. In the callback
987
 
       function we free it. If the Avahi server is terminated before
988
 
       the callback function is called the Avahi server will free the
989
 
       resolver for us. */
990
 
    
991
 
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
992
 
                                    name, type, domain, protocol, 0,
993
 
                                    resolve_callback, NULL) == NULL)
994
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
995
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
996
 
    break;
997
 
    
998
 
  case AVAHI_BROWSER_REMOVE:
999
 
    break;
1000
 
    
1001
 
  case AVAHI_BROWSER_ALL_FOR_NOW:
1002
 
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1003
 
    if(debug){
1004
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
1005
 
    }
1006
 
    break;
1007
 
  }
1008
 
}
1009
 
 
1010
 
/* stop main loop after sigterm has been called */
1011
 
static void handle_sigterm(int sig){
1012
 
  if(quit_now){
1013
 
    return;
1014
 
  }
1015
 
  quit_now = 1;
1016
 
  signal_received = sig;
1017
 
  int old_errno = errno;
1018
 
  if(mc.simple_poll != NULL){
1019
 
    avahi_simple_poll_quit(mc.simple_poll);
1020
 
  }
1021
 
  errno = old_errno;
1022
 
}
1023
 
 
1024
 
/* 
1025
 
 * This function determines if a directory entry in /sys/class/net
1026
 
 * corresponds to an acceptable network device.
1027
 
 * (This function is passed to scandir(3) as a filter function.)
1028
 
 */
1029
 
int good_interface(const struct dirent *if_entry){
1030
 
  ssize_t ssret;
1031
 
  char *flagname = NULL;
1032
 
  if(if_entry->d_name[0] == '.'){
1033
 
    return 0;
1034
 
  }
1035
 
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
1036
 
                     if_entry->d_name);
1037
 
  if(ret < 0){
1038
 
    perror("asprintf");
1039
 
    return 0;
1040
 
  }
1041
 
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
1042
 
  if(flags_fd == -1){
1043
 
    perror("open");
1044
 
    free(flagname);
1045
 
    return 0;
1046
 
  }
1047
 
  free(flagname);
1048
 
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
1049
 
  /* read line from flags_fd */
1050
 
  ssize_t to_read = 2+(sizeof(ifreq_flags)*2)+1; /* "0x1003\n" */
1051
 
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
1052
 
  flagstring[(size_t)to_read] = '\0';
1053
 
  if(flagstring == NULL){
1054
 
    perror("malloc");
1055
 
    close(flags_fd);
1056
 
    return 0;
1057
 
  }
1058
 
  while(to_read > 0){
1059
 
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
1060
 
                                             (size_t)to_read));
1061
 
    if(ssret == -1){
1062
 
      perror("read");
1063
 
      free(flagstring);
1064
 
      close(flags_fd);
1065
 
      return 0;
1066
 
    }
1067
 
    to_read -= ssret;
1068
 
    if(ssret == 0){
1069
 
      break;
1070
 
    }
1071
 
  }
1072
 
  close(flags_fd);
1073
 
  intmax_t tmpmax;
1074
 
  char *tmp;
1075
 
  errno = 0;
1076
 
  tmpmax = strtoimax(flagstring, &tmp, 0);
1077
 
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
1078
 
                                         and not (isspace(*tmp)))
1079
 
     or tmpmax != (ifreq_flags)tmpmax){
1080
 
    if(debug){
1081
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1082
 
              flagstring, if_entry->d_name);
1083
 
    }
1084
 
    free(flagstring);
1085
 
    return 0;
1086
 
  }
1087
 
  free(flagstring);
1088
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
1089
 
  /* Reject the loopback device */
1090
 
  if(flags & IFF_LOOPBACK){
1091
 
    if(debug){
1092
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1093
 
              if_entry->d_name);
1094
 
    }
1095
 
    return 0;
1096
 
  }
1097
 
  /* Accept point-to-point devices only if connect_to is specified */
1098
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1099
 
    if(debug){
1100
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1101
 
              if_entry->d_name);
1102
 
    }
1103
 
    return 1;
1104
 
  }
1105
 
  /* Otherwise, reject non-broadcast-capable devices */
1106
 
  if(not (flags & IFF_BROADCAST)){
1107
 
    if(debug){
1108
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1109
 
              if_entry->d_name);
1110
 
    }
1111
 
    return 0;
1112
 
  }
1113
 
  /* Reject non-ARP interfaces (including dummy interfaces) */
1114
 
  if(flags & IFF_NOARP){
1115
 
    if(debug){
1116
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
1117
 
              if_entry->d_name);
1118
 
    }
1119
 
    return 0;
1120
 
  }
1121
 
  /* Accept this device */
1122
 
  if(debug){
1123
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1124
 
            if_entry->d_name);
1125
 
  }
1126
 
  return 1;
1127
 
}
1128
 
 
1129
 
int main(int argc, char *argv[]){
1130
 
  AvahiSServiceBrowser *sb = NULL;
1131
 
  int error;
1132
 
  int ret;
1133
 
  intmax_t tmpmax;
1134
 
  char *tmp;
1135
 
  int exitcode = EXIT_SUCCESS;
1136
 
  const char *interface = "";
1137
 
  struct ifreq network;
1138
 
  int sd = -1;
1139
 
  bool take_down_interface = false;
1140
 
  uid_t uid;
1141
 
  gid_t gid;
1142
 
  char tempdir[] = "/tmp/mandosXXXXXX";
1143
 
  bool tempdir_created = false;
1144
 
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1145
 
  const char *seckey = PATHDIR "/" SECKEY;
1146
 
  const char *pubkey = PATHDIR "/" PUBKEY;
1147
 
  
1148
 
  bool gnutls_initialized = false;
1149
 
  bool gpgme_initialized = false;
1150
 
  float delay = 2.5f;
1151
 
  
1152
 
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1153
 
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1154
 
  
1155
 
  uid = getuid();
1156
 
  gid = getgid();
1157
 
  
1158
 
  /* Lower any group privileges we might have, just to be safe */
1159
 
  errno = 0;
1160
 
  ret = setgid(gid);
1161
 
  if(ret == -1){
1162
 
    perror("setgid");
1163
 
  }
1164
 
  
1165
 
  /* Lower user privileges (temporarily) */
1166
 
  errno = 0;
1167
 
  ret = seteuid(uid);
1168
 
  if(ret == -1){
1169
 
    perror("seteuid");
1170
 
  }
1171
 
  
1172
 
  if(quit_now){
1173
 
    goto end;
1174
 
  }
1175
 
  
1176
 
  {
1177
 
    struct argp_option options[] = {
1178
 
      { .name = "debug", .key = 128,
1179
 
        .doc = "Debug mode", .group = 3 },
1180
 
      { .name = "connect", .key = 'c',
1181
 
        .arg = "ADDRESS:PORT",
1182
 
        .doc = "Connect directly to a specific Mandos server",
1183
 
        .group = 1 },
1184
 
      { .name = "interface", .key = 'i',
1185
 
        .arg = "NAME",
1186
 
        .doc = "Network interface that will be used to search for"
1187
 
        " Mandos servers",
1188
 
        .group = 1 },
1189
 
      { .name = "seckey", .key = 's',
1190
 
        .arg = "FILE",
1191
 
        .doc = "OpenPGP secret key file base name",
1192
 
        .group = 1 },
1193
 
      { .name = "pubkey", .key = 'p',
1194
 
        .arg = "FILE",
1195
 
        .doc = "OpenPGP public key file base name",
1196
 
        .group = 2 },
1197
 
      { .name = "dh-bits", .key = 129,
1198
 
        .arg = "BITS",
1199
 
        .doc = "Bit length of the prime number used in the"
1200
 
        " Diffie-Hellman key exchange",
1201
 
        .group = 2 },
1202
 
      { .name = "priority", .key = 130,
1203
 
        .arg = "STRING",
1204
 
        .doc = "GnuTLS priority string for the TLS handshake",
1205
 
        .group = 1 },
1206
 
      { .name = "delay", .key = 131,
1207
 
        .arg = "SECONDS",
1208
 
        .doc = "Maximum delay to wait for interface startup",
1209
 
        .group = 2 },
1210
 
      /*
1211
 
       * These reproduce what we would get without ARGP_NO_HELP
1212
 
       */
1213
 
      { .name = "help", .key = '?',
1214
 
        .doc = "Give this help list", .group = -1 },
1215
 
      { .name = "usage", .key = -3,
1216
 
        .doc = "Give a short usage message", .group = -1 },
1217
 
      { .name = "version", .key = 'V',
1218
 
        .doc = "Print program version", .group = -1 },
1219
 
      { .name = NULL }
1220
 
    };
1221
 
    
1222
 
    error_t parse_opt(int key, char *arg,
1223
 
                      struct argp_state *state){
1224
 
      errno = 0;
1225
 
      switch(key){
1226
 
      case 128:                 /* --debug */
1227
 
        debug = true;
1228
 
        break;
1229
 
      case 'c':                 /* --connect */
1230
 
        connect_to = arg;
1231
 
        break;
1232
 
      case 'i':                 /* --interface */
1233
 
        interface = arg;
1234
 
        break;
1235
 
      case 's':                 /* --seckey */
1236
 
        seckey = arg;
1237
 
        break;
1238
 
      case 'p':                 /* --pubkey */
1239
 
        pubkey = arg;
1240
 
        break;
1241
 
      case 129:                 /* --dh-bits */
1242
 
        errno = 0;
1243
 
        tmpmax = strtoimax(arg, &tmp, 10);
1244
 
        if(errno != 0 or tmp == arg or *tmp != '\0'
1245
 
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
1246
 
          argp_error(state, "Bad number of DH bits");
1247
 
        }
1248
 
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1249
 
        break;
1250
 
      case 130:                 /* --priority */
1251
 
        mc.priority = arg;
1252
 
        break;
1253
 
      case 131:                 /* --delay */
1254
 
        errno = 0;
1255
 
        delay = strtof(arg, &tmp);
1256
 
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1257
 
          argp_error(state, "Bad delay");
1258
 
        }
1259
 
        break;
1260
 
        /*
1261
 
         * These reproduce what we would get without ARGP_NO_HELP
1262
 
         */
1263
 
      case '?':                 /* --help */
1264
 
        argp_state_help(state, state->out_stream,
1265
 
                        (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
1266
 
                        & ~(unsigned int)ARGP_HELP_EXIT_OK);
1267
 
      case -3:                  /* --usage */
1268
 
        argp_state_help(state, state->out_stream,
1269
 
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1270
 
      case 'V':                 /* --version */
1271
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
1272
 
        exit(argp_err_exit_status);
1273
 
        break;
1274
 
      default:
1275
 
        return ARGP_ERR_UNKNOWN;
1276
 
      }
1277
 
      return errno;
1278
 
    }
1279
 
    
1280
 
    struct argp argp = { .options = options, .parser = parse_opt,
1281
 
                         .args_doc = "",
1282
 
                         .doc = "Mandos client -- Get and decrypt"
1283
 
                         " passwords from a Mandos server" };
1284
 
    ret = argp_parse(&argp, argc, argv,
1285
 
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
1286
 
    switch(ret){
1287
 
    case 0:
1288
 
      break;
1289
 
    case ENOMEM:
 
576
static void browse_callback(
 
577
    AvahiSServiceBrowser *b,
 
578
    AvahiIfIndex interface,
 
579
    AvahiProtocol protocol,
 
580
    AvahiBrowserEvent event,
 
581
    const char *name,
 
582
    const char *type,
 
583
    const char *domain,
 
584
    AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
 
585
    void* userdata) {
 
586
    
 
587
    AvahiServer *s = userdata;
 
588
    assert(b);                  /* Spurious warning */
 
589
    
 
590
    /* Called whenever a new services becomes available on the LAN or
 
591
       is removed from the LAN */
 
592
    
 
593
    switch (event) {
1290
594
    default:
1291
 
      errno = ret;
1292
 
      perror("argp_parse");
1293
 
      exitcode = EX_OSERR;
1294
 
      goto end;
1295
 
    case EINVAL:
1296
 
      exitcode = EX_USAGE;
1297
 
      goto end;
1298
 
    }
1299
 
  }
1300
 
  
1301
 
  if(not debug){
1302
 
    avahi_set_log_function(empty_log);
1303
 
  }
1304
 
 
1305
 
  if(interface[0] == '\0'){
1306
 
    struct dirent **direntries;
1307
 
    ret = scandir(sys_class_net, &direntries, good_interface,
1308
 
                  alphasort);
1309
 
    if(ret >= 1){
1310
 
      /* Pick the first good interface */
1311
 
      interface = strdup(direntries[0]->d_name);
1312
 
      if(debug){
1313
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1314
 
      }
1315
 
      if(interface == NULL){
1316
 
        perror("malloc");
1317
 
        free(direntries);
1318
 
        exitcode = EXIT_FAILURE;
1319
 
        goto end;
1320
 
      }
1321
 
      free(direntries);
1322
 
    } else {
1323
 
      free(direntries);
1324
 
      fprintf(stderr, "Could not find a network interface\n");
1325
 
      exitcode = EXIT_FAILURE;
1326
 
      goto end;
1327
 
    }
1328
 
  }
1329
 
  
1330
 
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1331
 
     from the signal handler */
1332
 
  /* Initialize the pseudo-RNG for Avahi */
1333
 
  srand((unsigned int) time(NULL));
1334
 
  mc.simple_poll = avahi_simple_poll_new();
1335
 
  if(mc.simple_poll == NULL){
1336
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1337
 
    exitcode = EX_UNAVAILABLE;
1338
 
    goto end;
1339
 
  }
1340
 
  
1341
 
  sigemptyset(&sigterm_action.sa_mask);
1342
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1343
 
  if(ret == -1){
1344
 
    perror("sigaddset");
1345
 
    exitcode = EX_OSERR;
1346
 
    goto end;
1347
 
  }
1348
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1349
 
  if(ret == -1){
1350
 
    perror("sigaddset");
1351
 
    exitcode = EX_OSERR;
1352
 
    goto end;
1353
 
  }
1354
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1355
 
  if(ret == -1){
1356
 
    perror("sigaddset");
1357
 
    exitcode = EX_OSERR;
1358
 
    goto end;
1359
 
  }
1360
 
  /* Need to check if the handler is SIG_IGN before handling:
1361
 
     | [[info:libc:Initial Signal Actions]] |
1362
 
     | [[info:libc:Basic Signal Handling]]  |
1363
 
  */
1364
 
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1365
 
  if(ret == -1){
1366
 
    perror("sigaction");
1367
 
    return EX_OSERR;
1368
 
  }
1369
 
  if(old_sigterm_action.sa_handler != SIG_IGN){
1370
 
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1371
 
    if(ret == -1){
1372
 
      perror("sigaction");
1373
 
      exitcode = EX_OSERR;
1374
 
      goto end;
1375
 
    }
1376
 
  }
1377
 
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1378
 
  if(ret == -1){
1379
 
    perror("sigaction");
1380
 
    return EX_OSERR;
1381
 
  }
1382
 
  if(old_sigterm_action.sa_handler != SIG_IGN){
1383
 
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1384
 
    if(ret == -1){
1385
 
      perror("sigaction");
1386
 
      exitcode = EX_OSERR;
1387
 
      goto end;
1388
 
    }
1389
 
  }
1390
 
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1391
 
  if(ret == -1){
1392
 
    perror("sigaction");
1393
 
    return EX_OSERR;
1394
 
  }
1395
 
  if(old_sigterm_action.sa_handler != SIG_IGN){
1396
 
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1397
 
    if(ret == -1){
1398
 
      perror("sigaction");
1399
 
      exitcode = EX_OSERR;
1400
 
      goto end;
1401
 
    }
1402
 
  }
1403
 
  
1404
 
  /* If the interface is down, bring it up */
1405
 
  if(strcmp(interface, "none") != 0){
1406
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1407
 
    if(if_index == 0){
1408
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1409
 
      exitcode = EX_UNAVAILABLE;
1410
 
      goto end;
1411
 
    }
1412
 
    
1413
 
    if(quit_now){
1414
 
      goto end;
1415
 
    }
1416
 
    
1417
 
    /* Re-raise priviliges */
1418
 
    errno = 0;
1419
 
    ret = seteuid(0);
1420
 
    if(ret == -1){
1421
 
      perror("seteuid");
1422
 
    }
1423
 
    
1424
 
#ifdef __linux__
1425
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1426
 
       messages about the network interface to mess up the prompt */
1427
 
    ret = klogctl(8, NULL, 5);
1428
 
    bool restore_loglevel = true;
1429
 
    if(ret == -1){
1430
 
      restore_loglevel = false;
1431
 
      perror("klogctl");
1432
 
    }
1433
 
#endif  /* __linux__ */
1434
 
    
1435
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1436
 
    if(sd < 0){
1437
 
      perror("socket");
1438
 
      exitcode = EX_OSERR;
1439
 
#ifdef __linux__
1440
 
      if(restore_loglevel){
1441
 
        ret = klogctl(7, NULL, 0);
1442
 
        if(ret == -1){
1443
 
          perror("klogctl");
1444
 
        }
1445
 
      }
1446
 
#endif  /* __linux__ */
1447
 
      /* Lower privileges */
1448
 
      errno = 0;
1449
 
      ret = seteuid(uid);
1450
 
      if(ret == -1){
1451
 
        perror("seteuid");
1452
 
      }
1453
 
      goto end;
1454
 
    }
1455
 
    strcpy(network.ifr_name, interface);
1456
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1457
 
    if(ret == -1){
1458
 
      perror("ioctl SIOCGIFFLAGS");
1459
 
#ifdef __linux__
1460
 
      if(restore_loglevel){
1461
 
        ret = klogctl(7, NULL, 0);
1462
 
        if(ret == -1){
1463
 
          perror("klogctl");
1464
 
        }
1465
 
      }
1466
 
#endif  /* __linux__ */
1467
 
      exitcode = EX_OSERR;
1468
 
      /* Lower privileges */
1469
 
      errno = 0;
1470
 
      ret = seteuid(uid);
1471
 
      if(ret == -1){
1472
 
        perror("seteuid");
1473
 
      }
1474
 
      goto end;
1475
 
    }
1476
 
    if((network.ifr_flags & IFF_UP) == 0){
1477
 
      network.ifr_flags |= IFF_UP;
1478
 
      take_down_interface = true;
1479
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1480
 
      if(ret == -1){
1481
 
        take_down_interface = false;
1482
 
        perror("ioctl SIOCSIFFLAGS +IFF_UP");
1483
 
        exitcode = EX_OSERR;
1484
 
#ifdef __linux__
1485
 
        if(restore_loglevel){
1486
 
          ret = klogctl(7, NULL, 0);
1487
 
          if(ret == -1){
1488
 
            perror("klogctl");
1489
 
          }
1490
 
        }
1491
 
#endif  /* __linux__ */
1492
 
        /* Lower privileges */
1493
 
        errno = 0;
1494
 
        ret = seteuid(uid);
1495
 
        if(ret == -1){
1496
 
          perror("seteuid");
1497
 
        }
1498
 
        goto end;
1499
 
      }
1500
 
    }
1501
 
    /* sleep checking until interface is running */
1502
 
    for(int i=0; i < delay * 4; i++){
1503
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1504
 
      if(ret == -1){
1505
 
        perror("ioctl SIOCGIFFLAGS");
1506
 
      } else if(network.ifr_flags & IFF_RUNNING){
1507
 
        break;
1508
 
      }
1509
 
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1510
 
      ret = nanosleep(&sleeptime, NULL);
1511
 
      if(ret == -1 and errno != EINTR){
1512
 
        perror("nanosleep");
1513
 
      }
1514
 
    }
1515
 
    if(not take_down_interface){
1516
 
      /* We won't need the socket anymore */
1517
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1518
 
      if(ret == -1){
1519
 
        perror("close");
1520
 
      }
1521
 
    }
1522
 
#ifdef __linux__
1523
 
    if(restore_loglevel){
1524
 
      /* Restores kernel loglevel to default */
1525
 
      ret = klogctl(7, NULL, 0);
1526
 
      if(ret == -1){
1527
 
        perror("klogctl");
1528
 
      }
1529
 
    }
1530
 
#endif  /* __linux__ */
1531
 
    /* Lower privileges */
1532
 
    errno = 0;
1533
 
    if(take_down_interface){
1534
 
      /* Lower privileges */
1535
 
      ret = seteuid(uid);
1536
 
      if(ret == -1){
1537
 
        perror("seteuid");
1538
 
      }
1539
 
    } else {
1540
 
      /* Lower privileges permanently */
1541
 
      ret = setuid(uid);
1542
 
      if(ret == -1){
1543
 
        perror("setuid");
1544
 
      }
1545
 
    }
1546
 
  }
1547
 
  
1548
 
  if(quit_now){
1549
 
    goto end;
1550
 
  }
1551
 
  
1552
 
  ret = init_gnutls_global(pubkey, seckey);
1553
 
  if(ret == -1){
1554
 
    fprintf(stderr, "init_gnutls_global failed\n");
1555
 
    exitcode = EX_UNAVAILABLE;
1556
 
    goto end;
1557
 
  } else {
1558
 
    gnutls_initialized = true;
1559
 
  }
1560
 
  
1561
 
  if(quit_now){
1562
 
    goto end;
1563
 
  }
1564
 
  
1565
 
  tempdir_created = true;
1566
 
  if(mkdtemp(tempdir) == NULL){
1567
 
    tempdir_created = false;
1568
 
    perror("mkdtemp");
1569
 
    goto end;
1570
 
  }
1571
 
  
1572
 
  if(quit_now){
1573
 
    goto end;
1574
 
  }
1575
 
  
1576
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
1577
 
    fprintf(stderr, "init_gpgme failed\n");
1578
 
    exitcode = EX_UNAVAILABLE;
1579
 
    goto end;
1580
 
  } else {
1581
 
    gpgme_initialized = true;
1582
 
  }
1583
 
  
1584
 
  if(quit_now){
1585
 
    goto end;
1586
 
  }
1587
 
  
1588
 
  if(connect_to != NULL){
1589
 
    /* Connect directly, do not use Zeroconf */
1590
 
    /* (Mainly meant for debugging) */
1591
 
    char *address = strrchr(connect_to, ':');
1592
 
    if(address == NULL){
1593
 
      fprintf(stderr, "No colon in address\n");
1594
 
      exitcode = EX_USAGE;
1595
 
      goto end;
1596
 
    }
1597
 
    
1598
 
    if(quit_now){
1599
 
      goto end;
1600
 
    }
1601
 
    
1602
 
    uint16_t port;
1603
 
    errno = 0;
1604
 
    tmpmax = strtoimax(address+1, &tmp, 10);
1605
 
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1606
 
       or tmpmax != (uint16_t)tmpmax){
1607
 
      fprintf(stderr, "Bad port number\n");
1608
 
      exitcode = EX_USAGE;
1609
 
      goto end;
1610
 
    }
1611
 
  
1612
 
    if(quit_now){
1613
 
      goto end;
1614
 
    }
1615
 
    
1616
 
    port = (uint16_t)tmpmax;
1617
 
    *address = '\0';
1618
 
    address = connect_to;
1619
 
    /* Colon in address indicates IPv6 */
1620
 
    int af;
1621
 
    if(strchr(address, ':') != NULL){
1622
 
      af = AF_INET6;
1623
 
    } else {
1624
 
      af = AF_INET;
1625
 
    }
1626
 
    
1627
 
    if(quit_now){
1628
 
      goto end;
1629
 
    }
1630
 
 
1631
 
    while(not quit_now){
1632
 
      ret = start_mandos_communication(address, port, if_index, af);
1633
 
      if(quit_now or ret == 0){
1634
 
        break;
1635
 
      }
1636
 
      sleep(15);
1637
 
    };
1638
 
 
1639
 
    if (not quit_now){
1640
 
      exitcode = EXIT_SUCCESS;
1641
 
    }
1642
 
 
1643
 
    goto end;
1644
 
  }
1645
 
  
1646
 
  if(quit_now){
1647
 
    goto end;
1648
 
  }
1649
 
  
1650
 
  {
 
595
    case AVAHI_BROWSER_FAILURE:
 
596
      
 
597
      fprintf(stderr, "(Browser) %s\n",
 
598
              avahi_strerror(avahi_server_errno(server)));
 
599
      avahi_simple_poll_quit(simple_poll);
 
600
      return;
 
601
      
 
602
    case AVAHI_BROWSER_NEW:
 
603
      /* We ignore the returned resolver object. In the callback
 
604
         function we free it. If the server is terminated before
 
605
         the callback function is called the server will free
 
606
         the resolver for us. */
 
607
      
 
608
      if (!(avahi_s_service_resolver_new(s, interface, protocol, name,
 
609
                                         type, domain,
 
610
                                         AVAHI_PROTO_INET6, 0,
 
611
                                         resolve_callback, s)))
 
612
        fprintf(stderr, "Failed to resolve service '%s': %s\n", name,
 
613
                avahi_strerror(avahi_server_errno(s)));
 
614
      break;
 
615
      
 
616
    case AVAHI_BROWSER_REMOVE:
 
617
      break;
 
618
      
 
619
    case AVAHI_BROWSER_ALL_FOR_NOW:
 
620
    case AVAHI_BROWSER_CACHE_EXHAUSTED:
 
621
      break;
 
622
    }
 
623
}
 
624
 
 
625
int main(AVAHI_GCC_UNUSED int argc, AVAHI_GCC_UNUSED char*argv[]) {
1651
626
    AvahiServerConfig config;
1652
 
    /* Do not publish any local Zeroconf records */
 
627
    AvahiSServiceBrowser *sb = NULL;
 
628
    int error;
 
629
    int ret;
 
630
    int returncode = EXIT_SUCCESS;
 
631
    const char *interface = NULL;
 
632
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
 
633
    char *connect_to = NULL;
 
634
    
 
635
    while (true){
 
636
      static struct option long_options[] = {
 
637
        {"debug", no_argument, (int *)&debug, 1},
 
638
        {"connect", required_argument, 0, 'c'},
 
639
        {"interface", required_argument, 0, 'i'},
 
640
        {0, 0, 0, 0} };
 
641
      
 
642
      int option_index = 0;
 
643
      ret = getopt_long (argc, argv, "i:", long_options,
 
644
                         &option_index);
 
645
      
 
646
      if (ret == -1){
 
647
        break;
 
648
      }
 
649
      
 
650
      switch(ret){
 
651
      case 0:
 
652
        break;
 
653
      case 'i':
 
654
        interface = optarg;
 
655
        break;
 
656
      case 'c':
 
657
        connect_to = optarg;
 
658
        break;
 
659
      default:
 
660
        exit(EXIT_FAILURE);
 
661
      }
 
662
    }
 
663
    
 
664
    if(interface != NULL){
 
665
      if_index = (AvahiIfIndex) if_nametoindex(interface);
 
666
      if(if_index == 0){
 
667
        fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
668
        exit(EXIT_FAILURE);
 
669
      }
 
670
    }
 
671
    
 
672
    if(connect_to != NULL){
 
673
      /* Connect directly, do not use Zeroconf */
 
674
      /* (Mainly meant for debugging) */
 
675
      char *address = strrchr(connect_to, ':');
 
676
      if(address == NULL){
 
677
        fprintf(stderr, "No colon in address\n");
 
678
        exit(EXIT_FAILURE);
 
679
      }
 
680
      errno = 0;
 
681
      uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
 
682
      if(errno){
 
683
        perror("Bad port number");
 
684
        exit(EXIT_FAILURE);
 
685
      }
 
686
      *address = '\0';
 
687
      address = connect_to;
 
688
      ret = start_mandos_communication(address, port, if_index);
 
689
      if(ret < 0){
 
690
        exit(EXIT_FAILURE);
 
691
      } else {
 
692
        exit(EXIT_SUCCESS);
 
693
      }
 
694
    }
 
695
    
 
696
    if (not debug){
 
697
      avahi_set_log_function(empty_log);
 
698
    }
 
699
    
 
700
    /* Initialize the psuedo-RNG */
 
701
    srand((unsigned int) time(NULL));
 
702
 
 
703
    /* Allocate main loop object */
 
704
    if (!(simple_poll = avahi_simple_poll_new())) {
 
705
        fprintf(stderr, "Failed to create simple poll object.\n");
 
706
        
 
707
        goto exit;
 
708
    }
 
709
 
 
710
    /* Do not publish any local records */
1653
711
    avahi_server_config_init(&config);
1654
712
    config.publish_hinfo = 0;
1655
713
    config.publish_addresses = 0;
1656
714
    config.publish_workstation = 0;
1657
715
    config.publish_domain = 0;
1658
 
    
 
716
 
1659
717
    /* Allocate a new server */
1660
 
    mc.server = avahi_server_new(avahi_simple_poll_get
1661
 
                                 (mc.simple_poll), &config, NULL,
1662
 
                                 NULL, &error);
1663
 
    
1664
 
    /* Free the Avahi configuration data */
 
718
    server = avahi_server_new(avahi_simple_poll_get(simple_poll),
 
719
                              &config, NULL, NULL, &error);
 
720
 
 
721
    /* Free the configuration data */
1665
722
    avahi_server_config_free(&config);
1666
 
  }
1667
 
  
1668
 
  /* Check if creating the Avahi server object succeeded */
1669
 
  if(mc.server == NULL){
1670
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1671
 
            avahi_strerror(error));
1672
 
    exitcode = EX_UNAVAILABLE;
1673
 
    goto end;
1674
 
  }
1675
 
  
1676
 
  if(quit_now){
1677
 
    goto end;
1678
 
  }
1679
 
  
1680
 
  /* Create the Avahi service browser */
1681
 
  sb = avahi_s_service_browser_new(mc.server, if_index,
1682
 
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1683
 
                                   NULL, 0, browse_callback, NULL);
1684
 
  if(sb == NULL){
1685
 
    fprintf(stderr, "Failed to create service browser: %s\n",
1686
 
            avahi_strerror(avahi_server_errno(mc.server)));
1687
 
    exitcode = EX_UNAVAILABLE;
1688
 
    goto end;
1689
 
  }
1690
 
  
1691
 
  if(quit_now){
1692
 
    goto end;
1693
 
  }
1694
 
  
1695
 
  /* Run the main loop */
1696
 
  
1697
 
  if(debug){
1698
 
    fprintf(stderr, "Starting Avahi loop search\n");
1699
 
  }
1700
 
  
1701
 
  avahi_simple_poll_loop(mc.simple_poll);
1702
 
  
1703
 
 end:
1704
 
  
1705
 
  if(debug){
1706
 
    fprintf(stderr, "%s exiting\n", argv[0]);
1707
 
  }
1708
 
  
1709
 
  /* Cleanup things */
1710
 
  if(sb != NULL)
1711
 
    avahi_s_service_browser_free(sb);
1712
 
  
1713
 
  if(mc.server != NULL)
1714
 
    avahi_server_free(mc.server);
1715
 
  
1716
 
  if(mc.simple_poll != NULL)
1717
 
    avahi_simple_poll_free(mc.simple_poll);
1718
 
  
1719
 
  if(gnutls_initialized){
1720
 
    gnutls_certificate_free_credentials(mc.cred);
1721
 
    gnutls_global_deinit();
1722
 
    gnutls_dh_params_deinit(mc.dh_params);
1723
 
  }
1724
 
  
1725
 
  if(gpgme_initialized){
1726
 
    gpgme_release(mc.ctx);
1727
 
  }
1728
 
  
1729
 
  /* Take down the network interface */
1730
 
  if(take_down_interface){
1731
 
    /* Re-raise priviliges */
1732
 
    errno = 0;
1733
 
    ret = seteuid(0);
1734
 
    if(ret == -1){
1735
 
      perror("seteuid");
1736
 
    }
1737
 
    if(geteuid() == 0){
1738
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1739
 
      if(ret == -1){
1740
 
        perror("ioctl SIOCGIFFLAGS");
1741
 
      } else if(network.ifr_flags & IFF_UP) {
1742
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1743
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1744
 
        if(ret == -1){
1745
 
          perror("ioctl SIOCSIFFLAGS -IFF_UP");
1746
 
        }
1747
 
      }
1748
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1749
 
      if(ret == -1){
1750
 
        perror("close");
1751
 
      }
1752
 
      /* Lower privileges permanently */
1753
 
      errno = 0;
1754
 
      ret = setuid(uid);
1755
 
      if(ret == -1){
1756
 
        perror("setuid");
1757
 
      }
1758
 
    }
1759
 
  }
1760
 
  
1761
 
  /* Removes the temp directory used by GPGME */
1762
 
  if(tempdir_created){
1763
 
    DIR *d;
1764
 
    struct dirent *direntry;
1765
 
    d = opendir(tempdir);
1766
 
    if(d == NULL){
1767
 
      if(errno != ENOENT){
1768
 
        perror("opendir");
1769
 
      }
1770
 
    } else {
1771
 
      while(true){
1772
 
        direntry = readdir(d);
1773
 
        if(direntry == NULL){
1774
 
          break;
1775
 
        }
1776
 
        /* Skip "." and ".." */
1777
 
        if(direntry->d_name[0] == '.'
1778
 
           and (direntry->d_name[1] == '\0'
1779
 
                or (direntry->d_name[1] == '.'
1780
 
                    and direntry->d_name[2] == '\0'))){
1781
 
          continue;
1782
 
        }
1783
 
        char *fullname = NULL;
1784
 
        ret = asprintf(&fullname, "%s/%s", tempdir,
1785
 
                       direntry->d_name);
1786
 
        if(ret < 0){
1787
 
          perror("asprintf");
1788
 
          continue;
1789
 
        }
1790
 
        ret = remove(fullname);
1791
 
        if(ret == -1){
1792
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1793
 
                  strerror(errno));
1794
 
        }
1795
 
        free(fullname);
1796
 
      }
1797
 
      closedir(d);
1798
 
    }
1799
 
    ret = rmdir(tempdir);
1800
 
    if(ret == -1 and errno != ENOENT){
1801
 
      perror("rmdir");
1802
 
    }
1803
 
  }
1804
 
  
1805
 
  if(quit_now){
1806
 
    sigemptyset(&old_sigterm_action.sa_mask);
1807
 
    old_sigterm_action.sa_handler = SIG_DFL;
1808
 
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
1809
 
                                            &old_sigterm_action,
1810
 
                                            NULL));
1811
 
    if(ret == -1){
1812
 
      perror("sigaction");
1813
 
    }
1814
 
    do {
1815
 
      ret = raise(signal_received);
1816
 
    } while(ret != 0 and errno == EINTR);
1817
 
    if(ret != 0){
1818
 
      perror("raise");
1819
 
      abort();
1820
 
    }
1821
 
    TEMP_FAILURE_RETRY(pause());
1822
 
  }
1823
 
  
1824
 
  return exitcode;
 
723
 
 
724
    /* Check if creating the server object succeeded */
 
725
    if (!server) {
 
726
        fprintf(stderr, "Failed to create server: %s\n",
 
727
                avahi_strerror(error));
 
728
        returncode = EXIT_FAILURE;
 
729
        goto exit;
 
730
    }
 
731
    
 
732
    /* Create the service browser */
 
733
    sb = avahi_s_service_browser_new(server, if_index,
 
734
                                     AVAHI_PROTO_INET6,
 
735
                                     "_mandos._tcp", NULL, 0,
 
736
                                     browse_callback, server);
 
737
    if (!sb) {
 
738
        fprintf(stderr, "Failed to create service browser: %s\n",
 
739
                avahi_strerror(avahi_server_errno(server)));
 
740
        returncode = EXIT_FAILURE;
 
741
        goto exit;
 
742
    }
 
743
    
 
744
    /* Run the main loop */
 
745
 
 
746
    if (debug){
 
747
      fprintf(stderr, "Starting avahi loop search\n");
 
748
    }
 
749
    
 
750
    avahi_simple_poll_loop(simple_poll);
 
751
    
 
752
 exit:
 
753
 
 
754
    if (debug){
 
755
      fprintf(stderr, "%s exiting\n", argv[0]);
 
756
    }
 
757
    
 
758
    /* Cleanup things */
 
759
    if (sb)
 
760
        avahi_s_service_browser_free(sb);
 
761
    
 
762
    if (server)
 
763
        avahi_server_free(server);
 
764
 
 
765
    if (simple_poll)
 
766
        avahi_simple_poll_free(simple_poll);
 
767
 
 
768
    return returncode;
1825
769
}