/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: Björn Påhlsson
  • Date: 2010-09-07 20:22:16 UTC
  • mto: (237.4.3 mandos-release)
  • mto: This revision was merged to the branch mainline in revision 421.
  • Revision ID: belorn@fukt.bsnet.se-20100907202216-vypcn3nsd02mqz4s
mandos-monitor: removed milisecondsseconds from countdown.

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-2011 Teddy Hogeborn
13
 
 * Copyright © 2008-2011 Björn Påhlsson
 
12
 * Copyright © 2008,2009 Teddy Hogeborn
 
13
 * Copyright © 2008,2009 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
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@recompile.se>.
 
29
 * Contact the authors at <mandos@fukt.bsnet.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
62
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
63
                                   strtoimax() */
64
64
#include <assert.h>             /* assert() */
65
 
#include <errno.h>              /* perror(), errno,
66
 
                                   program_invocation_short_name */
67
 
#include <time.h>               /* nanosleep(), time(), sleep() */
 
65
#include <errno.h>              /* perror(), errno */
 
66
#include <time.h>               /* nanosleep(), time() */
68
67
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
69
68
                                   SIOCSIFFLAGS, if_indextoname(),
70
69
                                   if_nametoindex(), IF_NAMESIZE */
74
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
74
                                   getuid(), getgid(), seteuid(),
76
75
                                   setgid(), pause() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
76
#include <arpa/inet.h>          /* inet_pton(), htons */
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,
127
126
bool debug = false;
128
127
static const char mandos_protocol_version[] = "1";
129
128
const char *argp_program_version = "mandos-client " VERSION;
130
 
const char *argp_program_bug_address = "<mandos@recompile.se>";
131
 
static const char sys_class_net[] = "/sys/class/net";
132
 
char *connect_to = NULL;
133
 
 
134
 
/* Doubly linked list that need to be circularly linked when used */
135
 
typedef struct server{
136
 
  const char *ip;
137
 
  uint16_t port;
138
 
  AvahiIfIndex if_index;
139
 
  int af;
140
 
  struct timespec last_seen;
141
 
  struct server *next;
142
 
  struct server *prev;
143
 
} server;
 
129
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
144
130
 
145
131
/* Used for passing in values through the Avahi callback functions */
146
132
typedef struct {
151
137
  gnutls_dh_params_t dh_params;
152
138
  const char *priority;
153
139
  gpgme_ctx_t ctx;
154
 
  server *current_server;
155
140
} mandos_context;
156
141
 
157
142
/* global context so signal handler can reach it*/
158
143
mandos_context mc = { .simple_poll = NULL, .server = NULL,
159
144
                      .dh_bits = 1024, .priority = "SECURE256"
160
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
161
 
                      .current_server = NULL };
 
145
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
162
146
 
163
147
sig_atomic_t quit_now = 0;
164
148
int signal_received = 0;
165
149
 
166
 
/* Function to use when printing errors */
167
 
void perror_plus(const char *print_text){
168
 
  fprintf(stderr, "Mandos plugin %s: ",
169
 
          program_invocation_short_name);
170
 
  perror(print_text);
171
 
}
172
 
 
173
150
/*
174
151
 * Make additional room in "buffer" for at least BUFFER_SIZE more
175
152
 * bytes. "buffer_capacity" is how much is currently allocated,
187
164
  return buffer_capacity;
188
165
}
189
166
 
190
 
/* Add server to set of servers to retry periodically */
191
 
int add_server(const char *ip, uint16_t port,
192
 
                 AvahiIfIndex if_index,
193
 
                 int af){
194
 
  int ret;
195
 
  server *new_server = malloc(sizeof(server));
196
 
  if(new_server == NULL){
197
 
    perror_plus("malloc");
198
 
    return -1;
199
 
  }
200
 
  *new_server = (server){ .ip = strdup(ip),
201
 
                         .port = port,
202
 
                         .if_index = if_index,
203
 
                         .af = af };
204
 
  if(new_server->ip == NULL){
205
 
    perror_plus("strdup");
206
 
    return -1;
207
 
  }
208
 
  /* Special case of first server */
209
 
  if (mc.current_server == NULL){
210
 
    new_server->next = new_server;
211
 
    new_server->prev = new_server;
212
 
    mc.current_server = new_server;
213
 
  /* Place the new server last in the list */
214
 
  } else {
215
 
    new_server->next = mc.current_server;
216
 
    new_server->prev = mc.current_server->prev;
217
 
    new_server->prev->next = new_server;
218
 
    mc.current_server->prev = new_server;
219
 
  }
220
 
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
221
 
  if(ret == -1){
222
 
    perror_plus("clock_gettime");
223
 
    return -1;
224
 
  }
225
 
  return 0;
226
 
}
227
 
 
228
167
/* 
229
168
 * Initialize GPGME.
230
169
 */
244
183
    
245
184
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
246
185
    if(fd == -1){
247
 
      perror_plus("open");
 
186
      perror("open");
248
187
      return false;
249
188
    }
250
189
    
264
203
    
265
204
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
266
205
    if(ret == -1){
267
 
      perror_plus("close");
 
206
      perror("close");
268
207
    }
269
208
    gpgme_data_release(pgp_data);
270
209
    return true;
283
222
    return false;
284
223
  }
285
224
  
286
 
  /* Set GPGME home directory for the OpenPGP engine only */
 
225
    /* Set GPGME home directory for the OpenPGP engine only */
287
226
  rc = gpgme_get_engine_info(&engine_info);
288
227
  if(rc != GPG_ERR_NO_ERROR){
289
228
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
395
334
  
396
335
  /* Seek back to the beginning of the GPGME plaintext data buffer */
397
336
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
398
 
    perror_plus("gpgme_data_seek");
 
337
    perror("gpgme_data_seek");
399
338
    plaintext_length = -1;
400
339
    goto decrypt_end;
401
340
  }
406
345
                                      (size_t)plaintext_length,
407
346
                                      plaintext_capacity);
408
347
    if(plaintext_capacity == 0){
409
 
        perror_plus("incbuffer");
 
348
        perror("incbuffer");
410
349
        plaintext_length = -1;
411
350
        goto decrypt_end;
412
351
    }
419
358
      break;
420
359
    }
421
360
    if(ret < 0){
422
 
      perror_plus("gpgme_data_read");
 
361
      perror("gpgme_data_read");
423
362
      plaintext_length = -1;
424
363
      goto decrypt_end;
425
364
    }
482
421
  }
483
422
  
484
423
  /* OpenPGP credentials */
485
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
424
  gnutls_certificate_allocate_credentials(&mc.cred);
486
425
  if(ret != GNUTLS_E_SUCCESS){
487
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
 
426
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
 
427
                                                    from
 
428
                                                    -Wunreachable-code
 
429
                                                 */
488
430
            safer_gnutls_strerror(ret));
489
431
    gnutls_global_deinit();
490
432
    return -1;
645
587
  tcp_sd = socket(pf, SOCK_STREAM, 0);
646
588
  if(tcp_sd < 0){
647
589
    int e = errno;
648
 
    perror_plus("socket");
 
590
    perror("socket");
649
591
    errno = e;
650
592
    goto mandos_end;
651
593
  }
665
607
  }
666
608
  if(ret < 0 ){
667
609
    int e = errno;
668
 
    perror_plus("inet_pton");
 
610
    perror("inet_pton");
669
611
    errno = e;
670
612
    goto mandos_end;
671
613
  }
707
649
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
708
650
      char interface[IF_NAMESIZE];
709
651
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
710
 
        perror_plus("if_indextoname");
 
652
        perror("if_indextoname");
711
653
      } else {
712
654
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
713
655
                ip, interface, port);
727
669
                        sizeof(addrstr));
728
670
    }
729
671
    if(pcret == NULL){
730
 
      perror_plus("inet_ntop");
 
672
      perror("inet_ntop");
731
673
    } else {
732
674
      if(strcmp(addrstr, ip) != 0){
733
675
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
746
688
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
747
689
  }
748
690
  if(ret < 0){
749
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
750
 
      int e = errno;
751
 
      perror_plus("connect");
752
 
      errno = e;
753
 
    }
 
691
    int e = errno;
 
692
    perror("connect");
 
693
    errno = e;
754
694
    goto mandos_end;
755
695
  }
756
696
  
767
707
                                   out_size - written));
768
708
    if(ret == -1){
769
709
      int e = errno;
770
 
      perror_plus("write");
 
710
      perror("write");
771
711
      errno = e;
772
712
      goto mandos_end;
773
713
    }
798
738
    goto mandos_end;
799
739
  }
800
740
  
801
 
  /* Spurious warning from -Wint-to-pointer-cast */
802
741
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
803
742
  
804
743
  if(quit_now){
841
780
                                   buffer_capacity);
842
781
    if(buffer_capacity == 0){
843
782
      int e = errno;
844
 
      perror_plus("incbuffer");
 
783
      perror("incbuffer");
845
784
      errno = e;
846
785
      goto mandos_end;
847
786
    }
952
891
      if(e == 0){
953
892
        e = errno;
954
893
      }
955
 
      perror_plus("close");
 
894
      perror("close");
956
895
    }
957
896
    gnutls_deinit(session);
958
 
    errno = e;
959
897
    if(quit_now){
960
 
      errno = EINTR;
 
898
      e = EINTR;
961
899
      retval = -1;
962
900
    }
 
901
    errno = e;
963
902
  }
964
903
  return retval;
965
904
}
1008
947
                                           avahi_proto_to_af(proto));
1009
948
      if(ret == 0){
1010
949
        avahi_simple_poll_quit(mc.simple_poll);
1011
 
      } else {
1012
 
        ret = add_server(ip, port, interface,
1013
 
                         avahi_proto_to_af(proto));
1014
950
      }
1015
951
    }
1016
952
  }
1070
1006
  }
1071
1007
}
1072
1008
 
1073
 
/* Signal handler that stops main loop after SIGTERM */
 
1009
/* stop main loop after sigterm has been called */
1074
1010
static void handle_sigterm(int sig){
1075
1011
  if(quit_now){
1076
1012
    return;
1078
1014
  quit_now = 1;
1079
1015
  signal_received = sig;
1080
1016
  int old_errno = errno;
1081
 
  /* set main loop to exit */
1082
1017
  if(mc.simple_poll != NULL){
1083
1018
    avahi_simple_poll_quit(mc.simple_poll);
1084
1019
  }
1085
1020
  errno = old_errno;
1086
1021
}
1087
1022
 
1088
 
bool get_flags(const char *ifname, struct ifreq *ifr){
1089
 
  int ret;
1090
 
  
1091
 
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1092
 
  if(s < 0){
1093
 
    perror_plus("socket");
1094
 
    return false;
1095
 
  }
1096
 
  strcpy(ifr->ifr_name, ifname);
1097
 
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1098
 
  if(ret == -1){
1099
 
    if(debug){
1100
 
      perror_plus("ioctl SIOCGIFFLAGS");
1101
 
    }
1102
 
    return false;
1103
 
  }
1104
 
  return true;
1105
 
}
1106
 
 
1107
 
bool good_flags(const char *ifname, const struct ifreq *ifr){
1108
 
  
1109
 
  /* Reject the loopback device */
1110
 
  if(ifr->ifr_flags & IFF_LOOPBACK){
1111
 
    if(debug){
1112
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1113
 
              ifname);
1114
 
    }
1115
 
    return false;
1116
 
  }
1117
 
  /* Accept point-to-point devices only if connect_to is specified */
1118
 
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1119
 
    if(debug){
1120
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1121
 
              ifname);
1122
 
    }
1123
 
    return true;
1124
 
  }
1125
 
  /* Otherwise, reject non-broadcast-capable devices */
1126
 
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1127
 
    if(debug){
1128
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1129
 
              ifname);
1130
 
    }
1131
 
    return false;
1132
 
  }
1133
 
  /* Reject non-ARP interfaces (including dummy interfaces) */
1134
 
  if(ifr->ifr_flags & IFF_NOARP){
1135
 
    if(debug){
1136
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
1137
 
    }
1138
 
    return false;
1139
 
  }
1140
 
  
1141
 
  /* Accept this device */
1142
 
  if(debug){
1143
 
    fprintf(stderr, "Interface \"%s\" is good\n", ifname);
1144
 
  }
1145
 
  return true;
1146
 
}
1147
 
 
1148
 
/* 
1149
 
 * This function determines if a directory entry in /sys/class/net
1150
 
 * corresponds to an acceptable network device.
1151
 
 * (This function is passed to scandir(3) as a filter function.)
1152
 
 */
1153
 
int good_interface(const struct dirent *if_entry){
1154
 
  int ret;
1155
 
  if(if_entry->d_name[0] == '.'){
1156
 
    return 0;
1157
 
  }
1158
 
  struct ifreq ifr;
1159
 
 
1160
 
  if(not get_flags(if_entry->d_name, &ifr)){
1161
 
    return 0;
1162
 
  }
1163
 
  
1164
 
  if(not good_flags(if_entry->d_name, &ifr)){
1165
 
    return 0;
1166
 
  }
1167
 
  return 1;
1168
 
}
1169
 
 
1170
 
int notdotentries(const struct dirent *direntry){
1171
 
  /* Skip "." and ".." */
1172
 
  if(direntry->d_name[0] == '.'
1173
 
     and (direntry->d_name[1] == '\0'
1174
 
          or (direntry->d_name[1] == '.'
1175
 
              and direntry->d_name[2] == '\0'))){
1176
 
    return 0;
1177
 
  }
1178
 
  return 1;
1179
 
}
1180
 
 
1181
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1182
 
  int ret;
1183
 
  struct timespec now;
1184
 
  struct timespec waited_time;
1185
 
  intmax_t block_time;
1186
 
  
1187
 
  while(true){
1188
 
    if(mc.current_server == NULL){
1189
 
      if (debug){
1190
 
        fprintf(stderr,
1191
 
                "Wait until first server is found. No timeout!\n");
1192
 
      }
1193
 
      ret = avahi_simple_poll_iterate(s, -1);
1194
 
    } else {
1195
 
      if (debug){
1196
 
        fprintf(stderr, "Check current_server if we should run it,"
1197
 
                " or wait\n");
1198
 
      }
1199
 
      /* the current time */
1200
 
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1201
 
      if(ret == -1){
1202
 
        perror_plus("clock_gettime");
1203
 
        return -1;
1204
 
      }
1205
 
      /* Calculating in ms how long time between now and server
1206
 
         who we visted longest time ago. Now - last seen.  */
1207
 
      waited_time.tv_sec = (now.tv_sec
1208
 
                            - mc.current_server->last_seen.tv_sec);
1209
 
      waited_time.tv_nsec = (now.tv_nsec
1210
 
                             - mc.current_server->last_seen.tv_nsec);
1211
 
      /* total time is 10s/10,000ms.
1212
 
         Converting to s from ms by dividing by 1,000,
1213
 
         and ns to ms by dividing by 1,000,000. */
1214
 
      block_time = ((retry_interval
1215
 
                     - ((intmax_t)waited_time.tv_sec * 1000))
1216
 
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1217
 
      
1218
 
      if (debug){
1219
 
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
1220
 
      }
1221
 
      
1222
 
      if(block_time <= 0){
1223
 
        ret = start_mandos_communication(mc.current_server->ip,
1224
 
                                         mc.current_server->port,
1225
 
                                         mc.current_server->if_index,
1226
 
                                         mc.current_server->af);
1227
 
        if(ret == 0){
1228
 
          avahi_simple_poll_quit(mc.simple_poll);
1229
 
          return 0;
1230
 
        }
1231
 
        ret = clock_gettime(CLOCK_MONOTONIC,
1232
 
                            &mc.current_server->last_seen);
1233
 
        if(ret == -1){
1234
 
          perror_plus("clock_gettime");
1235
 
          return -1;
1236
 
        }
1237
 
        mc.current_server = mc.current_server->next;
1238
 
        block_time = 0;         /* Call avahi to find new Mandos
1239
 
                                   servers, but don't block */
1240
 
      }
1241
 
      
1242
 
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1243
 
    }
1244
 
    if(ret != 0){
1245
 
      if (ret > 0 or errno != EINTR) {
1246
 
        return (ret != 1) ? ret : 0;
1247
 
      }
1248
 
    }
1249
 
  }
1250
 
}
1251
 
 
1252
1023
int main(int argc, char *argv[]){
1253
1024
  AvahiSServiceBrowser *sb = NULL;
1254
1025
  int error;
1256
1027
  intmax_t tmpmax;
1257
1028
  char *tmp;
1258
1029
  int exitcode = EXIT_SUCCESS;
1259
 
  const char *interface = "";
 
1030
  const char *interface = "eth0";
1260
1031
  struct ifreq network;
1261
1032
  int sd = -1;
1262
1033
  bool take_down_interface = false;
1263
1034
  uid_t uid;
1264
1035
  gid_t gid;
 
1036
  char *connect_to = NULL;
1265
1037
  char tempdir[] = "/tmp/mandosXXXXXX";
1266
1038
  bool tempdir_created = false;
1267
1039
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1271
1043
  bool gnutls_initialized = false;
1272
1044
  bool gpgme_initialized = false;
1273
1045
  float delay = 2.5f;
1274
 
  double retry_interval = 10; /* 10s between trying a server and
1275
 
                                 retrying the same server again */
1276
1046
  
1277
1047
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1278
1048
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1284
1054
  errno = 0;
1285
1055
  ret = setgid(gid);
1286
1056
  if(ret == -1){
1287
 
    perror_plus("setgid");
 
1057
    perror("setgid");
1288
1058
  }
1289
1059
  
1290
1060
  /* Lower user privileges (temporarily) */
1291
1061
  errno = 0;
1292
1062
  ret = seteuid(uid);
1293
1063
  if(ret == -1){
1294
 
    perror_plus("seteuid");
 
1064
    perror("seteuid");
1295
1065
  }
1296
1066
  
1297
1067
  if(quit_now){
1332
1102
        .arg = "SECONDS",
1333
1103
        .doc = "Maximum delay to wait for interface startup",
1334
1104
        .group = 2 },
1335
 
      { .name = "retry", .key = 132,
1336
 
        .arg = "SECONDS",
1337
 
        .doc = "Retry interval used when denied by the mandos server",
1338
 
        .group = 2 },
1339
1105
      /*
1340
1106
       * These reproduce what we would get without ARGP_NO_HELP
1341
1107
       */
1385
1151
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1386
1152
          argp_error(state, "Bad delay");
1387
1153
        }
1388
 
      case 132:                 /* --retry */
1389
 
        errno = 0;
1390
 
        retry_interval = strtod(arg, &tmp);
1391
 
        if(errno != 0 or tmp == arg or *tmp != '\0'
1392
 
           or (retry_interval * 1000) > INT_MAX
1393
 
           or retry_interval < 0){
1394
 
          argp_error(state, "Bad retry interval");
1395
 
        }
1396
1154
        break;
1397
1155
        /*
1398
1156
         * These reproduce what we would get without ARGP_NO_HELP
1426
1184
    case ENOMEM:
1427
1185
    default:
1428
1186
      errno = ret;
1429
 
      perror_plus("argp_parse");
 
1187
      perror("argp_parse");
1430
1188
      exitcode = EX_OSERR;
1431
1189
      goto end;
1432
1190
    case EINVAL:
1434
1192
      goto end;
1435
1193
    }
1436
1194
  }
1437
 
    
1438
 
  {
1439
 
    /* Work around Debian bug #633582:
1440
 
       <http://bugs.debian.org/633582> */
1441
 
    struct stat st;
1442
 
    
1443
 
    /* Re-raise priviliges */
1444
 
    errno = 0;
1445
 
    ret = seteuid(0);
1446
 
    if(ret == -1){
1447
 
      perror_plus("seteuid");
1448
 
    }
1449
 
    
1450
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1451
 
      int seckey_fd = open(seckey, O_RDONLY);
1452
 
      if(seckey_fd == -1){
1453
 
        perror_plus("open");
1454
 
      } else {
1455
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1456
 
        if(ret == -1){
1457
 
          perror_plus("fstat");
1458
 
        } else {
1459
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1460
 
            ret = fchown(seckey_fd, uid, gid);
1461
 
            if(ret == -1){
1462
 
              perror_plus("fchown");
1463
 
            }
1464
 
          }
1465
 
        }
1466
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1467
 
      }
1468
 
    }
1469
 
    
1470
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1471
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1472
 
      if(pubkey_fd == -1){
1473
 
        perror_plus("open");
1474
 
      } else {
1475
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1476
 
        if(ret == -1){
1477
 
          perror_plus("fstat");
1478
 
        } else {
1479
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1480
 
            ret = fchown(pubkey_fd, uid, gid);
1481
 
            if(ret == -1){
1482
 
              perror_plus("fchown");
1483
 
            }
1484
 
          }
1485
 
        }
1486
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1487
 
      }
1488
 
    }
1489
 
    
1490
 
    /* Lower privileges */
1491
 
    errno = 0;
1492
 
    ret = seteuid(uid);
1493
 
    if(ret == -1){
1494
 
      perror_plus("seteuid");
1495
 
    }
1496
 
  }
1497
1195
  
1498
1196
  if(not debug){
1499
1197
    avahi_set_log_function(empty_log);
1500
1198
  }
1501
 
 
1502
 
  if(interface[0] == '\0'){
1503
 
    struct dirent **direntries;
1504
 
    ret = scandir(sys_class_net, &direntries, good_interface,
1505
 
                  alphasort);
1506
 
    if(ret >= 1){
1507
 
      /* Pick the first good interface */
1508
 
      interface = strdup(direntries[0]->d_name);
1509
 
      if(debug){
1510
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1511
 
      }
1512
 
      if(interface == NULL){
1513
 
        perror_plus("malloc");
1514
 
        free(direntries);
1515
 
        exitcode = EXIT_FAILURE;
1516
 
        goto end;
1517
 
      }
1518
 
      free(direntries);
1519
 
    } else {
1520
 
      free(direntries);
1521
 
      fprintf(stderr, "Could not find a network interface\n");
1522
 
      exitcode = EXIT_FAILURE;
1523
 
      goto end;
1524
 
    }
1525
 
  }
1526
1199
  
1527
1200
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1528
1201
     from the signal handler */
1538
1211
  sigemptyset(&sigterm_action.sa_mask);
1539
1212
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1540
1213
  if(ret == -1){
1541
 
    perror_plus("sigaddset");
 
1214
    perror("sigaddset");
1542
1215
    exitcode = EX_OSERR;
1543
1216
    goto end;
1544
1217
  }
1545
1218
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1546
1219
  if(ret == -1){
1547
 
    perror_plus("sigaddset");
 
1220
    perror("sigaddset");
1548
1221
    exitcode = EX_OSERR;
1549
1222
    goto end;
1550
1223
  }
1551
1224
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1552
1225
  if(ret == -1){
1553
 
    perror_plus("sigaddset");
 
1226
    perror("sigaddset");
1554
1227
    exitcode = EX_OSERR;
1555
1228
    goto end;
1556
1229
  }
1560
1233
  */
1561
1234
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1562
1235
  if(ret == -1){
1563
 
    perror_plus("sigaction");
 
1236
    perror("sigaction");
1564
1237
    return EX_OSERR;
1565
1238
  }
1566
1239
  if(old_sigterm_action.sa_handler != SIG_IGN){
1567
1240
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1568
1241
    if(ret == -1){
1569
 
      perror_plus("sigaction");
 
1242
      perror("sigaction");
1570
1243
      exitcode = EX_OSERR;
1571
1244
      goto end;
1572
1245
    }
1573
1246
  }
1574
1247
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1575
1248
  if(ret == -1){
1576
 
    perror_plus("sigaction");
 
1249
    perror("sigaction");
1577
1250
    return EX_OSERR;
1578
1251
  }
1579
1252
  if(old_sigterm_action.sa_handler != SIG_IGN){
1580
1253
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1581
1254
    if(ret == -1){
1582
 
      perror_plus("sigaction");
 
1255
      perror("sigaction");
1583
1256
      exitcode = EX_OSERR;
1584
1257
      goto end;
1585
1258
    }
1586
1259
  }
1587
1260
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1588
1261
  if(ret == -1){
1589
 
    perror_plus("sigaction");
 
1262
    perror("sigaction");
1590
1263
    return EX_OSERR;
1591
1264
  }
1592
1265
  if(old_sigterm_action.sa_handler != SIG_IGN){
1593
1266
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1594
1267
    if(ret == -1){
1595
 
      perror_plus("sigaction");
 
1268
      perror("sigaction");
1596
1269
      exitcode = EX_OSERR;
1597
1270
      goto end;
1598
1271
    }
1599
1272
  }
1600
1273
  
1601
1274
  /* If the interface is down, bring it up */
1602
 
  if(strcmp(interface, "none") != 0){
 
1275
  if(interface[0] != '\0'){
1603
1276
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1604
1277
    if(if_index == 0){
1605
1278
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1615
1288
    errno = 0;
1616
1289
    ret = seteuid(0);
1617
1290
    if(ret == -1){
1618
 
      perror_plus("seteuid");
 
1291
      perror("seteuid");
1619
1292
    }
1620
1293
    
1621
1294
#ifdef __linux__
1625
1298
    bool restore_loglevel = true;
1626
1299
    if(ret == -1){
1627
1300
      restore_loglevel = false;
1628
 
      perror_plus("klogctl");
 
1301
      perror("klogctl");
1629
1302
    }
1630
1303
#endif  /* __linux__ */
1631
1304
    
1632
1305
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1633
1306
    if(sd < 0){
1634
 
      perror_plus("socket");
 
1307
      perror("socket");
1635
1308
      exitcode = EX_OSERR;
1636
1309
#ifdef __linux__
1637
1310
      if(restore_loglevel){
1638
1311
        ret = klogctl(7, NULL, 0);
1639
1312
        if(ret == -1){
1640
 
          perror_plus("klogctl");
 
1313
          perror("klogctl");
1641
1314
        }
1642
1315
      }
1643
1316
#endif  /* __linux__ */
1645
1318
      errno = 0;
1646
1319
      ret = seteuid(uid);
1647
1320
      if(ret == -1){
1648
 
        perror_plus("seteuid");
 
1321
        perror("seteuid");
1649
1322
      }
1650
1323
      goto end;
1651
1324
    }
1652
1325
    strcpy(network.ifr_name, interface);
1653
1326
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1654
1327
    if(ret == -1){
1655
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1328
      perror("ioctl SIOCGIFFLAGS");
1656
1329
#ifdef __linux__
1657
1330
      if(restore_loglevel){
1658
1331
        ret = klogctl(7, NULL, 0);
1659
1332
        if(ret == -1){
1660
 
          perror_plus("klogctl");
 
1333
          perror("klogctl");
1661
1334
        }
1662
1335
      }
1663
1336
#endif  /* __linux__ */
1666
1339
      errno = 0;
1667
1340
      ret = seteuid(uid);
1668
1341
      if(ret == -1){
1669
 
        perror_plus("seteuid");
 
1342
        perror("seteuid");
1670
1343
      }
1671
1344
      goto end;
1672
1345
    }
1676
1349
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1677
1350
      if(ret == -1){
1678
1351
        take_down_interface = false;
1679
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1352
        perror("ioctl SIOCSIFFLAGS");
1680
1353
        exitcode = EX_OSERR;
1681
1354
#ifdef __linux__
1682
1355
        if(restore_loglevel){
1683
1356
          ret = klogctl(7, NULL, 0);
1684
1357
          if(ret == -1){
1685
 
            perror_plus("klogctl");
 
1358
            perror("klogctl");
1686
1359
          }
1687
1360
        }
1688
1361
#endif  /* __linux__ */
1690
1363
        errno = 0;
1691
1364
        ret = seteuid(uid);
1692
1365
        if(ret == -1){
1693
 
          perror_plus("seteuid");
 
1366
          perror("seteuid");
1694
1367
        }
1695
1368
        goto end;
1696
1369
      }
1697
1370
    }
1698
 
    /* Sleep checking until interface is running.
1699
 
       Check every 0.25s, up to total time of delay */
 
1371
    /* sleep checking until interface is running */
1700
1372
    for(int i=0; i < delay * 4; i++){
1701
1373
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1702
1374
      if(ret == -1){
1703
 
        perror_plus("ioctl SIOCGIFFLAGS");
 
1375
        perror("ioctl SIOCGIFFLAGS");
1704
1376
      } else if(network.ifr_flags & IFF_RUNNING){
1705
1377
        break;
1706
1378
      }
1707
1379
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1708
1380
      ret = nanosleep(&sleeptime, NULL);
1709
1381
      if(ret == -1 and errno != EINTR){
1710
 
        perror_plus("nanosleep");
 
1382
        perror("nanosleep");
1711
1383
      }
1712
1384
    }
1713
1385
    if(not take_down_interface){
1714
1386
      /* We won't need the socket anymore */
1715
1387
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1716
1388
      if(ret == -1){
1717
 
        perror_plus("close");
 
1389
        perror("close");
1718
1390
      }
1719
1391
    }
1720
1392
#ifdef __linux__
1722
1394
      /* Restores kernel loglevel to default */
1723
1395
      ret = klogctl(7, NULL, 0);
1724
1396
      if(ret == -1){
1725
 
        perror_plus("klogctl");
 
1397
        perror("klogctl");
1726
1398
      }
1727
1399
    }
1728
1400
#endif  /* __linux__ */
1732
1404
      /* Lower privileges */
1733
1405
      ret = seteuid(uid);
1734
1406
      if(ret == -1){
1735
 
        perror_plus("seteuid");
 
1407
        perror("seteuid");
1736
1408
      }
1737
1409
    } else {
1738
1410
      /* Lower privileges permanently */
1739
1411
      ret = setuid(uid);
1740
1412
      if(ret == -1){
1741
 
        perror_plus("setuid");
 
1413
        perror("setuid");
1742
1414
      }
1743
1415
    }
1744
1416
  }
1760
1432
    goto end;
1761
1433
  }
1762
1434
  
 
1435
  tempdir_created = true;
1763
1436
  if(mkdtemp(tempdir) == NULL){
1764
 
    perror_plus("mkdtemp");
 
1437
    tempdir_created = false;
 
1438
    perror("mkdtemp");
1765
1439
    goto end;
1766
1440
  }
1767
 
  tempdir_created = true;
1768
1441
  
1769
1442
  if(quit_now){
1770
1443
    goto end;
1812
1485
    
1813
1486
    port = (uint16_t)tmpmax;
1814
1487
    *address = '\0';
 
1488
    address = connect_to;
1815
1489
    /* Colon in address indicates IPv6 */
1816
1490
    int af;
1817
 
    if(strchr(connect_to, ':') != NULL){
 
1491
    if(strchr(address, ':') != NULL){
1818
1492
      af = AF_INET6;
1819
 
      /* Accept [] around IPv6 address - see RFC 5952 */
1820
 
      if(connect_to[0] == '[' and address[-1] == ']')
1821
 
        {
1822
 
          connect_to++;
1823
 
          address[-1] = '\0';
1824
 
        }
1825
1493
    } else {
1826
1494
      af = AF_INET;
1827
1495
    }
1828
 
    address = connect_to;
1829
1496
    
1830
1497
    if(quit_now){
1831
1498
      goto end;
1832
1499
    }
1833
1500
    
1834
 
    while(not quit_now){
1835
 
      ret = start_mandos_communication(address, port, if_index, af);
1836
 
      if(quit_now or ret == 0){
1837
 
        break;
1838
 
      }
1839
 
      if(debug){
1840
 
        fprintf(stderr, "Retrying in %d seconds\n",
1841
 
                (int)retry_interval);
1842
 
      }
1843
 
      sleep((int)retry_interval);
1844
 
    }
1845
 
    
1846
 
    if (not quit_now){
 
1501
    ret = start_mandos_communication(address, port, if_index, af);
 
1502
    if(ret < 0){
 
1503
      switch(errno){
 
1504
      case ENETUNREACH:
 
1505
      case EHOSTDOWN:
 
1506
      case EHOSTUNREACH:
 
1507
        exitcode = EX_NOHOST;
 
1508
        break;
 
1509
      case EINVAL:
 
1510
        exitcode = EX_USAGE;
 
1511
        break;
 
1512
      case EIO:
 
1513
        exitcode = EX_IOERR;
 
1514
        break;
 
1515
      case EPROTO:
 
1516
        exitcode = EX_PROTOCOL;
 
1517
        break;
 
1518
      default:
 
1519
        exitcode = EX_OSERR;
 
1520
        break;
 
1521
      }
 
1522
    } else {
1847
1523
      exitcode = EXIT_SUCCESS;
1848
1524
    }
1849
 
 
1850
1525
    goto end;
1851
1526
  }
1852
1527
  
1904
1579
  if(debug){
1905
1580
    fprintf(stderr, "Starting Avahi loop search\n");
1906
1581
  }
1907
 
 
1908
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
1909
 
                                (int)(retry_interval * 1000));
1910
 
  if(debug){
1911
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
1912
 
            (ret == 0) ? "successfully" : "with error");
1913
 
  }
 
1582
  
 
1583
  avahi_simple_poll_loop(mc.simple_poll);
1914
1584
  
1915
1585
 end:
1916
1586
  
1937
1607
  if(gpgme_initialized){
1938
1608
    gpgme_release(mc.ctx);
1939
1609
  }
1940
 
 
1941
 
  /* Cleans up the circular linked list of Mandos servers the client
1942
 
     has seen */
1943
 
  if(mc.current_server != NULL){
1944
 
    mc.current_server->prev->next = NULL;
1945
 
    while(mc.current_server != NULL){
1946
 
      server *next = mc.current_server->next;
1947
 
      free(mc.current_server);
1948
 
      mc.current_server = next;
1949
 
    }
1950
 
  }
1951
1610
  
1952
1611
  /* Take down the network interface */
1953
1612
  if(take_down_interface){
1955
1614
    errno = 0;
1956
1615
    ret = seteuid(0);
1957
1616
    if(ret == -1){
1958
 
      perror_plus("seteuid");
 
1617
      perror("seteuid");
1959
1618
    }
1960
1619
    if(geteuid() == 0){
1961
1620
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1962
1621
      if(ret == -1){
1963
 
        perror_plus("ioctl SIOCGIFFLAGS");
 
1622
        perror("ioctl SIOCGIFFLAGS");
1964
1623
      } else if(network.ifr_flags & IFF_UP) {
1965
1624
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1966
1625
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1967
1626
        if(ret == -1){
1968
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1627
          perror("ioctl SIOCSIFFLAGS");
1969
1628
        }
1970
1629
      }
1971
1630
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1972
1631
      if(ret == -1){
1973
 
        perror_plus("close");
 
1632
        perror("close");
1974
1633
      }
1975
1634
      /* Lower privileges permanently */
1976
1635
      errno = 0;
1977
1636
      ret = setuid(uid);
1978
1637
      if(ret == -1){
1979
 
        perror_plus("setuid");
 
1638
        perror("setuid");
1980
1639
      }
1981
1640
    }
1982
1641
  }
1983
1642
  
1984
 
  /* Removes the GPGME temp directory and all files inside */
 
1643
  /* Removes the temp directory used by GPGME */
1985
1644
  if(tempdir_created){
1986
 
    struct dirent **direntries = NULL;
1987
 
    struct dirent *direntry = NULL;
1988
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
1989
 
                             alphasort);
1990
 
    if (numentries > 0){
1991
 
      for(int i = 0; i < numentries; i++){
1992
 
        direntry = direntries[i];
 
1645
    DIR *d;
 
1646
    struct dirent *direntry;
 
1647
    d = opendir(tempdir);
 
1648
    if(d == NULL){
 
1649
      if(errno != ENOENT){
 
1650
        perror("opendir");
 
1651
      }
 
1652
    } else {
 
1653
      while(true){
 
1654
        direntry = readdir(d);
 
1655
        if(direntry == NULL){
 
1656
          break;
 
1657
        }
 
1658
        /* Skip "." and ".." */
 
1659
        if(direntry->d_name[0] == '.'
 
1660
           and (direntry->d_name[1] == '\0'
 
1661
                or (direntry->d_name[1] == '.'
 
1662
                    and direntry->d_name[2] == '\0'))){
 
1663
          continue;
 
1664
        }
1993
1665
        char *fullname = NULL;
1994
1666
        ret = asprintf(&fullname, "%s/%s", tempdir,
1995
1667
                       direntry->d_name);
1996
1668
        if(ret < 0){
1997
 
          perror_plus("asprintf");
 
1669
          perror("asprintf");
1998
1670
          continue;
1999
1671
        }
2000
1672
        ret = remove(fullname);
2004
1676
        }
2005
1677
        free(fullname);
2006
1678
      }
2007
 
    }
2008
 
 
2009
 
    /* need to clean even if 0 because man page doesn't specify */
2010
 
    free(direntries);
2011
 
    if (numentries == -1){
2012
 
      perror_plus("scandir");
 
1679
      closedir(d);
2013
1680
    }
2014
1681
    ret = rmdir(tempdir);
2015
1682
    if(ret == -1 and errno != ENOENT){
2016
 
      perror_plus("rmdir");
 
1683
      perror("rmdir");
2017
1684
    }
2018
1685
  }
2019
1686
  
2024
1691
                                            &old_sigterm_action,
2025
1692
                                            NULL));
2026
1693
    if(ret == -1){
2027
 
      perror_plus("sigaction");
 
1694
      perror("sigaction");
2028
1695
    }
2029
1696
    do {
2030
1697
      ret = raise(signal_received);
2031
1698
    } while(ret != 0 and errno == EINTR);
2032
1699
    if(ret != 0){
2033
 
      perror_plus("raise");
 
1700
      perror("raise");
2034
1701
      abort();
2035
1702
    }
2036
1703
    TEMP_FAILURE_RETRY(pause());