/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-2013 Teddy Hogeborn
13
 
 * Copyright © 2008-2013 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() */
136
133
 
137
134
bool debug = false;
138
135
static const char mandos_protocol_version[] = "1";
139
 
const char * argp_program_version = "mandos-client " VERSION;
140
 
const char * argp_program_bug_address = "<mandos@recompile.se>";
 
136
const char *argp_program_version = "mandos-client " VERSION;
 
137
const char *argp_program_bug_address = "<mandos@recompile.se>";
141
138
static const char sys_class_net[] = "/sys/class/net";
142
139
char *connect_to = NULL;
143
140
const char *hookdir = HOOKDIR;
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;
1382
1324
  return 1;
1383
1325
}
1384
1326
 
1385
 
__attribute__((nonnull, warn_unused_result))
1386
1327
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
1387
1328
                            mandos_context *mc){
1388
1329
  int ret;
1392
1333
  
1393
1334
  while(true){
1394
1335
    if(mc->current_server == NULL){
1395
 
      if(debug){
 
1336
      if (debug){
1396
1337
        fprintf_plus(stderr, "Wait until first server is found."
1397
1338
                     " No timeout!\n");
1398
1339
      }
1399
1340
      ret = avahi_simple_poll_iterate(s, -1);
1400
1341
    } else {
1401
 
      if(debug){
 
1342
      if (debug){
1402
1343
        fprintf_plus(stderr, "Check current_server if we should run"
1403
1344
                     " it, or wait\n");
1404
1345
      }
1421
1362
                     - ((intmax_t)waited_time.tv_sec * 1000))
1422
1363
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1423
1364
      
1424
 
      if(debug){
 
1365
      if (debug){
1425
1366
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1426
1367
                     block_time);
1427
1368
      }
1449
1390
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1450
1391
    }
1451
1392
    if(ret != 0){
1452
 
      if(ret > 0 or errno != EINTR){
 
1393
      if (ret > 0 or errno != EINTR){
1453
1394
        return (ret != 1) ? ret : 0;
1454
1395
      }
1455
1396
    }
1457
1398
}
1458
1399
 
1459
1400
/* Set effective uid to 0, return errno */
1460
 
__attribute__((warn_unused_result))
1461
1401
error_t raise_privileges(void){
1462
1402
  error_t old_errno = errno;
1463
1403
  error_t ret_errno = 0;
1470
1410
}
1471
1411
 
1472
1412
/* Set effective and real user ID to 0.  Return errno. */
1473
 
__attribute__((warn_unused_result))
1474
1413
error_t raise_privileges_permanently(void){
1475
1414
  error_t old_errno = errno;
1476
1415
  error_t ret_errno = raise_privileges();
1487
1426
}
1488
1427
 
1489
1428
/* Set effective user ID to unprivileged saved user ID */
1490
 
__attribute__((warn_unused_result))
1491
1429
error_t lower_privileges(void){
1492
1430
  error_t old_errno = errno;
1493
1431
  error_t ret_errno = 0;
1500
1438
}
1501
1439
 
1502
1440
/* Lower privileges permanently */
1503
 
__attribute__((warn_unused_result))
1504
1441
error_t lower_privileges_permanently(void){
1505
1442
  error_t old_errno = errno;
1506
1443
  error_t ret_errno = 0;
1512
1449
  return ret_errno;
1513
1450
}
1514
1451
 
1515
 
__attribute__((nonnull))
1516
 
void run_network_hooks(const char *mode, const char *interface,
 
1452
bool run_network_hooks(const char *mode, const char *interface,
1517
1453
                       const float delay){
1518
1454
  struct dirent **direntries;
 
1455
  struct dirent *direntry;
 
1456
  int ret;
1519
1457
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1520
1458
                         alphasort);
1521
1459
  if(numhooks == -1){
1528
1466
      perror_plus("scandir");
1529
1467
    }
1530
1468
  } else {
1531
 
    struct dirent *direntry;
1532
 
    int ret;
1533
1469
    int devnull = open("/dev/null", O_RDONLY);
1534
1470
    for(int i = 0; i < numhooks; i++){
1535
1471
      direntry = direntries[i];
1547
1483
      if(hook_pid == 0){
1548
1484
        /* Child */
1549
1485
        /* Raise privileges */
1550
 
        if(raise_privileges_permanently() != 0){
1551
 
          perror_plus("Failed to raise privileges");
1552
 
          _exit(EX_NOPERM);
1553
 
        }
 
1486
        raise_privileges_permanently();
1554
1487
        /* Set group */
1555
1488
        errno = 0;
1556
1489
        ret = setgid(0);
1557
1490
        if(ret == -1){
1558
1491
          perror_plus("setgid");
1559
 
          _exit(EX_NOPERM);
1560
1492
        }
1561
1493
        /* Reset supplementary groups */
1562
1494
        errno = 0;
1563
1495
        ret = setgroups(0, NULL);
1564
1496
        if(ret == -1){
1565
1497
          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
 
        }
 
1498
        }
 
1499
        dup2(devnull, STDIN_FILENO);
 
1500
        close(devnull);
 
1501
        dup2(STDERR_FILENO, STDOUT_FILENO);
1583
1502
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1584
1503
        if(ret == -1){
1585
1504
          perror_plus("setenv");
1601
1520
          _exit(EX_OSERR);
1602
1521
        }
1603
1522
        char *delaystring;
1604
 
        ret = asprintf(&delaystring, "%f", (double)delay);
 
1523
        ret = asprintf(&delaystring, "%f", delay);
1605
1524
        if(ret == -1){
1606
1525
          perror_plus("asprintf");
1607
1526
          _exit(EX_OSERR);
1660
1579
    }
1661
1580
    close(devnull);
1662
1581
  }
 
1582
  return true;
1663
1583
}
1664
1584
 
1665
 
__attribute__((nonnull, warn_unused_result))
1666
1585
error_t bring_up_interface(const char *const interface,
1667
1586
                           const float delay){
 
1587
  int sd = -1;
1668
1588
  error_t old_errno = errno;
1669
 
  int ret;
 
1589
  error_t ret_errno = 0;
 
1590
  int ret, ret_setflags;
1670
1591
  struct ifreq network;
1671
1592
  unsigned int if_index = if_nametoindex(interface);
1672
1593
  if(if_index == 0){
1681
1602
  }
1682
1603
  
1683
1604
  if(not interface_is_up(interface)){
1684
 
    error_t ret_errno = 0, ioctl_errno = 0;
1685
 
    if(not get_flags(interface, &network)){
 
1605
    if(not get_flags(interface, &network) and debug){
1686
1606
      ret_errno = errno;
1687
1607
      fprintf_plus(stderr, "Failed to get flags for interface "
1688
1608
                   "\"%s\"\n", interface);
1689
 
      errno = old_errno;
1690
1609
      return ret_errno;
1691
1610
    }
1692
 
    network.ifr_flags |= IFF_UP; /* set flag */
 
1611
    network.ifr_flags |= IFF_UP;
1693
1612
    
1694
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1695
 
    if(sd == -1){
 
1613
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1614
    if(sd < 0){
1696
1615
      ret_errno = errno;
1697
1616
      perror_plus("socket");
1698
1617
      errno = old_errno;
1699
1618
      return ret_errno;
1700
1619
    }
1701
 
    
 
1620
  
1702
1621
    if(quit_now){
1703
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1704
 
      if(ret == -1){
1705
 
        perror_plus("close");
1706
 
      }
 
1622
      close(sd);
1707
1623
      errno = old_errno;
1708
1624
      return EINTR;
1709
1625
    }
1713
1629
                   interface);
1714
1630
    }
1715
1631
    
1716
 
    /* Raise privileges */
1717
 
    ret_errno = raise_privileges();
1718
 
    bool restore_loglevel = false;
1719
 
    if(ret_errno != 0){
1720
 
      perror_plus("Failed to raise privileges");
1721
 
    }
 
1632
    /* Raise priviliges */
 
1633
    raise_privileges();
 
1634
    
1722
1635
#ifdef __linux__
1723
 
    int ret_linux;
1724
 
    if(ret_errno == 0){
1725
 
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1726
 
         messages about the network interface to mess up the prompt */
1727
 
      ret_linux = klogctl(8, NULL, 5);
1728
 
      if(ret_linux == -1){
1729
 
        perror_plus("klogctl");
1730
 
      } else {
1731
 
        restore_loglevel = true;
1732
 
      }
 
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");
1733
1643
    }
1734
1644
#endif  /* __linux__ */
1735
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1736
 
    ioctl_errno = errno;
 
1645
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1646
    ret_errno = errno;
1737
1647
#ifdef __linux__
1738
1648
    if(restore_loglevel){
1739
1649
      ret_linux = klogctl(7, NULL, 0);
1743
1653
    }
1744
1654
#endif  /* __linux__ */
1745
1655
    
1746
 
    /* If raise_privileges() succeeded above */
1747
 
    if(ret_errno == 0){
1748
 
      /* Lower privileges */
1749
 
      ret_errno = lower_privileges();
1750
 
      if(ret_errno != 0){
1751
 
        errno = ret_errno;
1752
 
        perror_plus("Failed to lower privileges");
1753
 
      }
1754
 
    }
 
1656
    /* Lower privileges */
 
1657
    lower_privileges();
1755
1658
    
1756
1659
    /* Close the socket */
1757
1660
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1760
1663
    }
1761
1664
    
1762
1665
    if(ret_setflags == -1){
1763
 
      errno = ioctl_errno;
 
1666
      errno = ret_errno;
1764
1667
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1765
1668
      errno = old_errno;
1766
 
      return ioctl_errno;
 
1669
      return ret_errno;
1767
1670
    }
1768
1671
  } else if(debug){
1769
1672
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
1787
1690
  return 0;
1788
1691
}
1789
1692
 
1790
 
__attribute__((nonnull, warn_unused_result))
1791
1693
error_t take_down_interface(const char *const interface){
 
1694
  int sd = -1;
1792
1695
  error_t old_errno = errno;
 
1696
  error_t ret_errno = 0;
 
1697
  int ret, ret_setflags;
1793
1698
  struct ifreq network;
1794
1699
  unsigned int if_index = if_nametoindex(interface);
1795
1700
  if(if_index == 0){
1798
1703
    return ENXIO;
1799
1704
  }
1800
1705
  if(interface_is_up(interface)){
1801
 
    error_t ret_errno = 0, ioctl_errno = 0;
1802
1706
    if(not get_flags(interface, &network) and debug){
1803
1707
      ret_errno = errno;
1804
1708
      fprintf_plus(stderr, "Failed to get flags for interface "
1805
1709
                   "\"%s\"\n", interface);
1806
 
      errno = old_errno;
1807
1710
      return ret_errno;
1808
1711
    }
1809
1712
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1810
1713
    
1811
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1812
 
    if(sd == -1){
 
1714
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1715
    if(sd < 0){
1813
1716
      ret_errno = errno;
1814
1717
      perror_plus("socket");
1815
1718
      errno = old_errno;
1821
1724
                   interface);
1822
1725
    }
1823
1726
    
1824
 
    /* Raise privileges */
1825
 
    ret_errno = raise_privileges();
1826
 
    if(ret_errno != 0){
1827
 
      perror_plus("Failed to raise privileges");
1828
 
    }
1829
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1830
 
    ioctl_errno = errno;
1831
 
    
1832
 
    /* If raise_privileges() succeeded above */
1833
 
    if(ret_errno == 0){
1834
 
      /* Lower privileges */
1835
 
      ret_errno = lower_privileges();
1836
 
      if(ret_errno != 0){
1837
 
        errno = ret_errno;
1838
 
        perror_plus("Failed to lower privileges");
1839
 
      }
1840
 
    }
 
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();
1841
1735
    
1842
1736
    /* Close the socket */
1843
 
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1737
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1844
1738
    if(ret == -1){
1845
1739
      perror_plus("close");
1846
1740
    }
1847
1741
    
1848
1742
    if(ret_setflags == -1){
1849
 
      errno = ioctl_errno;
 
1743
      errno = ret_errno;
1850
1744
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1851
1745
      errno = old_errno;
1852
 
      return ioctl_errno;
 
1746
      return ret_errno;
1853
1747
    }
1854
1748
  } else if(debug){
1855
1749
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
1863
1757
int main(int argc, char *argv[]){
1864
1758
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
1865
1759
                        .priority = "SECURE256:!CTYPE-X.509:"
1866
 
                        "+CTYPE-OPENPGP", .current_server = NULL,
 
1760
                        "+CTYPE-OPENPGP", .current_server = NULL, 
1867
1761
                        .interfaces = NULL, .interfaces_size = 0 };
1868
1762
  AvahiSServiceBrowser *sb = NULL;
1869
1763
  error_t ret_errno;
1873
1767
  int exitcode = EXIT_SUCCESS;
1874
1768
  char *interfaces_to_take_down = NULL;
1875
1769
  size_t interfaces_to_take_down_size = 0;
1876
 
  char run_tempdir[] = "/run/tmp/mandosXXXXXX";
1877
 
  char old_tempdir[] = "/tmp/mandosXXXXXX";
1878
 
  char *tempdir = NULL;
 
1770
  char tempdir[] = "/tmp/mandosXXXXXX";
 
1771
  bool tempdir_created = false;
1879
1772
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1880
1773
  const char *seckey = PATHDIR "/" SECKEY;
1881
1774
  const char *pubkey = PATHDIR "/" PUBKEY;
1882
1775
  char *interfaces_hooks = NULL;
 
1776
  size_t interfaces_hooks_size = 0;
1883
1777
  
1884
1778
  bool gnutls_initialized = false;
1885
1779
  bool gpgme_initialized = false;
2063
1957
    /* Work around Debian bug #633582:
2064
1958
       <http://bugs.debian.org/633582> */
2065
1959
    
2066
 
    /* Re-raise privileges */
2067
 
    ret_errno = raise_privileges();
2068
 
    if(ret_errno != 0){
2069
 
      errno = ret_errno;
2070
 
      perror_plus("Failed to raise privileges");
2071
 
    } else {
 
1960
    /* Re-raise priviliges */
 
1961
    if(raise_privileges() == 0){
2072
1962
      struct stat st;
2073
1963
      
2074
1964
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
2114
2004
      }
2115
2005
    
2116
2006
      /* Lower privileges */
2117
 
      ret_errno = lower_privileges();
2118
 
      if(ret_errno != 0){
2119
 
        errno = ret_errno;
2120
 
        perror_plus("Failed to lower privileges");
 
2007
      errno = 0;
 
2008
      ret = seteuid(uid);
 
2009
      if(ret == -1){
 
2010
        perror_plus("seteuid");
2121
2011
      }
2122
2012
    }
2123
2013
  }
2124
2014
  
2125
 
  /* Remove invalid interface names (except "none") */
 
2015
  /* Remove empty interface names */
2126
2016
  {
2127
2017
    char *interface = NULL;
2128
2018
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2129
2019
                                 interface))){
2130
 
      if(strcmp(interface, "none") != 0
2131
 
         and if_nametoindex(interface) == 0){
2132
 
        if(interface[0] != '\0'){
 
2020
      if(if_nametoindex(interface) == 0){
 
2021
        if(interface[0] != '\0' and strcmp(interface, "none") != 0){
2133
2022
          fprintf_plus(stderr, "Not using nonexisting interface"
2134
2023
                       " \"%s\"\n", interface);
2135
2024
        }
2141
2030
  
2142
2031
  /* Run network hooks */
2143
2032
  {
 
2033
    
2144
2034
    if(mc.interfaces != NULL){
2145
2035
      interfaces_hooks = malloc(mc.interfaces_size);
2146
2036
      if(interfaces_hooks == NULL){
2148
2038
        goto end;
2149
2039
      }
2150
2040
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
2151
 
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
2152
 
    }
2153
 
    run_network_hooks("start", interfaces_hooks != NULL ?
2154
 
                      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
    }
2155
2049
  }
2156
2050
  
2157
2051
  if(not debug){
2245
2139
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
2246
2140
                             direntries[i]->d_name);
2247
2141
        if(ret_errno != 0){
2248
 
          errno = ret_errno;
2249
2142
          perror_plus("argz_add");
2250
2143
          continue;
2251
2144
        }
2263
2156
    }
2264
2157
  }
2265
2158
  
2266
 
  /* Bring up interfaces which are down, and remove any "none"s */
2267
 
  {
 
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)){
2268
2171
    char *interface = NULL;
2269
2172
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2270
2173
                                 interface))){
2271
 
      /* If interface name is "none", stop bringing up interfaces.
2272
 
         Also remove all instances of "none" from the list */
2273
 
      if(strcmp(interface, "none") == 0){
2274
 
        argz_delete(&mc.interfaces, &mc.interfaces_size,
2275
 
                    interface);
2276
 
        interface = NULL;
2277
 
        while((interface = argz_next(mc.interfaces,
2278
 
                                     mc.interfaces_size, interface))){
2279
 
          if(strcmp(interface, "none") == 0){
2280
 
            argz_delete(&mc.interfaces, &mc.interfaces_size,
2281
 
                        interface);
2282
 
            interface = NULL;
2283
 
          }
2284
 
        }
2285
 
        break;
2286
 
      }
2287
2174
      bool interface_was_up = interface_is_up(interface);
2288
 
      errno = bring_up_interface(interface, delay);
 
2175
      ret = bring_up_interface(interface, delay);
2289
2176
      if(not interface_was_up){
2290
 
        if(errno != 0){
 
2177
        if(ret != 0){
 
2178
          errno = ret;
2291
2179
          perror_plus("Failed to bring up interface");
2292
2180
        } else {
2293
 
          errno = argz_add(&interfaces_to_take_down,
2294
 
                           &interfaces_to_take_down_size,
2295
 
                           interface);
2296
 
          if(errno != 0){
2297
 
            perror_plus("argz_add");
2298
 
          }
 
2181
          ret_errno = argz_add(&interfaces_to_take_down,
 
2182
                               &interfaces_to_take_down_size,
 
2183
                               interface);
2299
2184
        }
2300
2185
      }
2301
2186
    }
 
2187
    free(mc.interfaces);
 
2188
    mc.interfaces = NULL;
 
2189
    mc.interfaces_size = 0;
2302
2190
    if(debug and (interfaces_to_take_down == NULL)){
2303
2191
      fprintf_plus(stderr, "No interfaces were brought up\n");
2304
2192
    }
2305
2193
  }
2306
2194
  
2307
 
  /* If we only got one interface, explicitly use only that one */
2308
 
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
2309
 
    if(debug){
2310
 
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
2311
 
                   mc.interfaces);
2312
 
    }
2313
 
    if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
2314
 
  }
2315
 
  
2316
2195
  if(quit_now){
2317
2196
    goto end;
2318
2197
  }
2330
2209
    goto end;
2331
2210
  }
2332
2211
  
2333
 
  /* Try /run/tmp before /tmp */
2334
 
  tempdir = mkdtemp(run_tempdir);
2335
 
  if(tempdir == NULL and errno == ENOENT){
2336
 
      if(debug){
2337
 
        fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
2338
 
                     run_tempdir, old_tempdir);
2339
 
      }
2340
 
      tempdir = mkdtemp(old_tempdir);
2341
 
  }
2342
 
  if(tempdir == NULL){
 
2212
  if(mkdtemp(tempdir) == NULL){
2343
2213
    perror_plus("mkdtemp");
2344
2214
    goto end;
2345
2215
  }
 
2216
  tempdir_created = true;
2346
2217
  
2347
2218
  if(quit_now){
2348
2219
    goto end;
2384
2255
      exitcode = EX_USAGE;
2385
2256
      goto end;
2386
2257
    }
2387
 
    
 
2258
  
2388
2259
    if(quit_now){
2389
2260
      goto end;
2390
2261
    }
2420
2291
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2421
2292
                     (int)retry_interval);
2422
2293
      }
2423
 
      sleep((unsigned int)retry_interval);
 
2294
      sleep((int)retry_interval);
2424
2295
    }
2425
2296
    
2426
 
    if(not quit_now){
 
2297
    if (not quit_now){
2427
2298
      exitcode = EXIT_SUCCESS;
2428
2299
    }
2429
2300
    
2499
2370
  }
2500
2371
  
2501
2372
  /* Cleanup things */
2502
 
  free(mc.interfaces);
2503
 
  
2504
2373
  if(sb != NULL)
2505
2374
    avahi_s_service_browser_free(sb);
2506
2375
  
2531
2400
    }
2532
2401
  }
2533
2402
  
2534
 
  /* Re-raise privileges */
 
2403
  /* Re-raise priviliges */
2535
2404
  {
2536
 
    ret_errno = raise_privileges();
2537
 
    if(ret_errno != 0){
2538
 
      perror_plus("Failed to raise privileges");
2539
 
    } else {
2540
 
      
2541
 
      /* Run network hooks */
2542
 
      run_network_hooks("stop", interfaces_hooks != NULL ?
2543
 
                        interfaces_hooks : "", delay);
2544
 
      
2545
 
      /* Take down the network interfaces which were brought up */
2546
 
      {
2547
 
        char *interface = NULL;
2548
 
        while((interface=argz_next(interfaces_to_take_down,
2549
 
                                   interfaces_to_take_down_size,
2550
 
                                   interface))){
2551
 
          ret_errno = take_down_interface(interface);
2552
 
          if(ret_errno != 0){
2553
 
            errno = ret_errno;
2554
 
            perror_plus("Failed to take down interface");
2555
 
          }
2556
 
        }
2557
 
        if(debug and (interfaces_to_take_down == NULL)){
2558
 
          fprintf_plus(stderr, "No interfaces needed to be taken"
2559
 
                       " down\n");
2560
 
        }
2561
 
      }
2562
 
    }
2563
 
    ret_errno = lower_privileges_permanently();
2564
 
    if(ret_errno != 0){
2565
 
      perror_plus("Failed to lower privileges permanently");
2566
 
    }
 
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();
2567
2430
  }
2568
2431
  
2569
2432
  free(interfaces_to_take_down);
2570
2433
  free(interfaces_hooks);
2571
2434
  
2572
2435
  /* Removes the GPGME temp directory and all files inside */
2573
 
  if(tempdir != NULL){
 
2436
  if(tempdir_created){
2574
2437
    struct dirent **direntries = NULL;
2575
2438
    struct dirent *direntry = NULL;
2576
2439
    int numentries = scandir(tempdir, &direntries, notdotentries,
2577
2440
                             alphasort);
2578
 
    if(numentries > 0){
 
2441
    if (numentries > 0){
2579
2442
      for(int i = 0; i < numentries; i++){
2580
2443
        direntry = direntries[i];
2581
2444
        char *fullname = NULL;
2596
2459
 
2597
2460
    /* need to clean even if 0 because man page doesn't specify */
2598
2461
    free(direntries);
2599
 
    if(numentries == -1){
 
2462
    if (numentries == -1){
2600
2463
      perror_plus("scandir");
2601
2464
    }
2602
2465
    ret = rmdir(tempdir);