817
499
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
818
500
__attribute__((unused)) const char *txt){}
820
/* Set effective uid to 0, return errno */
821
__attribute__((warn_unused_result))
822
int raise_privileges(void){
823
int old_errno = errno;
825
if(seteuid(0) == -1){
832
/* Set effective and real user ID to 0. Return errno. */
833
__attribute__((warn_unused_result))
834
int raise_privileges_permanently(void){
835
int old_errno = errno;
836
int ret = raise_privileges();
848
/* Set effective user ID to unprivileged saved user ID */
849
__attribute__((warn_unused_result))
850
int lower_privileges(void){
851
int old_errno = errno;
853
if(seteuid(uid) == -1){
860
/* Lower privileges permanently */
861
__attribute__((warn_unused_result))
862
int lower_privileges_permanently(void){
863
int old_errno = errno;
865
if(setuid(uid) == -1){
872
/* Helper function to add_local_route() and delete_local_route() */
873
__attribute__((nonnull, warn_unused_result))
874
static bool add_delete_local_route(const bool add,
876
AvahiIfIndex if_index){
878
char helper[] = "mandos-client-iprouteadddel";
879
char add_arg[] = "add";
880
char delete_arg[] = "delete";
881
char debug_flag[] = "--debug";
882
char *pluginhelperdir = getenv("MANDOSPLUGINHELPERDIR");
883
if(pluginhelperdir == NULL){
885
fprintf_plus(stderr, "MANDOSPLUGINHELPERDIR environment"
886
" variable not set; cannot run helper\n");
891
char interface[IF_NAMESIZE];
892
if(if_indextoname((unsigned int)if_index, interface) == NULL){
893
perror_plus("if_indextoname");
897
int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
899
perror_plus("open(\"/dev/null\", O_RDONLY)");
905
/* Raise privileges */
906
errno = raise_privileges_permanently();
908
perror_plus("Failed to raise privileges");
909
/* _exit(EX_NOPERM); */
915
perror_plus("setgid");
918
/* Reset supplementary groups */
920
ret = setgroups(0, NULL);
922
perror_plus("setgroups");
926
ret = dup2(devnull, STDIN_FILENO);
928
perror_plus("dup2(devnull, STDIN_FILENO)");
931
ret = close(devnull);
933
perror_plus("close");
936
ret = dup2(STDERR_FILENO, STDOUT_FILENO);
938
perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
941
int helperdir_fd = (int)TEMP_FAILURE_RETRY(open(pluginhelperdir,
946
if(helperdir_fd == -1){
948
_exit(EX_UNAVAILABLE);
950
int helper_fd = (int)TEMP_FAILURE_RETRY(openat(helperdir_fd,
953
perror_plus("openat");
955
_exit(EX_UNAVAILABLE);
959
#pragma GCC diagnostic push
960
#pragma GCC diagnostic ignored "-Wcast-qual"
962
if(fexecve(helper_fd, (char *const [])
963
{ helper, add ? add_arg : delete_arg, (char *)address,
964
interface, debug ? debug_flag : NULL, NULL },
967
#pragma GCC diagnostic pop
969
perror_plus("fexecve");
981
pret = waitpid(pid, &status, 0);
982
if(pret == -1 and errno == EINTR and quit_now){
983
int errno_raising = 0;
984
if((errno = raise_privileges()) != 0){
985
errno_raising = errno;
986
perror_plus("Failed to raise privileges in order to"
987
" kill helper program");
989
if(kill(pid, SIGTERM) == -1){
992
if((errno_raising == 0) and (errno = lower_privileges()) != 0){
993
perror_plus("Failed to lower privileges after killing"
998
} while(pret == -1 and errno == EINTR);
1000
perror_plus("waitpid");
1003
if(WIFEXITED(status)){
1004
if(WEXITSTATUS(status) != 0){
1005
fprintf_plus(stderr, "Error: iprouteadddel exited"
1006
" with status %d\n", WEXITSTATUS(status));
1011
if(WIFSIGNALED(status)){
1012
fprintf_plus(stderr, "Error: iprouteadddel died by"
1013
" signal %d\n", WTERMSIG(status));
1016
fprintf_plus(stderr, "Error: iprouteadddel crashed\n");
1020
__attribute__((nonnull, warn_unused_result))
1021
static bool add_local_route(const char *address,
1022
AvahiIfIndex if_index){
1024
fprintf_plus(stderr, "Adding route to %s\n", address);
1026
return add_delete_local_route(true, address, if_index);
1029
__attribute__((nonnull, warn_unused_result))
1030
static bool delete_local_route(const char *address,
1031
AvahiIfIndex if_index){
1033
fprintf_plus(stderr, "Removing route to %s\n", address);
1035
return add_delete_local_route(false, address, if_index);
1038
502
/* Called when a Mandos server is found */
1039
__attribute__((nonnull, warn_unused_result))
1040
static int start_mandos_communication(const char *ip, in_port_t port,
503
static int start_mandos_communication(const char *ip, uint16_t port,
1041
504
AvahiIfIndex if_index,
1042
int af, mandos_context *mc){
1043
int ret, tcp_sd = -1;
1045
struct sockaddr_storage to;
507
union { struct sockaddr in; struct sockaddr_in6 in6; } to;
1046
508
char *buffer = NULL;
1047
char *decrypted_buffer = NULL;
509
char *decrypted_buffer;
1048
510
size_t buffer_length = 0;
1049
511
size_t buffer_capacity = 0;
512
ssize_t decrypted_buffer_size;
515
char interface[IF_NAMESIZE];
1052
516
gnutls_session_t session;
1053
int pf; /* Protocol family */
1054
bool route_added = false;
1071
fprintf_plus(stderr, "Bad address family: %d\n", af);
1076
/* If the interface is specified and we have a list of interfaces */
1077
if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
1078
/* Check if the interface is one of the interfaces we are using */
1081
char *interface = NULL;
1082
while((interface=argz_next(mc->interfaces, mc->interfaces_size,
1084
if(if_nametoindex(interface) == (unsigned int)if_index){
1091
/* This interface does not match any in the list, so we don't
1092
connect to the server */
1094
char interface[IF_NAMESIZE];
1095
if(if_indextoname((unsigned int)if_index, interface) == NULL){
1096
perror_plus("if_indextoname");
1098
fprintf_plus(stderr, "Skipping server on non-used interface"
1100
if_indextoname((unsigned int)if_index,
518
ret = init_gnutls_session (mc, &session);
524
fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
528
tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
535
if(if_indextoname((unsigned int)if_index, interface) == NULL){
536
perror("if_indextoname");
539
fprintf(stderr, "Binding to interface %s\n", interface);
1108
ret = init_gnutls_session(&session, mc);
542
memset(&to, 0, sizeof(to));
543
to.in6.sin6_family = AF_INET6;
544
/* It would be nice to have a way to detect if we were passed an
545
IPv4 address here. Now we assume an IPv6 address. */
546
ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
1114
fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
1115
PRIuMAX "\n", ip, (uintmax_t)port);
1118
tcp_sd = socket(pf, SOCK_STREAM | SOCK_CLOEXEC, 0);
1121
perror_plus("socket");
1132
struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&to;
1133
*to6 = (struct sockaddr_in6){ .sin6_family = (sa_family_t)af };
1134
ret = inet_pton(af, ip, &to6->sin6_addr);
1136
struct sockaddr_in *to4 = (struct sockaddr_in *)&to;
1137
*to4 = (struct sockaddr_in){ .sin_family = (sa_family_t)af };
1138
ret = inet_pton(af, ip, &to4->sin_addr);
1142
perror_plus("inet_pton");
1148
fprintf_plus(stderr, "Bad address: %s\n", ip);
1153
((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
1154
if(IN6_IS_ADDR_LINKLOCAL
1155
(&((struct sockaddr_in6 *)&to)->sin6_addr)){
1156
if(if_index == AVAHI_IF_UNSPEC){
1157
fprintf_plus(stderr, "An IPv6 link-local address is"
1158
" incomplete without a network interface\n");
1162
/* Set the network interface number as scope */
1163
((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
1166
((struct sockaddr_in *)&to)->sin_port = htons(port);
552
fprintf(stderr, "Bad address: %s\n", ip);
555
to.in6.sin6_port = htons(port); /* Spurious warning */
557
to.in6.sin6_scope_id = (uint32_t)if_index;
1175
if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
1176
char interface[IF_NAMESIZE];
1177
if(if_indextoname((unsigned int)if_index, interface) == NULL){
1178
perror_plus("if_indextoname");
1180
fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
1181
"\n", ip, interface, (uintmax_t)port);
1184
fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
1185
ip, (uintmax_t)port);
1187
char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
1188
INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
1190
ret = getnameinfo((struct sockaddr *)&to,
1191
sizeof(struct sockaddr_in6),
1192
addrstr, sizeof(addrstr), NULL, 0,
1195
ret = getnameinfo((struct sockaddr *)&to,
1196
sizeof(struct sockaddr_in),
1197
addrstr, sizeof(addrstr), NULL, 0,
1200
if(ret == EAI_SYSTEM){
1201
perror_plus("getnameinfo");
1202
} else if(ret != 0) {
1203
fprintf_plus(stderr, "getnameinfo: %s", gai_strerror(ret));
1204
} else if(strcmp(addrstr, ip) != 0){
1205
fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
1216
ret = connect(tcp_sd, (struct sockaddr *)&to,
1217
sizeof(struct sockaddr_in6));
1219
ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
1220
sizeof(struct sockaddr_in));
1223
if(((errno == ENETUNREACH) or (errno == EHOSTUNREACH))
1224
and if_index != AVAHI_IF_UNSPEC
1225
and connect_to == NULL
1226
and not route_added and
1227
((af == AF_INET6 and not
1228
IN6_IS_ADDR_LINKLOCAL(&(((struct sockaddr_in6 *)
1230
or (af == AF_INET and
1231
/* Not a a IPv4LL address */
1232
(ntohl(((struct sockaddr_in *)&to)->sin_addr.s_addr)
1233
& 0xFFFF0000L) != 0xA9FE0000L))){
1234
/* Work around Avahi bug - Avahi does not announce link-local
1235
addresses if it has a global address, so local hosts with
1236
*only* a link-local address (e.g. Mandos clients) cannot
1237
connect to a Mandos server announced by Avahi on a server
1238
host with a global address. Work around this by retrying
1239
with an explicit route added with the server's address.
1241
Avahi bug reference:
1242
https://lists.freedesktop.org/archives/avahi/2010-February/001833.html
1243
https://bugs.debian.org/587961
1246
fprintf_plus(stderr, "Mandos server unreachable, trying"
1250
route_added = add_local_route(ip, if_index);
1256
if(errno != ECONNREFUSED or debug){
1258
perror_plus("connect");
560
fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
562
char addrstr[INET6_ADDRSTRLEN] = "";
563
if(inet_ntop(to.in6.sin6_family, &(to.in6.sin6_addr), addrstr,
564
sizeof(addrstr)) == NULL){
567
if(strcmp(addrstr, ip) != 0){
568
fprintf(stderr, "Canonical address form: %s\n", addrstr);
573
ret = connect(tcp_sd, &to.in, sizeof(to));
1271
579
const char *out = mandos_protocol_version;
1274
582
size_t out_size = strlen(out);
1275
ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
1276
out_size - written));
1279
perror_plus("write");
583
ret = TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
584
out_size - written));
1281
588
goto mandos_end;
1283
590
written += (size_t)ret;
1284
591
if(written < out_size){
1287
if(out == mandos_protocol_version){
594
if (out == mandos_protocol_version){
1302
fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
1310
/* This casting via intptr_t is to eliminate warning about casting
1311
an int to a pointer type. This is exactly how the GnuTLS Guile
1312
function "set-session-transport-fd!" does it. */
1313
gnutls_transport_set_ptr(session,
1314
(gnutls_transport_ptr_t)(intptr_t)tcp_sd);
1322
ret = gnutls_handshake(session);
604
fprintf(stderr, "Establishing TLS session with %s\n", ip);
607
gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) tcp_sd);
610
ret = gnutls_handshake (session);
1327
611
} while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
1329
if(ret != GNUTLS_E_SUCCESS){
613
if (ret != GNUTLS_E_SUCCESS){
1331
fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
615
fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
1335
619
goto mandos_end;
1338
622
/* Read OpenPGP packet that contains the wanted password */
1341
fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
625
fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
1352
buffer_capacity = incbuffer(&buffer, buffer_length,
1354
if(buffer_capacity == 0){
1356
perror_plus("incbuffer");
1366
sret = gnutls_record_recv(session, buffer+buffer_length,
630
buffer_capacity = adjustbuffer(&buffer, buffer_length,
632
if (buffer_capacity == 0){
633
perror("adjustbuffer");
638
ret = gnutls_record_recv(session, buffer+buffer_length,
1373
645
case GNUTLS_E_INTERRUPTED:
1374
646
case GNUTLS_E_AGAIN:
1376
648
case GNUTLS_E_REHANDSHAKE:
1378
ret = gnutls_handshake(session);
650
ret = gnutls_handshake (session);
1384
651
} while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
1386
fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
653
fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
1390
656
goto mandos_end;
1394
fprintf_plus(stderr, "Unknown error while reading data from"
1395
" encrypted session with Mandos server\n");
1396
gnutls_bye(session, GNUTLS_SHUT_RDWR);
660
fprintf(stderr, "Unknown error while reading data from"
661
" encrypted session with Mandos server\n");
663
gnutls_bye (session, GNUTLS_SHUT_RDWR);
1398
664
goto mandos_end;
1401
buffer_length += (size_t) sret;
667
buffer_length += (size_t) ret;
1406
fprintf_plus(stderr, "Closing TLS session\n");
1415
ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
1420
} while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
1422
if(buffer_length > 0){
1423
ssize_t decrypted_buffer_size;
1424
decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
1425
&decrypted_buffer, mc);
1426
if(decrypted_buffer_size >= 0){
672
fprintf(stderr, "Closing TLS session\n");
675
gnutls_bye (session, GNUTLS_SHUT_RDWR);
677
if (buffer_length > 0){
678
decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
681
if (decrypted_buffer_size >= 0){
1430
683
while(written < (size_t) decrypted_buffer_size){
1436
ret = (int)fwrite(decrypted_buffer + written, 1,
1437
(size_t)decrypted_buffer_size - written,
684
ret = (int)fwrite (decrypted_buffer + written, 1,
685
(size_t)decrypted_buffer_size - written,
1439
687
if(ret == 0 and ferror(stdout)){
1442
fprintf_plus(stderr, "Error writing encrypted data: %s\n",
689
fprintf(stderr, "Error writing encrypted data: %s\n",
1448
695
written += (size_t)ret;
1450
ret = fflush(stdout);
1454
fprintf_plus(stderr, "Error writing encrypted data: %s\n",
697
free(decrypted_buffer);
1464
705
/* Shutdown procedure */
1469
if(not delete_local_route(ip, if_index)){
1470
fprintf_plus(stderr, "Failed to delete local route to %s on"
1471
" interface %d", ip, if_index);
1475
free(decrypted_buffer);
1478
ret = close(tcp_sd);
1484
perror_plus("close");
1486
gnutls_deinit(session);
709
ret = TEMP_FAILURE_RETRY(close(tcp_sd));
713
gnutls_deinit (session);
1496
__attribute__((nonnull))
1497
717
static void resolve_callback(AvahiSServiceResolver *r,
1498
718
AvahiIfIndex interface,
1499
AvahiProtocol proto,
719
AVAHI_GCC_UNUSED AvahiProtocol protocol,
1500
720
AvahiResolverEvent event,
1501
721
const char *name,
1502
722
const char *type,
1611
805
case AVAHI_BROWSER_ALL_FOR_NOW:
1612
806
case AVAHI_BROWSER_CACHE_EXHAUSTED:
1614
fprintf_plus(stderr, "No Mandos server found, still"
808
fprintf(stderr, "No Mandos server found, still searching...\n");
1621
/* Signal handler that stops main loop after SIGTERM */
1622
static void handle_sigterm(int sig){
1627
signal_received = sig;
1628
int old_errno = errno;
1629
/* set main loop to exit */
1630
if(simple_poll != NULL){
1631
avahi_simple_poll_quit(simple_poll);
1636
__attribute__((nonnull, warn_unused_result))
1637
bool get_flags(const char *ifname, struct ifreq *ifr){
1641
int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1644
perror_plus("socket");
1648
strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
1649
ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
1650
ret = ioctl(s, SIOCGIFFLAGS, ifr);
1654
perror_plus("ioctl SIOCGIFFLAGS");
1662
__attribute__((nonnull, warn_unused_result))
1663
bool good_flags(const char *ifname, const struct ifreq *ifr){
1665
/* Reject the loopback device */
1666
if(ifr->ifr_flags & IFF_LOOPBACK){
1668
fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1673
/* Accept point-to-point devices only if connect_to is specified */
1674
if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1676
fprintf_plus(stderr, "Accepting point-to-point interface"
1677
" \"%s\"\n", ifname);
1681
/* Otherwise, reject non-broadcast-capable devices */
1682
if(not (ifr->ifr_flags & IFF_BROADCAST)){
1684
fprintf_plus(stderr, "Rejecting non-broadcast interface"
1685
" \"%s\"\n", ifname);
1689
/* Reject non-ARP interfaces (including dummy interfaces) */
1690
if(ifr->ifr_flags & IFF_NOARP){
1692
fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1698
/* Accept this device */
1700
fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1706
* This function determines if a directory entry in /sys/class/net
1707
* corresponds to an acceptable network device.
1708
* (This function is passed to scandir(3) as a filter function.)
1710
__attribute__((nonnull, warn_unused_result))
1711
int good_interface(const struct dirent *if_entry){
1712
if(if_entry->d_name[0] == '.'){
1717
if(not get_flags(if_entry->d_name, &ifr)){
1719
fprintf_plus(stderr, "Failed to get flags for interface "
1720
"\"%s\"\n", if_entry->d_name);
1725
if(not good_flags(if_entry->d_name, &ifr)){
1732
* This function determines if a network interface is up.
1734
__attribute__((nonnull, warn_unused_result))
1735
bool interface_is_up(const char *interface){
1737
if(not get_flags(interface, &ifr)){
1739
fprintf_plus(stderr, "Failed to get flags for interface "
1740
"\"%s\"\n", interface);
1745
return (bool)(ifr.ifr_flags & IFF_UP);
1749
* This function determines if a network interface is running
1751
__attribute__((nonnull, warn_unused_result))
1752
bool interface_is_running(const char *interface){
1754
if(not get_flags(interface, &ifr)){
1756
fprintf_plus(stderr, "Failed to get flags for interface "
1757
"\"%s\"\n", interface);
1762
return (bool)(ifr.ifr_flags & IFF_RUNNING);
1765
__attribute__((nonnull, pure, warn_unused_result))
1766
int notdotentries(const struct dirent *direntry){
1767
/* Skip "." and ".." */
1768
if(direntry->d_name[0] == '.'
1769
and (direntry->d_name[1] == '\0'
1770
or (direntry->d_name[1] == '.'
1771
and direntry->d_name[2] == '\0'))){
1777
/* Is this directory entry a runnable program? */
1778
__attribute__((nonnull, warn_unused_result))
1779
int runnable_hook(const struct dirent *direntry){
1784
if((direntry->d_name)[0] == '\0'){
1789
sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1790
"abcdefghijklmnopqrstuvwxyz"
1793
if((direntry->d_name)[sret] != '\0'){
1794
/* Contains non-allowed characters */
1796
fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
1802
ret = fstatat(hookdir_fd, direntry->d_name, &st, 0);
1805
perror_plus("Could not stat hook");
1809
if(not (S_ISREG(st.st_mode))){
1810
/* Not a regular file */
1812
fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
1817
if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1818
/* Not executable */
1820
fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
1826
fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
1832
__attribute__((nonnull, warn_unused_result))
1833
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
1834
mandos_context *mc){
1836
struct timespec now;
1837
struct timespec waited_time;
1838
intmax_t block_time;
1841
if(mc->current_server == NULL){
1843
fprintf_plus(stderr, "Wait until first server is found."
1846
ret = avahi_simple_poll_iterate(s, -1);
1849
fprintf_plus(stderr, "Check current_server if we should run"
1852
/* the current time */
1853
ret = clock_gettime(CLOCK_MONOTONIC, &now);
1855
perror_plus("clock_gettime");
1858
/* Calculating in ms how long time between now and server
1859
who we visted longest time ago. Now - last seen. */
1860
waited_time.tv_sec = (now.tv_sec
1861
- mc->current_server->last_seen.tv_sec);
1862
waited_time.tv_nsec = (now.tv_nsec
1863
- mc->current_server->last_seen.tv_nsec);
1864
/* total time is 10s/10,000ms.
1865
Converting to s from ms by dividing by 1,000,
1866
and ns to ms by dividing by 1,000,000. */
1867
block_time = ((retry_interval
1868
- ((intmax_t)waited_time.tv_sec * 1000))
1869
- ((intmax_t)waited_time.tv_nsec / 1000000));
1872
fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1876
if(block_time <= 0){
1877
ret = start_mandos_communication(mc->current_server->ip,
1878
mc->current_server->port,
1879
mc->current_server->if_index,
1880
mc->current_server->af, mc);
1882
avahi_simple_poll_quit(s);
1885
ret = clock_gettime(CLOCK_MONOTONIC,
1886
&mc->current_server->last_seen);
1888
perror_plus("clock_gettime");
1891
mc->current_server = mc->current_server->next;
1892
block_time = 0; /* Call avahi to find new Mandos
1893
servers, but don't block */
1896
ret = avahi_simple_poll_iterate(s, (int)block_time);
1899
if(ret > 0 or errno != EINTR){
1900
return (ret != 1) ? ret : 0;
1906
__attribute__((nonnull))
1907
void run_network_hooks(const char *mode, const char *interface,
1909
struct dirent **direntries = NULL;
1910
if(hookdir_fd == -1){
1911
hookdir_fd = open(hookdir, O_RDONLY | O_DIRECTORY | O_PATH
1913
if(hookdir_fd == -1){
1914
if(errno == ENOENT){
1916
fprintf_plus(stderr, "Network hook directory \"%s\" not"
1917
" found\n", hookdir);
1920
perror_plus("open");
1925
int numhooks = scandirat(hookdir_fd, ".", &direntries,
1926
runnable_hook, alphasort);
1928
perror_plus("scandir");
1931
struct dirent *direntry;
1933
int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
1935
perror_plus("open(\"/dev/null\", O_RDONLY)");
1938
for(int i = 0; i < numhooks; i++){
1939
direntry = direntries[i];
1941
fprintf_plus(stderr, "Running network hook \"%s\"\n",
1944
pid_t hook_pid = fork();
1947
/* Raise privileges */
1948
errno = raise_privileges_permanently();
1950
perror_plus("Failed to raise privileges");
1957
perror_plus("setgid");
1960
/* Reset supplementary groups */
1962
ret = setgroups(0, NULL);
1964
perror_plus("setgroups");
1967
ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1969
perror_plus("setenv");
1972
ret = setenv("DEVICE", interface, 1);
1974
perror_plus("setenv");
1977
ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1979
perror_plus("setenv");
1982
ret = setenv("MODE", mode, 1);
1984
perror_plus("setenv");
1988
ret = asprintf(&delaystring, "%f", (double)delay);
1990
perror_plus("asprintf");
1993
ret = setenv("DELAY", delaystring, 1);
1996
perror_plus("setenv");
2000
if(connect_to != NULL){
2001
ret = setenv("CONNECT", connect_to, 1);
2003
perror_plus("setenv");
2007
int hook_fd = (int)TEMP_FAILURE_RETRY(openat(hookdir_fd,
2011
perror_plus("openat");
2012
_exit(EXIT_FAILURE);
2014
if(close(hookdir_fd) == -1){
2015
perror_plus("close");
2016
_exit(EXIT_FAILURE);
2018
ret = dup2(devnull, STDIN_FILENO);
2020
perror_plus("dup2(devnull, STDIN_FILENO)");
2023
ret = close(devnull);
2025
perror_plus("close");
2028
ret = dup2(STDERR_FILENO, STDOUT_FILENO);
2030
perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
2033
if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
2035
perror_plus("fexecve");
2036
_exit(EXIT_FAILURE);
2040
perror_plus("fork");
2045
if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
2046
perror_plus("waitpid");
2050
if(WIFEXITED(status)){
2051
if(WEXITSTATUS(status) != 0){
2052
fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
2053
" with status %d\n", direntry->d_name,
2054
WEXITSTATUS(status));
2058
} else if(WIFSIGNALED(status)){
2059
fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
2060
" signal %d\n", direntry->d_name,
2065
fprintf_plus(stderr, "Warning: network hook \"%s\""
2066
" crashed\n", direntry->d_name);
2072
fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
2078
if(close(hookdir_fd) == -1){
2079
perror_plus("close");
2086
__attribute__((nonnull, warn_unused_result))
2087
int bring_up_interface(const char *const interface,
2089
int old_errno = errno;
2091
struct ifreq network;
2092
unsigned int if_index = if_nametoindex(interface);
2094
fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
2104
if(not interface_is_up(interface)){
2106
int ioctl_errno = 0;
2107
if(not get_flags(interface, &network)){
2109
fprintf_plus(stderr, "Failed to get flags for interface "
2110
"\"%s\"\n", interface);
2114
network.ifr_flags |= IFF_UP; /* set flag */
2116
int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
2119
perror_plus("socket");
2127
perror_plus("close");
2134
fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
2138
/* Raise privileges */
2139
ret_errno = raise_privileges();
2142
perror_plus("Failed to raise privileges");
2147
bool restore_loglevel = false;
2149
/* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
2150
messages about the network interface to mess up the prompt */
2151
ret_linux = klogctl(8, NULL, 5);
2152
if(ret_linux == -1){
2153
perror_plus("klogctl");
2155
restore_loglevel = true;
2158
#endif /* __linux__ */
2159
int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
2160
ioctl_errno = errno;
2162
if(restore_loglevel){
2163
ret_linux = klogctl(7, NULL, 0);
2164
if(ret_linux == -1){
2165
perror_plus("klogctl");
2168
#endif /* __linux__ */
2170
/* If raise_privileges() succeeded above */
2172
/* Lower privileges */
2173
ret_errno = lower_privileges();
2176
perror_plus("Failed to lower privileges");
2180
/* Close the socket */
2183
perror_plus("close");
2186
if(ret_setflags == -1){
2187
errno = ioctl_errno;
2188
perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
2193
fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
2197
/* Sleep checking until interface is running.
2198
Check every 0.25s, up to total time of delay */
2199
for(int i=0; i < delay * 4; i++){
2200
if(interface_is_running(interface)){
2203
struct timespec sleeptime = { .tv_nsec = 250000000 };
2204
ret = nanosleep(&sleeptime, NULL);
2205
if(ret == -1 and errno != EINTR){
2206
perror_plus("nanosleep");
2214
__attribute__((nonnull, warn_unused_result))
2215
int take_down_interface(const char *const interface){
2216
int old_errno = errno;
2217
struct ifreq network;
2218
unsigned int if_index = if_nametoindex(interface);
2220
fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
2224
if(interface_is_up(interface)){
2226
int ioctl_errno = 0;
2227
if(not get_flags(interface, &network) and debug){
2229
fprintf_plus(stderr, "Failed to get flags for interface "
2230
"\"%s\"\n", interface);
2234
network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2236
int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
2239
perror_plus("socket");
2245
fprintf_plus(stderr, "Taking down interface \"%s\"\n",
2249
/* Raise privileges */
2250
ret_errno = raise_privileges();
2253
perror_plus("Failed to raise privileges");
2256
int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
2257
ioctl_errno = errno;
2259
/* If raise_privileges() succeeded above */
2261
/* Lower privileges */
2262
ret_errno = lower_privileges();
2265
perror_plus("Failed to lower privileges");
2269
/* Close the socket */
2270
int ret = close(sd);
2272
perror_plus("close");
2275
if(ret_setflags == -1){
2276
errno = ioctl_errno;
2277
perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
2282
fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
2290
814
int main(int argc, char *argv[]){
2291
mandos_context mc = { .server = NULL, .dh_bits = 0,
2292
.priority = "SECURE256:!CTYPE-X.509"
2293
":+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256",
2294
.current_server = NULL, .interfaces = NULL,
2295
.interfaces_size = 0 };
2296
AvahiSServiceBrowser *sb = NULL;
2301
int exitcode = EXIT_SUCCESS;
2302
char *interfaces_to_take_down = NULL;
2303
size_t interfaces_to_take_down_size = 0;
2304
char run_tempdir[] = "/run/tmp/mandosXXXXXX";
2305
char old_tempdir[] = "/tmp/mandosXXXXXX";
2306
char *tempdir = NULL;
2307
AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
2308
const char *seckey = PATHDIR "/" SECKEY;
2309
const char *pubkey = PATHDIR "/" PUBKEY;
2310
const char *dh_params_file = NULL;
2311
char *interfaces_hooks = NULL;
2313
bool gnutls_initialized = false;
2314
bool gpgme_initialized = false;
2316
double retry_interval = 10; /* 10s between trying a server and
2317
retrying the same server again */
2319
struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
2320
struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
2325
/* Lower any group privileges we might have, just to be safe */
2329
perror_plus("setgid");
2332
/* Lower user privileges (temporarily) */
2336
perror_plus("seteuid");
2344
struct argp_option options[] = {
2345
{ .name = "debug", .key = 128,
2346
.doc = "Debug mode", .group = 3 },
2347
{ .name = "connect", .key = 'c',
2348
.arg = "ADDRESS:PORT",
2349
.doc = "Connect directly to a specific Mandos server",
2351
{ .name = "interface", .key = 'i',
2353
.doc = "Network interface that will be used to search for"
2356
{ .name = "seckey", .key = 's',
2358
.doc = "OpenPGP secret key file base name",
2360
{ .name = "pubkey", .key = 'p',
2362
.doc = "OpenPGP public key file base name",
2364
{ .name = "dh-bits", .key = 129,
2366
.doc = "Bit length of the prime number used in the"
2367
" Diffie-Hellman key exchange",
2369
{ .name = "dh-params", .key = 134,
2371
.doc = "PEM-encoded PKCS#3 file with pre-generated parameters"
2372
" for the Diffie-Hellman key exchange",
2374
{ .name = "priority", .key = 130,
2376
.doc = "GnuTLS priority string for the TLS handshake",
2378
{ .name = "delay", .key = 131,
2380
.doc = "Maximum delay to wait for interface startup",
2382
{ .name = "retry", .key = 132,
2384
.doc = "Retry interval used when denied by the Mandos server",
2386
{ .name = "network-hook-dir", .key = 133,
2388
.doc = "Directory where network hooks are located",
2391
* These reproduce what we would get without ARGP_NO_HELP
2393
{ .name = "help", .key = '?',
2394
.doc = "Give this help list", .group = -1 },
2395
{ .name = "usage", .key = -3,
2396
.doc = "Give a short usage message", .group = -1 },
2397
{ .name = "version", .key = 'V',
2398
.doc = "Print program version", .group = -1 },
2402
error_t parse_opt(int key, char *arg,
2403
struct argp_state *state){
815
AvahiSServiceBrowser *sb = NULL;
818
int exitcode = EXIT_SUCCESS;
819
const char *interface = "eth0";
820
struct ifreq network;
824
char *connect_to = NULL;
825
char tempdir[] = "/tmp/mandosXXXXXX";
826
AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
827
const char *seckey = PATHDIR "/" SECKEY;
828
const char *pubkey = PATHDIR "/" PUBKEY;
830
mandos_context mc = { .simple_poll = NULL, .server = NULL,
831
.dh_bits = 1024, .priority = "SECURE256"
832
":!CTYPE-X.509:+CTYPE-OPENPGP" };
833
bool gnutls_initalized = false;
834
bool gpgme_initalized = false;
837
struct argp_option options[] = {
838
{ .name = "debug", .key = 128,
839
.doc = "Debug mode", .group = 3 },
840
{ .name = "connect", .key = 'c',
841
.arg = "ADDRESS:PORT",
842
.doc = "Connect directly to a specific Mandos server",
844
{ .name = "interface", .key = 'i',
846
.doc = "Interface that will be used to search for Mandos"
849
{ .name = "seckey", .key = 's',
851
.doc = "OpenPGP secret key file base name",
853
{ .name = "pubkey", .key = 'p',
855
.doc = "OpenPGP public key file base name",
857
{ .name = "dh-bits", .key = 129,
859
.doc = "Bit length of the prime number used in the"
860
" Diffie-Hellman key exchange",
862
{ .name = "priority", .key = 130,
864
.doc = "GnuTLS priority string for the TLS handshake",
869
error_t parse_opt (int key, char *arg,
870
struct argp_state *state) {
871
/* Get the INPUT argument from `argp_parse', which we know is
872
a pointer to our plugin list pointer. */
874
case 128: /* --debug */
877
case 'c': /* --connect */
880
case 'i': /* --interface */
883
case 's': /* --seckey */
886
case 'p': /* --pubkey */
889
case 129: /* --dh-bits */
891
mc.dh_bits = (unsigned int) strtol(arg, NULL, 10);
897
case 130: /* --priority */
905
return ARGP_ERR_UNKNOWN;
910
struct argp argp = { .options = options, .parser = parse_opt,
912
.doc = "Mandos client -- Get and decrypt"
913
" passwords from a Mandos server" };
914
ret = argp_parse (&argp, argc, argv, 0, 0, NULL);
915
if (ret == ARGP_ERR_UNKNOWN){
916
fprintf(stderr, "Unknown error while parsing arguments\n");
917
exitcode = EXIT_FAILURE;
922
/* If the interface is down, bring it up */
924
sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
927
exitcode = EXIT_FAILURE;
930
strcpy(network.ifr_name, interface);
931
ret = ioctl(sd, SIOCGIFFLAGS, &network);
933
perror("ioctl SIOCGIFFLAGS");
934
exitcode = EXIT_FAILURE;
937
if((network.ifr_flags & IFF_UP) == 0){
938
network.ifr_flags |= IFF_UP;
939
ret = ioctl(sd, SIOCSIFFLAGS, &network);
941
perror("ioctl SIOCSIFFLAGS");
942
exitcode = EXIT_FAILURE;
946
ret = TEMP_FAILURE_RETRY(close(sd));
965
ret = init_gnutls_global(&mc, pubkey, seckey);
967
fprintf(stderr, "init_gnutls_global failed\n");
968
exitcode = EXIT_FAILURE;
971
gnutls_initalized = true;
974
if(mkdtemp(tempdir) == NULL){
980
if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
981
fprintf(stderr, "gpgme_initalized failed\n");
982
exitcode = EXIT_FAILURE;
985
gpgme_initalized = true;
988
if_index = (AvahiIfIndex) if_nametoindex(interface);
990
fprintf(stderr, "No such interface: \"%s\"\n", interface);
994
if(connect_to != NULL){
995
/* Connect directly, do not use Zeroconf */
996
/* (Mainly meant for debugging) */
997
char *address = strrchr(connect_to, ':');
999
fprintf(stderr, "No colon in address\n");
1000
exitcode = EXIT_FAILURE;
2406
case 128: /* --debug */
2409
case 'c': /* --connect */
2412
case 'i': /* --interface */
2413
ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
2416
argp_error(state, "%s", strerror(ret_errno));
2419
case 's': /* --seckey */
2422
case 'p': /* --pubkey */
2425
case 129: /* --dh-bits */
2427
tmpmax = strtoimax(arg, &tmp, 10);
2428
if(errno != 0 or tmp == arg or *tmp != '\0'
2429
or tmpmax != (typeof(mc.dh_bits))tmpmax){
2430
argp_error(state, "Bad number of DH bits");
2432
mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2434
case 134: /* --dh-params */
2435
dh_params_file = arg;
2437
case 130: /* --priority */
2440
case 131: /* --delay */
2442
delay = strtof(arg, &tmp);
2443
if(errno != 0 or tmp == arg or *tmp != '\0'){
2444
argp_error(state, "Bad delay");
2446
case 132: /* --retry */
2448
retry_interval = strtod(arg, &tmp);
2449
if(errno != 0 or tmp == arg or *tmp != '\0'
2450
or (retry_interval * 1000) > INT_MAX
2451
or retry_interval < 0){
2452
argp_error(state, "Bad retry interval");
2455
case 133: /* --network-hook-dir */
2459
* These reproduce what we would get without ARGP_NO_HELP
2461
case '?': /* --help */
2462
argp_state_help(state, state->out_stream,
2463
(ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
2464
& ~(unsigned int)ARGP_HELP_EXIT_OK);
2465
case -3: /* --usage */
2466
argp_state_help(state, state->out_stream,
2467
ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
2468
case 'V': /* --version */
2469
fprintf_plus(state->out_stream, "%s\n", argp_program_version);
2470
exit(argp_err_exit_status);
2473
return ARGP_ERR_UNKNOWN;
2478
struct argp argp = { .options = options, .parser = parse_opt,
2480
.doc = "Mandos client -- Get and decrypt"
2481
" passwords from a Mandos server" };
2482
ret_errno = argp_parse(&argp, argc, argv,
2483
ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
2490
perror_plus("argp_parse");
2491
exitcode = EX_OSERR;
2494
exitcode = EX_USAGE;
2500
/* Work around Debian bug #633582:
2501
<https://bugs.debian.org/633582> */
2503
/* Re-raise privileges */
2504
ret = raise_privileges();
2507
perror_plus("Failed to raise privileges");
2511
if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
2512
int seckey_fd = open(seckey, O_RDONLY);
2513
if(seckey_fd == -1){
2514
perror_plus("open");
2516
ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
2518
perror_plus("fstat");
2520
if(S_ISREG(st.st_mode)
2521
and st.st_uid == 0 and st.st_gid == 0){
2522
ret = fchown(seckey_fd, uid, gid);
2524
perror_plus("fchown");
2532
if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
2533
int pubkey_fd = open(pubkey, O_RDONLY);
2534
if(pubkey_fd == -1){
2535
perror_plus("open");
2537
ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
2539
perror_plus("fstat");
2541
if(S_ISREG(st.st_mode)
2542
and st.st_uid == 0 and st.st_gid == 0){
2543
ret = fchown(pubkey_fd, uid, gid);
2545
perror_plus("fchown");
2553
if(dh_params_file != NULL
2554
and strcmp(dh_params_file, PATHDIR "/dhparams.pem" ) == 0){
2555
int dhparams_fd = open(dh_params_file, O_RDONLY);
2556
if(dhparams_fd == -1){
2557
perror_plus("open");
2559
ret = (int)TEMP_FAILURE_RETRY(fstat(dhparams_fd, &st));
2561
perror_plus("fstat");
2563
if(S_ISREG(st.st_mode)
2564
and st.st_uid == 0 and st.st_gid == 0){
2565
ret = fchown(dhparams_fd, uid, gid);
2567
perror_plus("fchown");
2575
/* Lower privileges */
2576
ret = lower_privileges();
2579
perror_plus("Failed to lower privileges");
2584
/* Remove invalid interface names (except "none") */
2586
char *interface = NULL;
2587
while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2589
if(strcmp(interface, "none") != 0
2590
and if_nametoindex(interface) == 0){
2591
if(interface[0] != '\0'){
2592
fprintf_plus(stderr, "Not using nonexisting interface"
2593
" \"%s\"\n", interface);
2595
argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
2601
/* Run network hooks */
2603
if(mc.interfaces != NULL){
2604
interfaces_hooks = malloc(mc.interfaces_size);
2605
if(interfaces_hooks == NULL){
2606
perror_plus("malloc");
1004
uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
1006
perror("Bad port number");
1007
exitcode = EXIT_FAILURE;
2609
memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
2610
argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
2612
run_network_hooks("start", interfaces_hooks != NULL ?
2613
interfaces_hooks : "", delay);
2617
avahi_set_log_function(empty_log);
2620
/* Initialize Avahi early so avahi_simple_poll_quit() can be called
2621
from the signal handler */
2622
/* Initialize the pseudo-RNG for Avahi */
2623
srand((unsigned int) time(NULL));
2624
simple_poll = avahi_simple_poll_new();
2625
if(simple_poll == NULL){
2626
fprintf_plus(stderr,
2627
"Avahi: Failed to create simple poll object.\n");
2628
exitcode = EX_UNAVAILABLE;
2632
sigemptyset(&sigterm_action.sa_mask);
2633
ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
2635
perror_plus("sigaddset");
2636
exitcode = EX_OSERR;
2639
ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
2641
perror_plus("sigaddset");
2642
exitcode = EX_OSERR;
2645
ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
2647
perror_plus("sigaddset");
2648
exitcode = EX_OSERR;
2651
/* Need to check if the handler is SIG_IGN before handling:
2652
| [[info:libc:Initial Signal Actions]] |
2653
| [[info:libc:Basic Signal Handling]] |
2655
ret = sigaction(SIGINT, NULL, &old_sigterm_action);
2657
perror_plus("sigaction");
2660
if(old_sigterm_action.sa_handler != SIG_IGN){
2661
ret = sigaction(SIGINT, &sigterm_action, NULL);
2663
perror_plus("sigaction");
2664
exitcode = EX_OSERR;
2668
ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
2670
perror_plus("sigaction");
2673
if(old_sigterm_action.sa_handler != SIG_IGN){
2674
ret = sigaction(SIGHUP, &sigterm_action, NULL);
2676
perror_plus("sigaction");
2677
exitcode = EX_OSERR;
2681
ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
2683
perror_plus("sigaction");
2686
if(old_sigterm_action.sa_handler != SIG_IGN){
2687
ret = sigaction(SIGTERM, &sigterm_action, NULL);
2689
perror_plus("sigaction");
2690
exitcode = EX_OSERR;
2695
/* If no interfaces were specified, make a list */
2696
if(mc.interfaces == NULL){
2697
struct dirent **direntries = NULL;
2698
/* Look for any good interfaces */
2699
ret = scandir(sys_class_net, &direntries, good_interface,
2702
/* Add all found interfaces to interfaces list */
2703
for(int i = 0; i < ret; ++i){
2704
ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
2705
direntries[i]->d_name);
2708
perror_plus("argz_add");
2709
free(direntries[i]);
2713
fprintf_plus(stderr, "Will use interface \"%s\"\n",
2714
direntries[i]->d_name);
2716
free(direntries[i]);
2723
fprintf_plus(stderr, "Could not find a network interface\n");
2724
exitcode = EXIT_FAILURE;
2729
/* Bring up interfaces which are down, and remove any "none"s */
2731
char *interface = NULL;
2732
while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2734
/* If interface name is "none", stop bringing up interfaces.
2735
Also remove all instances of "none" from the list */
2736
if(strcmp(interface, "none") == 0){
2737
argz_delete(&mc.interfaces, &mc.interfaces_size,
2740
while((interface = argz_next(mc.interfaces,
2741
mc.interfaces_size, interface))){
2742
if(strcmp(interface, "none") == 0){
2743
argz_delete(&mc.interfaces, &mc.interfaces_size,
2750
bool interface_was_up = interface_is_up(interface);
2751
errno = bring_up_interface(interface, delay);
2752
if(not interface_was_up){
2754
fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
2755
" %s\n", interface, strerror(errno));
2757
errno = argz_add(&interfaces_to_take_down,
2758
&interfaces_to_take_down_size,
2761
perror_plus("argz_add");
2766
if(debug and (interfaces_to_take_down == NULL)){
2767
fprintf_plus(stderr, "No interfaces were brought up\n");
2771
/* If we only got one interface, explicitly use only that one */
2772
if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
2774
fprintf_plus(stderr, "Using only interface \"%s\"\n",
2777
if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
2784
ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
2786
fprintf_plus(stderr, "init_gnutls_global failed\n");
2787
exitcode = EX_UNAVAILABLE;
2790
gnutls_initialized = true;
2797
/* Try /run/tmp before /tmp */
2798
tempdir = mkdtemp(run_tempdir);
2799
if(tempdir == NULL and errno == ENOENT){
2801
fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
2802
run_tempdir, old_tempdir);
2804
tempdir = mkdtemp(old_tempdir);
2806
if(tempdir == NULL){
2807
perror_plus("mkdtemp");
2815
if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
2816
fprintf_plus(stderr, "init_gpgme failed\n");
2817
exitcode = EX_UNAVAILABLE;
2820
gpgme_initialized = true;
2827
if(connect_to != NULL){
2828
/* Connect directly, do not use Zeroconf */
2829
/* (Mainly meant for debugging) */
2830
char *address = strrchr(connect_to, ':');
2832
if(address == NULL){
2833
fprintf_plus(stderr, "No colon in address\n");
2834
exitcode = EX_USAGE;
2844
tmpmax = strtoimax(address+1, &tmp, 10);
2845
if(errno != 0 or tmp == address+1 or *tmp != '\0'
2846
or tmpmax != (in_port_t)tmpmax){
2847
fprintf_plus(stderr, "Bad port number\n");
2848
exitcode = EX_USAGE;
2856
port = (in_port_t)tmpmax;
2858
/* Colon in address indicates IPv6 */
2860
if(strchr(connect_to, ':') != NULL){
2862
/* Accept [] around IPv6 address - see RFC 5952 */
2863
if(connect_to[0] == '[' and address[-1] == ']')
2871
address = connect_to;
2877
while(not quit_now){
2878
ret = start_mandos_communication(address, port, if_index, af,
2880
if(quit_now or ret == 0){
2884
fprintf_plus(stderr, "Retrying in %d seconds\n",
2885
(int)retry_interval);
2887
sleep((unsigned int)retry_interval);
2891
exitcode = EXIT_SUCCESS;
2902
AvahiServerConfig config;
2903
/* Do not publish any local Zeroconf records */
2904
avahi_server_config_init(&config);
2905
config.publish_hinfo = 0;
2906
config.publish_addresses = 0;
2907
config.publish_workstation = 0;
2908
config.publish_domain = 0;
2910
/* Allocate a new server */
2911
mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2912
&config, NULL, NULL, &ret);
2914
/* Free the Avahi configuration data */
2915
avahi_server_config_free(&config);
2918
/* Check if creating the Avahi server object succeeded */
2919
if(mc.server == NULL){
2920
fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2921
avahi_strerror(ret));
2922
exitcode = EX_UNAVAILABLE;
2930
/* Create the Avahi service browser */
2931
sb = avahi_s_service_browser_new(mc.server, if_index,
2932
AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2933
NULL, 0, browse_callback,
2936
fprintf_plus(stderr, "Failed to create service browser: %s\n",
2937
avahi_strerror(avahi_server_errno(mc.server)));
2938
exitcode = EX_UNAVAILABLE;
2946
/* Run the main loop */
2949
fprintf_plus(stderr, "Starting Avahi loop search\n");
2952
ret = avahi_loop_with_timeout(simple_poll,
2953
(int)(retry_interval * 1000), &mc);
2955
fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2956
(ret == 0) ? "successfully" : "with error");
1011
address = connect_to;
1012
ret = start_mandos_communication(address, port, if_index, &mc);
1014
exitcode = EXIT_FAILURE;
1016
exitcode = EXIT_SUCCESS;
1022
avahi_set_log_function(empty_log);
1025
/* Initialize the pseudo-RNG for Avahi */
1026
srand((unsigned int) time(NULL));
1028
/* Allocate main Avahi loop object */
1029
mc.simple_poll = avahi_simple_poll_new();
1030
if (mc.simple_poll == NULL) {
1031
fprintf(stderr, "Avahi: Failed to create simple poll"
1033
exitcode = EXIT_FAILURE;
1038
AvahiServerConfig config;
1039
/* Do not publish any local Zeroconf records */
1040
avahi_server_config_init(&config);
1041
config.publish_hinfo = 0;
1042
config.publish_addresses = 0;
1043
config.publish_workstation = 0;
1044
config.publish_domain = 0;
1046
/* Allocate a new server */
1047
mc.server = avahi_server_new(avahi_simple_poll_get
1048
(mc.simple_poll), &config, NULL,
1051
/* Free the Avahi configuration data */
1052
avahi_server_config_free(&config);
1055
/* Check if creating the Avahi server object succeeded */
1056
if (mc.server == NULL) {
1057
fprintf(stderr, "Failed to create Avahi server: %s\n",
1058
avahi_strerror(error));
1059
exitcode = EXIT_FAILURE;
1063
/* Create the Avahi service browser */
1064
sb = avahi_s_service_browser_new(mc.server, if_index,
1066
"_mandos._tcp", NULL, 0,
1067
browse_callback, &mc);
1069
fprintf(stderr, "Failed to create service browser: %s\n",
1070
avahi_strerror(avahi_server_errno(mc.server)));
1071
exitcode = EXIT_FAILURE;
1075
/* Run the main loop */
1078
fprintf(stderr, "Starting Avahi loop search\n");
1081
avahi_simple_poll_loop(mc.simple_poll);
2962
if(signal_received){
2963
fprintf_plus(stderr, "%s exiting due to signal %d: %s\n",
2964
argv[0], signal_received,
2965
strsignal(signal_received));
2967
fprintf_plus(stderr, "%s exiting\n", argv[0]);
2971
/* Cleanup things */
2972
free(mc.interfaces);
2975
avahi_s_service_browser_free(sb);
2977
if(mc.server != NULL)
2978
avahi_server_free(mc.server);
2980
if(simple_poll != NULL)
2981
avahi_simple_poll_free(simple_poll);
2983
if(gnutls_initialized){
2984
gnutls_certificate_free_credentials(mc.cred);
2985
gnutls_dh_params_deinit(mc.dh_params);
2988
if(gpgme_initialized){
2989
gpgme_release(mc.ctx);
2992
/* Cleans up the circular linked list of Mandos servers the client
2994
if(mc.current_server != NULL){
2995
mc.current_server->prev->next = NULL;
2996
while(mc.current_server != NULL){
2997
server *next = mc.current_server->next;
2999
#pragma GCC diagnostic push
3000
#pragma GCC diagnostic ignored "-Wcast-qual"
3002
free((char *)(mc.current_server->ip));
3004
#pragma GCC diagnostic pop
3006
free(mc.current_server);
3007
mc.current_server = next;
3011
/* Re-raise privileges */
3013
ret = raise_privileges();
3016
perror_plus("Failed to raise privileges");
3019
/* Run network hooks */
3020
run_network_hooks("stop", interfaces_hooks != NULL ?
3021
interfaces_hooks : "", delay);
3023
/* Take down the network interfaces which were brought up */
3025
char *interface = NULL;
3026
while((interface=argz_next(interfaces_to_take_down,
3027
interfaces_to_take_down_size,
3029
ret = take_down_interface(interface);
3032
perror_plus("Failed to take down interface");
3035
if(debug and (interfaces_to_take_down == NULL)){
3036
fprintf_plus(stderr, "No interfaces needed to be taken"
3042
ret = lower_privileges_permanently();
3045
perror_plus("Failed to lower privileges permanently");
3049
free(interfaces_to_take_down);
3050
free(interfaces_hooks);
3052
void clean_dir_at(int base, const char * const dirname,
3054
struct dirent **direntries = NULL;
3056
int dir_fd = (int)TEMP_FAILURE_RETRY(openat(base, dirname,
3062
perror_plus("open");
3064
int numentries = scandirat(dir_fd, ".", &direntries,
3065
notdotentries, alphasort);
3066
if(numentries >= 0){
3067
for(int i = 0; i < numentries; i++){
3069
fprintf_plus(stderr, "Unlinking \"%s/%s\"\n",
3070
dirname, direntries[i]->d_name);
3072
dret = unlinkat(dir_fd, direntries[i]->d_name, 0);
3074
if(errno == EISDIR){
3075
dret = unlinkat(dir_fd, direntries[i]->d_name,
3078
if((dret == -1) and (errno == ENOTEMPTY)
3079
and (strcmp(direntries[i]->d_name, "private-keys-v1.d")
3080
== 0) and (level == 0)){
3081
/* Recurse only in this special case */
3082
clean_dir_at(dir_fd, direntries[i]->d_name, level+1);
3086
fprintf_plus(stderr, "unlink(\"%s/%s\"): %s\n", dirname,
3087
direntries[i]->d_name, strerror(errno));
3090
free(direntries[i]);
3093
/* need to clean even if 0 because man page doesn't specify */
3095
if(numentries == -1){
3096
perror_plus("scandirat");
3098
dret = unlinkat(base, dirname, AT_REMOVEDIR);
3099
if(dret == -1 and errno != ENOENT){
3100
perror_plus("rmdir");
3103
perror_plus("scandirat");
3108
/* Removes the GPGME temp directory and all files inside */
3109
if(tempdir != NULL){
3110
clean_dir_at(-1, tempdir, 0);
3114
sigemptyset(&old_sigterm_action.sa_mask);
3115
old_sigterm_action.sa_handler = SIG_DFL;
3116
ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
3117
&old_sigterm_action,
3120
perror_plus("sigaction");
3123
ret = raise(signal_received);
3124
} while(ret != 0 and errno == EINTR);
3126
perror_plus("raise");
3129
TEMP_FAILURE_RETRY(pause());
1086
fprintf(stderr, "%s exiting\n", argv[0]);
1089
/* Cleanup things */
1091
avahi_s_service_browser_free(sb);
1093
if (mc.server != NULL)
1094
avahi_server_free(mc.server);
1096
if (mc.simple_poll != NULL)
1097
avahi_simple_poll_free(mc.simple_poll);
1099
if (gnutls_initalized){
1100
gnutls_certificate_free_credentials(mc.cred);
1101
gnutls_global_deinit ();
1102
gnutls_dh_params_deinit(mc.dh_params);
1105
if(gpgme_initalized){
1106
gpgme_release(mc.ctx);
1109
/* Removes the temp directory used by GPGME */
1110
if(tempdir[0] != '\0'){
1112
struct dirent *direntry;
1113
d = opendir(tempdir);
1118
direntry = readdir(d);
1119
if(direntry == NULL){
1122
if (direntry->d_type == DT_REG){
1123
char *fullname = NULL;
1124
ret = asprintf(&fullname, "%s/%s", tempdir,
1130
ret = unlink(fullname);
1132
fprintf(stderr, "unlink(\"%s\"): %s",
1133
fullname, strerror(errno));
1140
ret = rmdir(tempdir);