/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2012-06-16 23:39:10 UTC
  • Revision ID: teddy@recompile.se-20120616233910-jxxxriq608qa6o8z
* plugins.d/mandos-client (mandos_context): New "interfaces" and
                                            "interfaces_size" members.
  (main): Removed "interfaces" and "interfaces_size" variabled; all
          users changed.

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