/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release

« back to all changes in this revision

Viewing changes to plugins.d/mandos-client.c

  • Committer: Teddy Hogeborn
  • Date: 2012-06-16 23:25:46 UTC
  • mto: (301.1.1 release) (237.7.272 trunk)
  • mto: This revision was merged to the branch mainline in revision 302.
  • Revision ID: teddy@recompile.se-20120616232546-dcrkmnhd4yhq6mvd
* plugins.d/mandos-client (mandos_context): Moved to inside "main()".
                                            All users changed.
  (add_server): Take new "current_server" argument; all callers
                changed.
  (init_gpgme, pgp_packet_decrypt, init_gnutls_global,
  init_gnutls_session, start_mandos_communication,
  avahi_loop_with_timeout): Take new "mc" argument"; all callers
                            changed.
  (resolve_callback, browse_callback): Handle void pointer userdata as
                                       "mc", a pointer to
                                       mandos_context.  All callers
                                       changed.
  (main): New "mc" variable.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2014 Teddy Hogeborn
13
 
 * Copyright © 2008-2014 Björn Påhlsson
 
12
 * Copyright © 2008-2012 Teddy Hogeborn
 
13
 * Copyright © 2008-2012 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
55
55
                                   opendir(), DIR */
56
56
#include <sys/stat.h>           /* open(), S_ISREG */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
 
                                   inet_pton(), connect(),
59
 
                                   getnameinfo() */
 
58
                                   inet_pton(), connect() */
60
59
#include <fcntl.h>              /* open() */
61
60
#include <dirent.h>             /* opendir(), struct dirent, readdir()
62
61
                                 */
74
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
74
                                   getuid(), getgid(), seteuid(),
76
75
                                   setgid(), pause(), _exit() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons() */
 
76
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
78
77
#include <iso646.h>             /* not, or, and */
79
78
#include <argp.h>               /* struct argp_option, error_t, struct
80
79
                                   argp_state, struct argp,
92
91
                                   argz_delete(), argz_append(),
93
92
                                   argz_stringify(), argz_add(),
94
93
                                   argz_count() */
95
 
#include <netdb.h>              /* getnameinfo(), NI_NUMERICHOST,
96
 
                                   EAI_SYSTEM, gai_strerror() */
97
94
 
98
95
#ifdef __linux__
99
96
#include <sys/klog.h>           /* klogctl() */
164
161
  const char *priority;
165
162
  gpgme_ctx_t ctx;
166
163
  server *current_server;
167
 
  char *interfaces;
168
 
  size_t interfaces_size;
169
164
} mandos_context;
170
165
 
171
166
/* global so signal handler can reach it*/
183
178
  perror(print_text);
184
179
}
185
180
 
186
 
__attribute__((format (gnu_printf, 2, 3), nonnull))
 
181
__attribute__((format (gnu_printf, 2, 3)))
187
182
int fprintf_plus(FILE *stream, const char *format, ...){
188
183
  va_list ap;
189
184
  va_start (ap, format);
190
185
  
191
186
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
192
187
                             program_invocation_short_name));
193
 
  return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
188
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
194
189
}
195
190
 
196
191
/*
198
193
 * bytes. "buffer_capacity" is how much is currently allocated,
199
194
 * "buffer_length" is how much is already used.
200
195
 */
201
 
__attribute__((nonnull, warn_unused_result))
202
196
size_t incbuffer(char **buffer, size_t buffer_length,
203
197
                 size_t buffer_capacity){
204
198
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
205
 
    char *new_buf = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
206
 
    if(new_buf == NULL){
207
 
      int old_errno = errno;
208
 
      free(*buffer);
209
 
      errno = old_errno;
210
 
      *buffer = NULL;
 
199
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
200
    if(buffer == NULL){
211
201
      return 0;
212
202
    }
213
 
    *buffer = new_buf;
214
203
    buffer_capacity += BUFFER_SIZE;
215
204
  }
216
205
  return buffer_capacity;
217
206
}
218
207
 
219
208
/* Add server to set of servers to retry periodically */
220
 
__attribute__((nonnull, warn_unused_result))
221
209
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
222
210
                int af, server **current_server){
223
211
  int ret;
234
222
    perror_plus("strdup");
235
223
    return false;
236
224
  }
237
 
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
238
 
  if(ret == -1){
239
 
    perror_plus("clock_gettime");
240
 
    return false;
241
 
  }
242
225
  /* Special case of first server */
243
226
  if(*current_server == NULL){
244
227
    new_server->next = new_server;
245
228
    new_server->prev = new_server;
246
229
    *current_server = new_server;
 
230
  /* Place the new server last in the list */
247
231
  } else {
248
 
    /* Place the new server last in the list */
249
232
    new_server->next = *current_server;
250
233
    new_server->prev = (*current_server)->prev;
251
234
    new_server->prev->next = new_server;
252
235
    (*current_server)->prev = new_server;
253
236
  }
 
237
  ret = clock_gettime(CLOCK_MONOTONIC, &(*current_server)->last_seen);
 
238
  if(ret == -1){
 
239
    perror_plus("clock_gettime");
 
240
    return false;
 
241
  }
254
242
  return true;
255
243
}
256
244
 
257
245
/* 
258
246
 * Initialize GPGME.
259
247
 */
260
 
__attribute__((nonnull, warn_unused_result))
261
 
static bool init_gpgme(const char * const seckey,
262
 
                       const char * const pubkey,
263
 
                       const char * const tempdir,
264
 
                       mandos_context *mc){
 
248
static bool init_gpgme(const char *seckey, const char *pubkey,
 
249
                       const char *tempdir, mandos_context *mc){
265
250
  gpgme_error_t rc;
266
251
  gpgme_engine_info_t engine_info;
267
252
  
268
253
  /*
269
254
   * Helper function to insert pub and seckey to the engine keyring.
270
255
   */
271
 
  bool import_key(const char * const filename){
 
256
  bool import_key(const char *filename){
272
257
    int ret;
273
258
    int fd;
274
259
    gpgme_data_t pgp_data;
355
340
 * Decrypt OpenPGP data.
356
341
 * Returns -1 on error
357
342
 */
358
 
__attribute__((nonnull, warn_unused_result))
359
343
static ssize_t pgp_packet_decrypt(const char *cryptotext,
360
344
                                  size_t crypto_size,
361
345
                                  char **plaintext,
481
465
  return plaintext_length;
482
466
}
483
467
 
484
 
__attribute__((warn_unused_result))
485
 
static const char *safer_gnutls_strerror(int value){
 
468
static const char * safer_gnutls_strerror(int value){
486
469
  const char *ret = gnutls_strerror(value);
487
470
  if(ret == NULL)
488
471
    ret = "(unknown)";
490
473
}
491
474
 
492
475
/* GnuTLS log function callback */
493
 
__attribute__((nonnull))
494
476
static void debuggnutls(__attribute__((unused)) int level,
495
477
                        const char* string){
496
478
  fprintf_plus(stderr, "GnuTLS: %s", string);
497
479
}
498
480
 
499
 
__attribute__((nonnull, warn_unused_result))
500
481
static int init_gnutls_global(const char *pubkeyfilename,
501
482
                              const char *seckeyfilename,
502
483
                              mandos_context *mc){
576
557
  return -1;
577
558
}
578
559
 
579
 
__attribute__((nonnull, warn_unused_result))
580
560
static int init_gnutls_session(gnutls_session_t *session,
581
561
                               mandos_context *mc){
582
562
  int ret;
639
619
                      __attribute__((unused)) const char *txt){}
640
620
 
641
621
/* Called when a Mandos server is found */
642
 
__attribute__((nonnull, warn_unused_result))
643
622
static int start_mandos_communication(const char *ip, in_port_t port,
644
623
                                      AvahiIfIndex if_index,
645
624
                                      int af, mandos_context *mc){
646
625
  int ret, tcp_sd = -1;
647
626
  ssize_t sret;
648
 
  struct sockaddr_storage to;
 
627
  union {
 
628
    struct sockaddr_in in;
 
629
    struct sockaddr_in6 in6;
 
630
  } to;
649
631
  char *buffer = NULL;
650
632
  char *decrypted_buffer = NULL;
651
633
  size_t buffer_length = 0;
675
657
    return -1;
676
658
  }
677
659
  
678
 
  /* If the interface is specified and we have a list of interfaces */
679
 
  if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
680
 
    /* Check if the interface is one of the interfaces we are using */
681
 
    bool match = false;
682
 
    {
683
 
      char *interface = NULL;
684
 
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
685
 
                                 interface))){
686
 
        if(if_nametoindex(interface) == (unsigned int)if_index){
687
 
          match = true;
688
 
          break;
689
 
        }
690
 
      }
691
 
    }
692
 
    if(not match){
693
 
      /* This interface does not match any in the list, so we don't
694
 
         connect to the server */
695
 
      if(debug){
696
 
        char interface[IF_NAMESIZE];
697
 
        if(if_indextoname((unsigned int)if_index, interface) == NULL){
698
 
          perror_plus("if_indextoname");
699
 
        } else {
700
 
          fprintf_plus(stderr, "Skipping server on non-used interface"
701
 
                       " \"%s\"\n",
702
 
                       if_indextoname((unsigned int)if_index,
703
 
                                      interface));
704
 
        }
705
 
      }
706
 
      return -1;
707
 
    }
708
 
  }
709
 
  
710
660
  ret = init_gnutls_session(&session, mc);
711
661
  if(ret != 0){
712
662
    return -1;
732
682
  
733
683
  memset(&to, 0, sizeof(to));
734
684
  if(af == AF_INET6){
735
 
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
736
 
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
 
685
    to.in6.sin6_family = (sa_family_t)af;
 
686
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
737
687
  } else {                      /* IPv4 */
738
 
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
739
 
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
 
688
    to.in.sin_family = (sa_family_t)af;
 
689
    ret = inet_pton(af, ip, &to.in.sin_addr);
740
690
  }
741
691
  if(ret < 0 ){
742
692
    int e = errno;
751
701
    goto mandos_end;
752
702
  }
753
703
  if(af == AF_INET6){
754
 
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
755
 
    if(IN6_IS_ADDR_LINKLOCAL
756
 
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
 
704
    to.in6.sin6_port = htons(port);    
 
705
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
706
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
 
707
                                -Wunreachable-code*/
757
708
      if(if_index == AVAHI_IF_UNSPEC){
758
709
        fprintf_plus(stderr, "An IPv6 link-local address is"
759
710
                     " incomplete without a network interface\n");
761
712
        goto mandos_end;
762
713
      }
763
714
      /* Set the network interface number as scope */
764
 
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
 
715
      to.in6.sin6_scope_id = (uint32_t)if_index;
765
716
    }
766
717
  } else {
767
 
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
 
718
    to.in.sin_port = htons(port); /* Spurious warnings from
 
719
                                     -Wconversion and
 
720
                                     -Wunreachable-code */
768
721
  }
769
722
  
770
723
  if(quit_now){
787
740
    }
788
741
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
789
742
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
 
743
    const char *pcret;
790
744
    if(af == AF_INET6){
791
 
      ret = getnameinfo((struct sockaddr *)&to,
792
 
                        sizeof(struct sockaddr_in6),
793
 
                        addrstr, sizeof(addrstr), NULL, 0,
794
 
                        NI_NUMERICHOST);
 
745
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
746
                        sizeof(addrstr));
795
747
    } else {
796
 
      ret = getnameinfo((struct sockaddr *)&to,
797
 
                        sizeof(struct sockaddr_in),
798
 
                        addrstr, sizeof(addrstr), NULL, 0,
799
 
                        NI_NUMERICHOST);
 
748
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
749
                        sizeof(addrstr));
800
750
    }
801
 
    if(ret == EAI_SYSTEM){
802
 
      perror_plus("getnameinfo");
803
 
    } else if(ret != 0) {
804
 
      fprintf_plus(stderr, "getnameinfo: %s", gai_strerror(ret));
805
 
    } else if(strcmp(addrstr, ip) != 0){
806
 
      fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
751
    if(pcret == NULL){
 
752
      perror_plus("inet_ntop");
 
753
    } else {
 
754
      if(strcmp(addrstr, ip) != 0){
 
755
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
756
      }
807
757
    }
808
758
  }
809
759
  
813
763
  }
814
764
  
815
765
  if(af == AF_INET6){
816
 
    ret = connect(tcp_sd, (struct sockaddr *)&to,
817
 
                  sizeof(struct sockaddr_in6));
 
766
    ret = connect(tcp_sd, &to.in6, sizeof(to));
818
767
  } else {
819
 
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
820
 
                  sizeof(struct sockaddr_in));
 
768
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
821
769
  }
822
770
  if(ret < 0){
823
 
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
771
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
824
772
      int e = errno;
825
773
      perror_plus("connect");
826
774
      errno = e;
1041
989
  return retval;
1042
990
}
1043
991
 
1044
 
__attribute__((nonnull))
1045
992
static void resolve_callback(AvahiSServiceResolver *r,
1046
993
                             AvahiIfIndex interface,
1047
994
                             AvahiProtocol proto,
1055
1002
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1056
1003
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1057
1004
                             flags,
1058
 
                             void *mc){
 
1005
                             void* mc){
1059
1006
  if(r == NULL){
1060
1007
    return;
1061
1008
  }
1114
1061
                            const char *domain,
1115
1062
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1116
1063
                            flags,
1117
 
                            void *mc){
 
1064
                            void* mc){
1118
1065
  if(b == NULL){
1119
1066
    return;
1120
1067
  }
1180
1127
  errno = old_errno;
1181
1128
}
1182
1129
 
1183
 
__attribute__((nonnull, warn_unused_result))
1184
1130
bool get_flags(const char *ifname, struct ifreq *ifr){
1185
1131
  int ret;
1186
1132
  error_t ret_errno;
1205
1151
  return true;
1206
1152
}
1207
1153
 
1208
 
__attribute__((nonnull, warn_unused_result))
1209
1154
bool good_flags(const char *ifname, const struct ifreq *ifr){
1210
1155
  
1211
1156
  /* Reject the loopback device */
1253
1198
 * corresponds to an acceptable network device.
1254
1199
 * (This function is passed to scandir(3) as a filter function.)
1255
1200
 */
1256
 
__attribute__((nonnull, warn_unused_result))
1257
1201
int good_interface(const struct dirent *if_entry){
1258
1202
  if(if_entry->d_name[0] == '.'){
1259
1203
    return 0;
1277
1221
/* 
1278
1222
 * This function determines if a network interface is up.
1279
1223
 */
1280
 
__attribute__((nonnull, warn_unused_result))
1281
1224
bool interface_is_up(const char *interface){
1282
1225
  struct ifreq ifr;
1283
1226
  if(not get_flags(interface, &ifr)){
1294
1237
/* 
1295
1238
 * This function determines if a network interface is running
1296
1239
 */
1297
 
__attribute__((nonnull, warn_unused_result))
1298
1240
bool interface_is_running(const char *interface){
1299
1241
  struct ifreq ifr;
1300
1242
  if(not get_flags(interface, &ifr)){
1308
1250
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1309
1251
}
1310
1252
 
1311
 
__attribute__((nonnull, pure, warn_unused_result))
1312
1253
int notdotentries(const struct dirent *direntry){
1313
1254
  /* Skip "." and ".." */
1314
1255
  if(direntry->d_name[0] == '.'
1321
1262
}
1322
1263
 
1323
1264
/* Is this directory entry a runnable program? */
1324
 
__attribute__((nonnull, warn_unused_result))
1325
1265
int runnable_hook(const struct dirent *direntry){
1326
1266
  int ret;
1327
1267
  size_t sret;
1382
1322
  return 1;
1383
1323
}
1384
1324
 
1385
 
__attribute__((nonnull, warn_unused_result))
1386
1325
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
1387
1326
                            mandos_context *mc){
1388
1327
  int ret;
1392
1331
  
1393
1332
  while(true){
1394
1333
    if(mc->current_server == NULL){
1395
 
      if(debug){
 
1334
      if (debug){
1396
1335
        fprintf_plus(stderr, "Wait until first server is found."
1397
1336
                     " No timeout!\n");
1398
1337
      }
1399
1338
      ret = avahi_simple_poll_iterate(s, -1);
1400
1339
    } else {
1401
 
      if(debug){
 
1340
      if (debug){
1402
1341
        fprintf_plus(stderr, "Check current_server if we should run"
1403
1342
                     " it, or wait\n");
1404
1343
      }
1421
1360
                     - ((intmax_t)waited_time.tv_sec * 1000))
1422
1361
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1423
1362
      
1424
 
      if(debug){
 
1363
      if (debug){
1425
1364
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1426
1365
                     block_time);
1427
1366
      }
1449
1388
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1450
1389
    }
1451
1390
    if(ret != 0){
1452
 
      if(ret > 0 or errno != EINTR){
 
1391
      if (ret > 0 or errno != EINTR){
1453
1392
        return (ret != 1) ? ret : 0;
1454
1393
      }
1455
1394
    }
1457
1396
}
1458
1397
 
1459
1398
/* Set effective uid to 0, return errno */
1460
 
__attribute__((warn_unused_result))
1461
1399
error_t raise_privileges(void){
1462
1400
  error_t old_errno = errno;
1463
1401
  error_t ret_errno = 0;
1470
1408
}
1471
1409
 
1472
1410
/* Set effective and real user ID to 0.  Return errno. */
1473
 
__attribute__((warn_unused_result))
1474
1411
error_t raise_privileges_permanently(void){
1475
1412
  error_t old_errno = errno;
1476
1413
  error_t ret_errno = raise_privileges();
1487
1424
}
1488
1425
 
1489
1426
/* Set effective user ID to unprivileged saved user ID */
1490
 
__attribute__((warn_unused_result))
1491
1427
error_t lower_privileges(void){
1492
1428
  error_t old_errno = errno;
1493
1429
  error_t ret_errno = 0;
1500
1436
}
1501
1437
 
1502
1438
/* Lower privileges permanently */
1503
 
__attribute__((warn_unused_result))
1504
1439
error_t lower_privileges_permanently(void){
1505
1440
  error_t old_errno = errno;
1506
1441
  error_t ret_errno = 0;
1512
1447
  return ret_errno;
1513
1448
}
1514
1449
 
1515
 
__attribute__((nonnull))
1516
 
void run_network_hooks(const char *mode, const char *interface,
 
1450
bool run_network_hooks(const char *mode, const char *interface,
1517
1451
                       const float delay){
1518
1452
  struct dirent **direntries;
 
1453
  struct dirent *direntry;
 
1454
  int ret;
1519
1455
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1520
1456
                         alphasort);
1521
1457
  if(numhooks == -1){
1528
1464
      perror_plus("scandir");
1529
1465
    }
1530
1466
  } else {
1531
 
    struct dirent *direntry;
1532
 
    int ret;
1533
1467
    int devnull = open("/dev/null", O_RDONLY);
1534
1468
    for(int i = 0; i < numhooks; i++){
1535
1469
      direntry = direntries[i];
1547
1481
      if(hook_pid == 0){
1548
1482
        /* Child */
1549
1483
        /* Raise privileges */
1550
 
        if(raise_privileges_permanently() != 0){
1551
 
          perror_plus("Failed to raise privileges");
1552
 
          _exit(EX_NOPERM);
1553
 
        }
 
1484
        raise_privileges_permanently();
1554
1485
        /* Set group */
1555
1486
        errno = 0;
1556
1487
        ret = setgid(0);
1557
1488
        if(ret == -1){
1558
1489
          perror_plus("setgid");
1559
 
          _exit(EX_NOPERM);
1560
1490
        }
1561
1491
        /* Reset supplementary groups */
1562
1492
        errno = 0;
1563
1493
        ret = setgroups(0, NULL);
1564
1494
        if(ret == -1){
1565
1495
          perror_plus("setgroups");
1566
 
          _exit(EX_NOPERM);
1567
 
        }
1568
 
        ret = dup2(devnull, STDIN_FILENO);
1569
 
        if(ret == -1){
1570
 
          perror_plus("dup2(devnull, STDIN_FILENO)");
1571
 
          _exit(EX_OSERR);
1572
 
        }
1573
 
        ret = close(devnull);
1574
 
        if(ret == -1){
1575
 
          perror_plus("close");
1576
 
          _exit(EX_OSERR);
1577
 
        }
1578
 
        ret = dup2(STDERR_FILENO, STDOUT_FILENO);
1579
 
        if(ret == -1){
1580
 
          perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
1581
 
          _exit(EX_OSERR);
1582
 
        }
 
1496
        }
 
1497
        dup2(devnull, STDIN_FILENO);
 
1498
        close(devnull);
 
1499
        dup2(STDERR_FILENO, STDOUT_FILENO);
1583
1500
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1584
1501
        if(ret == -1){
1585
1502
          perror_plus("setenv");
1601
1518
          _exit(EX_OSERR);
1602
1519
        }
1603
1520
        char *delaystring;
1604
 
        ret = asprintf(&delaystring, "%f", (double)delay);
 
1521
        ret = asprintf(&delaystring, "%f", delay);
1605
1522
        if(ret == -1){
1606
1523
          perror_plus("asprintf");
1607
1524
          _exit(EX_OSERR);
1660
1577
    }
1661
1578
    close(devnull);
1662
1579
  }
 
1580
  return true;
1663
1581
}
1664
1582
 
1665
 
__attribute__((nonnull, warn_unused_result))
1666
1583
error_t bring_up_interface(const char *const interface,
1667
1584
                           const float delay){
 
1585
  int sd = -1;
1668
1586
  error_t old_errno = errno;
1669
 
  int ret;
 
1587
  error_t ret_errno = 0;
 
1588
  int ret, ret_setflags;
1670
1589
  struct ifreq network;
1671
1590
  unsigned int if_index = if_nametoindex(interface);
1672
1591
  if(if_index == 0){
1681
1600
  }
1682
1601
  
1683
1602
  if(not interface_is_up(interface)){
1684
 
    error_t ret_errno = 0, ioctl_errno = 0;
1685
 
    if(not get_flags(interface, &network)){
 
1603
    if(not get_flags(interface, &network) and debug){
1686
1604
      ret_errno = errno;
1687
1605
      fprintf_plus(stderr, "Failed to get flags for interface "
1688
1606
                   "\"%s\"\n", interface);
1689
 
      errno = old_errno;
1690
1607
      return ret_errno;
1691
1608
    }
1692
 
    network.ifr_flags |= IFF_UP; /* set flag */
 
1609
    network.ifr_flags |= IFF_UP;
1693
1610
    
1694
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1695
 
    if(sd == -1){
 
1611
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1612
    if(sd < 0){
1696
1613
      ret_errno = errno;
1697
1614
      perror_plus("socket");
1698
1615
      errno = old_errno;
1699
1616
      return ret_errno;
1700
1617
    }
1701
 
    
 
1618
  
1702
1619
    if(quit_now){
1703
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1704
 
      if(ret == -1){
1705
 
        perror_plus("close");
1706
 
      }
 
1620
      close(sd);
1707
1621
      errno = old_errno;
1708
1622
      return EINTR;
1709
1623
    }
1713
1627
                   interface);
1714
1628
    }
1715
1629
    
1716
 
    /* Raise privileges */
1717
 
    ret_errno = raise_privileges();
1718
 
    if(ret_errno != 0){
1719
 
      perror_plus("Failed to raise privileges");
1720
 
    }
 
1630
    /* Raise priviliges */
 
1631
    raise_privileges();
1721
1632
    
1722
1633
#ifdef __linux__
1723
 
    int ret_linux;
1724
 
    bool restore_loglevel = false;
1725
 
    if(ret_errno == 0){
1726
 
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1727
 
         messages about the network interface to mess up the prompt */
1728
 
      ret_linux = klogctl(8, NULL, 5);
1729
 
      if(ret_linux == -1){
1730
 
        perror_plus("klogctl");
1731
 
      } else {
1732
 
        restore_loglevel = true;
1733
 
      }
 
1634
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1635
       messages about the network interface to mess up the prompt */
 
1636
    int ret_linux = klogctl(8, NULL, 5);
 
1637
    bool restore_loglevel = true;
 
1638
    if(ret_linux == -1){
 
1639
      restore_loglevel = false;
 
1640
      perror_plus("klogctl");
1734
1641
    }
1735
1642
#endif  /* __linux__ */
1736
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1737
 
    ioctl_errno = errno;
 
1643
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1644
    ret_errno = errno;
1738
1645
#ifdef __linux__
1739
1646
    if(restore_loglevel){
1740
1647
      ret_linux = klogctl(7, NULL, 0);
1744
1651
    }
1745
1652
#endif  /* __linux__ */
1746
1653
    
1747
 
    /* If raise_privileges() succeeded above */
1748
 
    if(ret_errno == 0){
1749
 
      /* Lower privileges */
1750
 
      ret_errno = lower_privileges();
1751
 
      if(ret_errno != 0){
1752
 
        errno = ret_errno;
1753
 
        perror_plus("Failed to lower privileges");
1754
 
      }
1755
 
    }
 
1654
    /* Lower privileges */
 
1655
    lower_privileges();
1756
1656
    
1757
1657
    /* Close the socket */
1758
1658
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1761
1661
    }
1762
1662
    
1763
1663
    if(ret_setflags == -1){
1764
 
      errno = ioctl_errno;
 
1664
      errno = ret_errno;
1765
1665
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1766
1666
      errno = old_errno;
1767
 
      return ioctl_errno;
 
1667
      return ret_errno;
1768
1668
    }
1769
1669
  } else if(debug){
1770
1670
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
1788
1688
  return 0;
1789
1689
}
1790
1690
 
1791
 
__attribute__((nonnull, warn_unused_result))
1792
1691
error_t take_down_interface(const char *const interface){
 
1692
  int sd = -1;
1793
1693
  error_t old_errno = errno;
 
1694
  error_t ret_errno = 0;
 
1695
  int ret, ret_setflags;
1794
1696
  struct ifreq network;
1795
1697
  unsigned int if_index = if_nametoindex(interface);
1796
1698
  if(if_index == 0){
1799
1701
    return ENXIO;
1800
1702
  }
1801
1703
  if(interface_is_up(interface)){
1802
 
    error_t ret_errno = 0, ioctl_errno = 0;
1803
1704
    if(not get_flags(interface, &network) and debug){
1804
1705
      ret_errno = errno;
1805
1706
      fprintf_plus(stderr, "Failed to get flags for interface "
1806
1707
                   "\"%s\"\n", interface);
1807
 
      errno = old_errno;
1808
1708
      return ret_errno;
1809
1709
    }
1810
1710
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1811
1711
    
1812
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1813
 
    if(sd == -1){
 
1712
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1713
    if(sd < 0){
1814
1714
      ret_errno = errno;
1815
1715
      perror_plus("socket");
1816
1716
      errno = old_errno;
1822
1722
                   interface);
1823
1723
    }
1824
1724
    
1825
 
    /* Raise privileges */
1826
 
    ret_errno = raise_privileges();
1827
 
    if(ret_errno != 0){
1828
 
      perror_plus("Failed to raise privileges");
1829
 
    }
1830
 
    
1831
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1832
 
    ioctl_errno = errno;
1833
 
    
1834
 
    /* If raise_privileges() succeeded above */
1835
 
    if(ret_errno == 0){
1836
 
      /* Lower privileges */
1837
 
      ret_errno = lower_privileges();
1838
 
      if(ret_errno != 0){
1839
 
        errno = ret_errno;
1840
 
        perror_plus("Failed to lower privileges");
1841
 
      }
1842
 
    }
 
1725
    /* Raise priviliges */
 
1726
    raise_privileges();
 
1727
    
 
1728
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1729
    ret_errno = errno;
 
1730
    
 
1731
    /* Lower privileges */
 
1732
    lower_privileges();
1843
1733
    
1844
1734
    /* Close the socket */
1845
 
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1735
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1846
1736
    if(ret == -1){
1847
1737
      perror_plus("close");
1848
1738
    }
1849
1739
    
1850
1740
    if(ret_setflags == -1){
1851
 
      errno = ioctl_errno;
 
1741
      errno = ret_errno;
1852
1742
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1853
1743
      errno = old_errno;
1854
 
      return ioctl_errno;
 
1744
      return ret_errno;
1855
1745
    }
1856
1746
  } else if(debug){
1857
1747
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
1865
1755
int main(int argc, char *argv[]){
1866
1756
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
1867
1757
                        .priority = "SECURE256:!CTYPE-X.509:"
1868
 
                        "+CTYPE-OPENPGP", .current_server = NULL,
1869
 
                        .interfaces = NULL, .interfaces_size = 0 };
 
1758
                        "+CTYPE-OPENPGP", .current_server = NULL };
1870
1759
  AvahiSServiceBrowser *sb = NULL;
1871
1760
  error_t ret_errno;
1872
1761
  int ret;
1873
1762
  intmax_t tmpmax;
1874
1763
  char *tmp;
1875
1764
  int exitcode = EXIT_SUCCESS;
 
1765
  char *interfaces = NULL;
 
1766
  size_t interfaces_size = 0;
1876
1767
  char *interfaces_to_take_down = NULL;
1877
1768
  size_t interfaces_to_take_down_size = 0;
1878
 
  char run_tempdir[] = "/run/tmp/mandosXXXXXX";
1879
 
  char old_tempdir[] = "/tmp/mandosXXXXXX";
1880
 
  char *tempdir = NULL;
 
1769
  char tempdir[] = "/tmp/mandosXXXXXX";
 
1770
  bool tempdir_created = false;
1881
1771
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1882
1772
  const char *seckey = PATHDIR "/" SECKEY;
1883
1773
  const char *pubkey = PATHDIR "/" PUBKEY;
1884
1774
  char *interfaces_hooks = NULL;
 
1775
  size_t interfaces_hooks_size = 0;
1885
1776
  
1886
1777
  bool gnutls_initialized = false;
1887
1778
  bool gpgme_initialized = false;
1978
1869
        connect_to = arg;
1979
1870
        break;
1980
1871
      case 'i':                 /* --interface */
1981
 
        ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
1982
 
                                 arg, (int)',');
 
1872
        ret_errno = argz_add_sep(&interfaces, &interfaces_size, arg,
 
1873
                                 (int)',');
1983
1874
        if(ret_errno != 0){
1984
1875
          argp_error(state, "%s", strerror(ret_errno));
1985
1876
        }
2065
1956
    /* Work around Debian bug #633582:
2066
1957
       <http://bugs.debian.org/633582> */
2067
1958
    
2068
 
    /* Re-raise privileges */
2069
 
    ret_errno = raise_privileges();
2070
 
    if(ret_errno != 0){
2071
 
      errno = ret_errno;
2072
 
      perror_plus("Failed to raise privileges");
2073
 
    } else {
 
1959
    /* Re-raise priviliges */
 
1960
    if(raise_privileges() == 0){
2074
1961
      struct stat st;
2075
1962
      
2076
1963
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
2116
2003
      }
2117
2004
    
2118
2005
      /* Lower privileges */
2119
 
      ret_errno = lower_privileges();
2120
 
      if(ret_errno != 0){
2121
 
        errno = ret_errno;
2122
 
        perror_plus("Failed to lower privileges");
 
2006
      errno = 0;
 
2007
      ret = seteuid(uid);
 
2008
      if(ret == -1){
 
2009
        perror_plus("seteuid");
2123
2010
      }
2124
2011
    }
2125
2012
  }
2126
2013
  
2127
 
  /* Remove invalid interface names (except "none") */
 
2014
  /* Remove empty interface names */
2128
2015
  {
2129
2016
    char *interface = NULL;
2130
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2017
    while((interface = argz_next(interfaces, interfaces_size,
2131
2018
                                 interface))){
2132
 
      if(strcmp(interface, "none") != 0
2133
 
         and if_nametoindex(interface) == 0){
2134
 
        if(interface[0] != '\0'){
 
2019
      if(if_nametoindex(interface) == 0){
 
2020
        if(interface[0] != '\0' and strcmp(interface, "none") != 0){
2135
2021
          fprintf_plus(stderr, "Not using nonexisting interface"
2136
2022
                       " \"%s\"\n", interface);
2137
2023
        }
2138
 
        argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
 
2024
        argz_delete(&interfaces, &interfaces_size, interface);
2139
2025
        interface = NULL;
2140
2026
      }
2141
2027
    }
2143
2029
  
2144
2030
  /* Run network hooks */
2145
2031
  {
2146
 
    if(mc.interfaces != NULL){
2147
 
      interfaces_hooks = malloc(mc.interfaces_size);
 
2032
    
 
2033
    if(interfaces != NULL){
 
2034
      interfaces_hooks = malloc(interfaces_size);
2148
2035
      if(interfaces_hooks == NULL){
2149
2036
        perror_plus("malloc");
2150
2037
        goto end;
2151
2038
      }
2152
 
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
2153
 
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
2154
 
    }
2155
 
    run_network_hooks("start", interfaces_hooks != NULL ?
2156
 
                      interfaces_hooks : "", delay);
 
2039
      memcpy(interfaces_hooks, interfaces, interfaces_size);
 
2040
      interfaces_hooks_size = interfaces_size;
 
2041
      argz_stringify(interfaces_hooks, interfaces_hooks_size,
 
2042
                     (int)',');
 
2043
    }
 
2044
    if(not run_network_hooks("start", interfaces_hooks != NULL ?
 
2045
                             interfaces_hooks : "", delay)){
 
2046
      goto end;
 
2047
    }
2157
2048
  }
2158
2049
  
2159
2050
  if(not debug){
2236
2127
  }
2237
2128
  
2238
2129
  /* If no interfaces were specified, make a list */
2239
 
  if(mc.interfaces == NULL){
 
2130
  if(interfaces == NULL){
2240
2131
    struct dirent **direntries;
2241
2132
    /* Look for any good interfaces */
2242
2133
    ret = scandir(sys_class_net, &direntries, good_interface,
2244
2135
    if(ret >= 1){
2245
2136
      /* Add all found interfaces to interfaces list */
2246
2137
      for(int i = 0; i < ret; ++i){
2247
 
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
 
2138
        ret_errno = argz_add(&interfaces, &interfaces_size,
2248
2139
                             direntries[i]->d_name);
2249
2140
        if(ret_errno != 0){
2250
 
          errno = ret_errno;
2251
2141
          perror_plus("argz_add");
2252
2142
          continue;
2253
2143
        }
2265
2155
    }
2266
2156
  }
2267
2157
  
2268
 
  /* Bring up interfaces which are down, and remove any "none"s */
2269
 
  {
 
2158
  /* If we only got one interface, explicitly use only that one */
 
2159
  if(argz_count(interfaces, interfaces_size) == 1){
 
2160
    if(debug){
 
2161
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
 
2162
                   interfaces);
 
2163
    }
 
2164
    if_index = (AvahiIfIndex)if_nametoindex(interfaces);
 
2165
  }
 
2166
  
 
2167
  /* Bring up interfaces which are down */
 
2168
  if(not (argz_count(interfaces, interfaces_size) == 1
 
2169
          and strcmp(interfaces, "none") == 0)){
2270
2170
    char *interface = NULL;
2271
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2171
    while((interface = argz_next(interfaces, interfaces_size,
2272
2172
                                 interface))){
2273
 
      /* If interface name is "none", stop bringing up interfaces.
2274
 
         Also remove all instances of "none" from the list */
2275
 
      if(strcmp(interface, "none") == 0){
2276
 
        argz_delete(&mc.interfaces, &mc.interfaces_size,
2277
 
                    interface);
2278
 
        interface = NULL;
2279
 
        while((interface = argz_next(mc.interfaces,
2280
 
                                     mc.interfaces_size, interface))){
2281
 
          if(strcmp(interface, "none") == 0){
2282
 
            argz_delete(&mc.interfaces, &mc.interfaces_size,
2283
 
                        interface);
2284
 
            interface = NULL;
2285
 
          }
2286
 
        }
2287
 
        break;
2288
 
      }
2289
2173
      bool interface_was_up = interface_is_up(interface);
2290
 
      errno = bring_up_interface(interface, delay);
 
2174
      ret = bring_up_interface(interface, delay);
2291
2175
      if(not interface_was_up){
2292
 
        if(errno != 0){
 
2176
        if(ret != 0){
 
2177
          errno = ret;
2293
2178
          perror_plus("Failed to bring up interface");
2294
2179
        } else {
2295
 
          errno = argz_add(&interfaces_to_take_down,
2296
 
                           &interfaces_to_take_down_size,
2297
 
                           interface);
2298
 
          if(errno != 0){
2299
 
            perror_plus("argz_add");
2300
 
          }
 
2180
          ret_errno = argz_add(&interfaces_to_take_down,
 
2181
                               &interfaces_to_take_down_size,
 
2182
                               interface);
2301
2183
        }
2302
2184
      }
2303
2185
    }
 
2186
    free(interfaces);
 
2187
    interfaces = NULL;
 
2188
    interfaces_size = 0;
2304
2189
    if(debug and (interfaces_to_take_down == NULL)){
2305
2190
      fprintf_plus(stderr, "No interfaces were brought up\n");
2306
2191
    }
2307
2192
  }
2308
2193
  
2309
 
  /* If we only got one interface, explicitly use only that one */
2310
 
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
2311
 
    if(debug){
2312
 
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
2313
 
                   mc.interfaces);
2314
 
    }
2315
 
    if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
2316
 
  }
2317
 
  
2318
2194
  if(quit_now){
2319
2195
    goto end;
2320
2196
  }
2332
2208
    goto end;
2333
2209
  }
2334
2210
  
2335
 
  /* Try /run/tmp before /tmp */
2336
 
  tempdir = mkdtemp(run_tempdir);
2337
 
  if(tempdir == NULL and errno == ENOENT){
2338
 
      if(debug){
2339
 
        fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
2340
 
                     run_tempdir, old_tempdir);
2341
 
      }
2342
 
      tempdir = mkdtemp(old_tempdir);
2343
 
  }
2344
 
  if(tempdir == NULL){
 
2211
  if(mkdtemp(tempdir) == NULL){
2345
2212
    perror_plus("mkdtemp");
2346
2213
    goto end;
2347
2214
  }
 
2215
  tempdir_created = true;
2348
2216
  
2349
2217
  if(quit_now){
2350
2218
    goto end;
2386
2254
      exitcode = EX_USAGE;
2387
2255
      goto end;
2388
2256
    }
2389
 
    
 
2257
  
2390
2258
    if(quit_now){
2391
2259
      goto end;
2392
2260
    }
2422
2290
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2423
2291
                     (int)retry_interval);
2424
2292
      }
2425
 
      sleep((unsigned int)retry_interval);
 
2293
      sleep((int)retry_interval);
2426
2294
    }
2427
2295
    
2428
 
    if(not quit_now){
 
2296
    if (not quit_now){
2429
2297
      exitcode = EXIT_SUCCESS;
2430
2298
    }
2431
2299
    
2501
2369
  }
2502
2370
  
2503
2371
  /* Cleanup things */
2504
 
  free(mc.interfaces);
2505
 
  
2506
2372
  if(sb != NULL)
2507
2373
    avahi_s_service_browser_free(sb);
2508
2374
  
2533
2399
    }
2534
2400
  }
2535
2401
  
2536
 
  /* Re-raise privileges */
 
2402
  /* Re-raise priviliges */
2537
2403
  {
2538
 
    ret_errno = raise_privileges();
2539
 
    if(ret_errno != 0){
2540
 
      perror_plus("Failed to raise privileges");
2541
 
    } else {
2542
 
      
2543
 
      /* Run network hooks */
2544
 
      run_network_hooks("stop", interfaces_hooks != NULL ?
2545
 
                        interfaces_hooks : "", delay);
2546
 
      
2547
 
      /* Take down the network interfaces which were brought up */
2548
 
      {
2549
 
        char *interface = NULL;
2550
 
        while((interface=argz_next(interfaces_to_take_down,
2551
 
                                   interfaces_to_take_down_size,
2552
 
                                   interface))){
2553
 
          ret_errno = take_down_interface(interface);
2554
 
          if(ret_errno != 0){
2555
 
            errno = ret_errno;
2556
 
            perror_plus("Failed to take down interface");
2557
 
          }
2558
 
        }
2559
 
        if(debug and (interfaces_to_take_down == NULL)){
2560
 
          fprintf_plus(stderr, "No interfaces needed to be taken"
2561
 
                       " down\n");
2562
 
        }
2563
 
      }
2564
 
    }
2565
 
    
2566
 
    ret_errno = lower_privileges_permanently();
2567
 
    if(ret_errno != 0){
2568
 
      perror_plus("Failed to lower privileges permanently");
2569
 
    }
 
2404
    raise_privileges();
 
2405
    
 
2406
    /* Run network hooks */
 
2407
    run_network_hooks("stop", interfaces_hooks != NULL ?
 
2408
                      interfaces_hooks : "", delay);
 
2409
    
 
2410
    /* Take down the network interfaces which were brought up */
 
2411
    {
 
2412
      char *interface = NULL;
 
2413
      while((interface=argz_next(interfaces_to_take_down,
 
2414
                                 interfaces_to_take_down_size,
 
2415
                                 interface))){
 
2416
        ret_errno = take_down_interface(interface);
 
2417
        if(ret_errno != 0){
 
2418
          errno = ret_errno;
 
2419
          perror_plus("Failed to take down interface");
 
2420
        }
 
2421
      }
 
2422
      if(debug and (interfaces_to_take_down == NULL)){
 
2423
        fprintf_plus(stderr, "No interfaces needed to be taken"
 
2424
                     " down\n");
 
2425
      }
 
2426
    }
 
2427
    
 
2428
    lower_privileges_permanently();
2570
2429
  }
2571
2430
  
2572
2431
  free(interfaces_to_take_down);
2573
2432
  free(interfaces_hooks);
2574
2433
  
2575
2434
  /* Removes the GPGME temp directory and all files inside */
2576
 
  if(tempdir != NULL){
 
2435
  if(tempdir_created){
2577
2436
    struct dirent **direntries = NULL;
2578
2437
    struct dirent *direntry = NULL;
2579
2438
    int numentries = scandir(tempdir, &direntries, notdotentries,
2580
2439
                             alphasort);
2581
 
    if(numentries > 0){
 
2440
    if (numentries > 0){
2582
2441
      for(int i = 0; i < numentries; i++){
2583
2442
        direntry = direntries[i];
2584
2443
        char *fullname = NULL;
2599
2458
 
2600
2459
    /* need to clean even if 0 because man page doesn't specify */
2601
2460
    free(direntries);
2602
 
    if(numentries == -1){
 
2461
    if (numentries == -1){
2603
2462
      perror_plus("scandir");
2604
2463
    }
2605
2464
    ret = rmdir(tempdir);