/mandos/release

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

« back to all changes in this revision

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

* plugins.d/mandos-client.c (good_interface): Use SIOCGIFFLAGS instead
                                              of reading
                                              /sys/class/net/*/flags.

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,2009 Teddy Hogeborn
13
 
 * Copyright © 2008,2009 Björn Påhlsson
 
12
 * Copyright © 2008-2011 Teddy Hogeborn
 
13
 * Copyright © 2008-2011 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@fukt.bsnet.se>.
 
29
 * Contact the authors at <mandos@recompile.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 */
 
65
#include <errno.h>              /* perror(), errno,
 
66
                                   program_invocation_short_name */
66
67
#include <time.h>               /* nanosleep(), time(), sleep() */
67
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
68
69
                                   SIOCSIFFLAGS, if_indextoname(),
73
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
74
75
                                   getuid(), getgid(), seteuid(),
75
76
                                   setgid(), pause() */
76
 
#include <arpa/inet.h>          /* inet_pton(), htons */
 
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
77
78
#include <iso646.h>             /* not, or, and */
78
79
#include <argp.h>               /* struct argp_option, error_t, struct
79
80
                                   argp_state, struct argp,
126
127
bool debug = false;
127
128
static const char mandos_protocol_version[] = "1";
128
129
const char *argp_program_version = "mandos-client " VERSION;
129
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
130
const char *argp_program_bug_address = "<mandos@recompile.se>";
130
131
static const char sys_class_net[] = "/sys/class/net";
131
132
char *connect_to = NULL;
132
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;
 
144
 
133
145
/* Used for passing in values through the Avahi callback functions */
134
146
typedef struct {
135
147
  AvahiSimplePoll *simple_poll;
139
151
  gnutls_dh_params_t dh_params;
140
152
  const char *priority;
141
153
  gpgme_ctx_t ctx;
 
154
  server *current_server;
142
155
} mandos_context;
143
156
 
144
157
/* global context so signal handler can reach it*/
145
158
mandos_context mc = { .simple_poll = NULL, .server = NULL,
146
159
                      .dh_bits = 1024, .priority = "SECURE256"
147
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
160
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
161
                      .current_server = NULL };
148
162
 
149
163
sig_atomic_t quit_now = 0;
150
164
int signal_received = 0;
151
165
 
 
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
 
152
173
/*
153
174
 * Make additional room in "buffer" for at least BUFFER_SIZE more
154
175
 * bytes. "buffer_capacity" is how much is currently allocated,
166
187
  return buffer_capacity;
167
188
}
168
189
 
 
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
 
169
228
/* 
170
229
 * Initialize GPGME.
171
230
 */
185
244
    
186
245
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
187
246
    if(fd == -1){
188
 
      perror("open");
 
247
      perror_plus("open");
189
248
      return false;
190
249
    }
191
250
    
205
264
    
206
265
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
207
266
    if(ret == -1){
208
 
      perror("close");
 
267
      perror_plus("close");
209
268
    }
210
269
    gpgme_data_release(pgp_data);
211
270
    return true;
224
283
    return false;
225
284
  }
226
285
  
227
 
    /* Set GPGME home directory for the OpenPGP engine only */
 
286
  /* Set GPGME home directory for the OpenPGP engine only */
228
287
  rc = gpgme_get_engine_info(&engine_info);
229
288
  if(rc != GPG_ERR_NO_ERROR){
230
289
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
336
395
  
337
396
  /* Seek back to the beginning of the GPGME plaintext data buffer */
338
397
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
339
 
    perror("gpgme_data_seek");
 
398
    perror_plus("gpgme_data_seek");
340
399
    plaintext_length = -1;
341
400
    goto decrypt_end;
342
401
  }
347
406
                                      (size_t)plaintext_length,
348
407
                                      plaintext_capacity);
349
408
    if(plaintext_capacity == 0){
350
 
        perror("incbuffer");
 
409
        perror_plus("incbuffer");
351
410
        plaintext_length = -1;
352
411
        goto decrypt_end;
353
412
    }
360
419
      break;
361
420
    }
362
421
    if(ret < 0){
363
 
      perror("gpgme_data_read");
 
422
      perror_plus("gpgme_data_read");
364
423
      plaintext_length = -1;
365
424
      goto decrypt_end;
366
425
    }
423
482
  }
424
483
  
425
484
  /* OpenPGP credentials */
426
 
  gnutls_certificate_allocate_credentials(&mc.cred);
 
485
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
427
486
  if(ret != GNUTLS_E_SUCCESS){
428
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
429
 
                                                    from
430
 
                                                    -Wunreachable-code
431
 
                                                 */
 
487
    fprintf(stderr, "GnuTLS memory error: %s\n",
432
488
            safer_gnutls_strerror(ret));
433
489
    gnutls_global_deinit();
434
490
    return -1;
589
645
  tcp_sd = socket(pf, SOCK_STREAM, 0);
590
646
  if(tcp_sd < 0){
591
647
    int e = errno;
592
 
    perror("socket");
 
648
    perror_plus("socket");
593
649
    errno = e;
594
650
    goto mandos_end;
595
651
  }
609
665
  }
610
666
  if(ret < 0 ){
611
667
    int e = errno;
612
 
    perror("inet_pton");
 
668
    perror_plus("inet_pton");
613
669
    errno = e;
614
670
    goto mandos_end;
615
671
  }
651
707
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
652
708
      char interface[IF_NAMESIZE];
653
709
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
654
 
        perror("if_indextoname");
 
710
        perror_plus("if_indextoname");
655
711
      } else {
656
712
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
657
713
                ip, interface, port);
671
727
                        sizeof(addrstr));
672
728
    }
673
729
    if(pcret == NULL){
674
 
      perror("inet_ntop");
 
730
      perror_plus("inet_ntop");
675
731
    } else {
676
732
      if(strcmp(addrstr, ip) != 0){
677
733
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
692
748
  if(ret < 0){
693
749
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
694
750
      int e = errno;
695
 
      perror("connect");
 
751
      perror_plus("connect");
696
752
      errno = e;
697
753
    }
698
754
    goto mandos_end;
711
767
                                   out_size - written));
712
768
    if(ret == -1){
713
769
      int e = errno;
714
 
      perror("write");
 
770
      perror_plus("write");
715
771
      errno = e;
716
772
      goto mandos_end;
717
773
    }
742
798
    goto mandos_end;
743
799
  }
744
800
  
 
801
  /* Spurious warning from -Wint-to-pointer-cast */
745
802
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
746
803
  
747
804
  if(quit_now){
784
841
                                   buffer_capacity);
785
842
    if(buffer_capacity == 0){
786
843
      int e = errno;
787
 
      perror("incbuffer");
 
844
      perror_plus("incbuffer");
788
845
      errno = e;
789
846
      goto mandos_end;
790
847
    }
895
952
      if(e == 0){
896
953
        e = errno;
897
954
      }
898
 
      perror("close");
 
955
      perror_plus("close");
899
956
    }
900
957
    gnutls_deinit(session);
 
958
    errno = e;
901
959
    if(quit_now){
902
 
      e = EINTR;
 
960
      errno = EINTR;
903
961
      retval = -1;
904
962
    }
905
 
    errno = e;
906
963
  }
907
964
  return retval;
908
965
}
951
1008
                                           avahi_proto_to_af(proto));
952
1009
      if(ret == 0){
953
1010
        avahi_simple_poll_quit(mc.simple_poll);
 
1011
      } else {
 
1012
        ret = add_server(ip, port, interface,
 
1013
                         avahi_proto_to_af(proto));
954
1014
      }
955
1015
    }
956
1016
  }
1010
1070
  }
1011
1071
}
1012
1072
 
1013
 
/* stop main loop after sigterm has been called */
 
1073
/* Signal handler that stops main loop after SIGTERM */
1014
1074
static void handle_sigterm(int sig){
1015
1075
  if(quit_now){
1016
1076
    return;
1018
1078
  quit_now = 1;
1019
1079
  signal_received = sig;
1020
1080
  int old_errno = errno;
 
1081
  /* set main loop to exit */
1021
1082
  if(mc.simple_poll != NULL){
1022
1083
    avahi_simple_poll_quit(mc.simple_poll);
1023
1084
  }
1031
1092
 */
1032
1093
int good_interface(const struct dirent *if_entry){
1033
1094
  ssize_t ssret;
1034
 
  char *flagname = NULL;
1035
 
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
1036
 
                     if_entry->d_name);
1037
 
  if(ret < 0){
1038
 
    perror("asprintf");
1039
 
    return 0;
1040
 
  }
 
1095
  int ret;
1041
1096
  if(if_entry->d_name[0] == '.'){
1042
1097
    return 0;
1043
1098
  }
1044
 
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
1045
 
  if(flags_fd == -1){
1046
 
    perror("open");
1047
 
    return 0;
1048
 
  }
1049
 
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
1050
 
  /* read line from flags_fd */
1051
 
  ssize_t to_read = (sizeof(ifreq_flags)*2)+3; /* "0x1003\n" */
1052
 
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
1053
 
  flagstring[(size_t)to_read] = '\0';
1054
 
  if(flagstring == NULL){
1055
 
    perror("malloc");
1056
 
    close(flags_fd);
1057
 
    return 0;
1058
 
  }
1059
 
  while(to_read > 0){
1060
 
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
1061
 
                                             (size_t)to_read));
1062
 
    if(ssret == -1){
1063
 
      perror("read");
1064
 
      free(flagstring);
1065
 
      close(flags_fd);
1066
 
      return 0;
1067
 
    }
1068
 
    to_read -= ssret;
1069
 
    if(ssret == 0){
1070
 
      break;
1071
 
    }
1072
 
  }
1073
 
  close(flags_fd);
1074
 
  intmax_t tmpmax;
1075
 
  char *tmp;
1076
 
  errno = 0;
1077
 
  tmpmax = strtoimax(flagstring, &tmp, 0);
1078
 
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
1079
 
                                         and not (isspace(*tmp)))
1080
 
     or tmpmax != (ifreq_flags)tmpmax){
 
1099
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1100
  if(s < 0){
 
1101
    perror_plus("socket");
 
1102
    return 0;
 
1103
  }
 
1104
  struct ifreq ifr;
 
1105
  strcpy(ifr.ifr_name, if_entry->d_name);
 
1106
  ret = ioctl(s, SIOCGIFFLAGS, &ifr);
 
1107
  if(ret == -1){
1081
1108
    if(debug){
1082
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1083
 
              flagstring, if_entry->d_name);
 
1109
      perror_plus("ioctl SIOCGIFFLAGS");
1084
1110
    }
1085
 
    free(flagstring);
1086
1111
    return 0;
1087
1112
  }
1088
 
  free(flagstring);
1089
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
1090
1113
  /* Reject the loopback device */
1091
 
  if(flags & IFF_LOOPBACK){
 
1114
  if(ifr.ifr_flags & IFF_LOOPBACK){
1092
1115
    if(debug){
1093
1116
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1094
1117
              if_entry->d_name);
1096
1119
    return 0;
1097
1120
  }
1098
1121
  /* Accept point-to-point devices only if connect_to is specified */
1099
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1122
  if(connect_to != NULL and (ifr.ifr_flags & IFF_POINTOPOINT)){
1100
1123
    if(debug){
1101
1124
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1102
1125
              if_entry->d_name);
1104
1127
    return 1;
1105
1128
  }
1106
1129
  /* Otherwise, reject non-broadcast-capable devices */
1107
 
  if(not (flags & IFF_BROADCAST)){
 
1130
  if(not (ifr.ifr_flags & IFF_BROADCAST)){
1108
1131
    if(debug){
1109
1132
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1110
1133
              if_entry->d_name);
1111
1134
    }
1112
1135
    return 0;
1113
1136
  }
 
1137
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1138
  if(ifr.ifr_flags & IFF_NOARP){
 
1139
    if(debug){
 
1140
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1141
              if_entry->d_name);
 
1142
    }
 
1143
    return 0;
 
1144
  }
1114
1145
  /* Accept this device */
1115
1146
  if(debug){
1116
1147
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1119
1150
  return 1;
1120
1151
}
1121
1152
 
 
1153
int notdotentries(const struct dirent *direntry){
 
1154
  /* Skip "." and ".." */
 
1155
  if(direntry->d_name[0] == '.'
 
1156
     and (direntry->d_name[1] == '\0'
 
1157
          or (direntry->d_name[1] == '.'
 
1158
              and direntry->d_name[2] == '\0'))){
 
1159
    return 0;
 
1160
  }
 
1161
  return 1;
 
1162
}
 
1163
 
 
1164
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1165
  int ret;
 
1166
  struct timespec now;
 
1167
  struct timespec waited_time;
 
1168
  intmax_t block_time;
 
1169
  
 
1170
  while(true){
 
1171
    if(mc.current_server == NULL){
 
1172
      if (debug){
 
1173
        fprintf(stderr,
 
1174
                "Wait until first server is found. No timeout!\n");
 
1175
      }
 
1176
      ret = avahi_simple_poll_iterate(s, -1);
 
1177
    } else {
 
1178
      if (debug){
 
1179
        fprintf(stderr, "Check current_server if we should run it,"
 
1180
                " or wait\n");
 
1181
      }
 
1182
      /* the current time */
 
1183
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
 
1184
      if(ret == -1){
 
1185
        perror_plus("clock_gettime");
 
1186
        return -1;
 
1187
      }
 
1188
      /* Calculating in ms how long time between now and server
 
1189
         who we visted longest time ago. Now - last seen.  */
 
1190
      waited_time.tv_sec = (now.tv_sec
 
1191
                            - mc.current_server->last_seen.tv_sec);
 
1192
      waited_time.tv_nsec = (now.tv_nsec
 
1193
                             - mc.current_server->last_seen.tv_nsec);
 
1194
      /* total time is 10s/10,000ms.
 
1195
         Converting to s from ms by dividing by 1,000,
 
1196
         and ns to ms by dividing by 1,000,000. */
 
1197
      block_time = ((retry_interval
 
1198
                     - ((intmax_t)waited_time.tv_sec * 1000))
 
1199
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
 
1200
      
 
1201
      if (debug){
 
1202
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
 
1203
      }
 
1204
      
 
1205
      if(block_time <= 0){
 
1206
        ret = start_mandos_communication(mc.current_server->ip,
 
1207
                                         mc.current_server->port,
 
1208
                                         mc.current_server->if_index,
 
1209
                                         mc.current_server->af);
 
1210
        if(ret == 0){
 
1211
          avahi_simple_poll_quit(mc.simple_poll);
 
1212
          return 0;
 
1213
        }
 
1214
        ret = clock_gettime(CLOCK_MONOTONIC,
 
1215
                            &mc.current_server->last_seen);
 
1216
        if(ret == -1){
 
1217
          perror_plus("clock_gettime");
 
1218
          return -1;
 
1219
        }
 
1220
        mc.current_server = mc.current_server->next;
 
1221
        block_time = 0;         /* Call avahi to find new Mandos
 
1222
                                   servers, but don't block */
 
1223
      }
 
1224
      
 
1225
      ret = avahi_simple_poll_iterate(s, (int)block_time);
 
1226
    }
 
1227
    if(ret != 0){
 
1228
      if (ret > 0 or errno != EINTR) {
 
1229
        return (ret != 1) ? ret : 0;
 
1230
      }
 
1231
    }
 
1232
  }
 
1233
}
 
1234
 
1122
1235
int main(int argc, char *argv[]){
1123
1236
  AvahiSServiceBrowser *sb = NULL;
1124
1237
  int error;
1141
1254
  bool gnutls_initialized = false;
1142
1255
  bool gpgme_initialized = false;
1143
1256
  float delay = 2.5f;
 
1257
  double retry_interval = 10; /* 10s between trying a server and
 
1258
                                 retrying the same server again */
1144
1259
  
1145
1260
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1146
1261
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1152
1267
  errno = 0;
1153
1268
  ret = setgid(gid);
1154
1269
  if(ret == -1){
1155
 
    perror("setgid");
 
1270
    perror_plus("setgid");
1156
1271
  }
1157
1272
  
1158
1273
  /* Lower user privileges (temporarily) */
1159
1274
  errno = 0;
1160
1275
  ret = seteuid(uid);
1161
1276
  if(ret == -1){
1162
 
    perror("seteuid");
 
1277
    perror_plus("seteuid");
1163
1278
  }
1164
1279
  
1165
1280
  if(quit_now){
1200
1315
        .arg = "SECONDS",
1201
1316
        .doc = "Maximum delay to wait for interface startup",
1202
1317
        .group = 2 },
 
1318
      { .name = "retry", .key = 132,
 
1319
        .arg = "SECONDS",
 
1320
        .doc = "Retry interval used when denied by the mandos server",
 
1321
        .group = 2 },
1203
1322
      /*
1204
1323
       * These reproduce what we would get without ARGP_NO_HELP
1205
1324
       */
1249
1368
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1250
1369
          argp_error(state, "Bad delay");
1251
1370
        }
 
1371
      case 132:                 /* --retry */
 
1372
        errno = 0;
 
1373
        retry_interval = strtod(arg, &tmp);
 
1374
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1375
           or (retry_interval * 1000) > INT_MAX
 
1376
           or retry_interval < 0){
 
1377
          argp_error(state, "Bad retry interval");
 
1378
        }
1252
1379
        break;
1253
1380
        /*
1254
1381
         * These reproduce what we would get without ARGP_NO_HELP
1282
1409
    case ENOMEM:
1283
1410
    default:
1284
1411
      errno = ret;
1285
 
      perror("argp_parse");
 
1412
      perror_plus("argp_parse");
1286
1413
      exitcode = EX_OSERR;
1287
1414
      goto end;
1288
1415
    case EINVAL:
1290
1417
      goto end;
1291
1418
    }
1292
1419
  }
 
1420
    
 
1421
  {
 
1422
    /* Work around Debian bug #633582:
 
1423
       <http://bugs.debian.org/633582> */
 
1424
    struct stat st;
 
1425
    
 
1426
    /* Re-raise priviliges */
 
1427
    errno = 0;
 
1428
    ret = seteuid(0);
 
1429
    if(ret == -1){
 
1430
      perror_plus("seteuid");
 
1431
    }
 
1432
    
 
1433
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1434
      int seckey_fd = open(seckey, O_RDONLY);
 
1435
      if(seckey_fd == -1){
 
1436
        perror_plus("open");
 
1437
      } else {
 
1438
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1439
        if(ret == -1){
 
1440
          perror_plus("fstat");
 
1441
        } else {
 
1442
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1443
            ret = fchown(seckey_fd, uid, gid);
 
1444
            if(ret == -1){
 
1445
              perror_plus("fchown");
 
1446
            }
 
1447
          }
 
1448
        }
 
1449
        TEMP_FAILURE_RETRY(close(seckey_fd));
 
1450
      }
 
1451
    }
 
1452
    
 
1453
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1454
      int pubkey_fd = open(pubkey, O_RDONLY);
 
1455
      if(pubkey_fd == -1){
 
1456
        perror_plus("open");
 
1457
      } else {
 
1458
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1459
        if(ret == -1){
 
1460
          perror_plus("fstat");
 
1461
        } else {
 
1462
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1463
            ret = fchown(pubkey_fd, uid, gid);
 
1464
            if(ret == -1){
 
1465
              perror_plus("fchown");
 
1466
            }
 
1467
          }
 
1468
        }
 
1469
        TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1470
      }
 
1471
    }
 
1472
    
 
1473
    /* Lower privileges */
 
1474
    errno = 0;
 
1475
    ret = seteuid(uid);
 
1476
    if(ret == -1){
 
1477
      perror_plus("seteuid");
 
1478
    }
 
1479
  }
1293
1480
  
1294
1481
  if(not debug){
1295
1482
    avahi_set_log_function(empty_log);
1306
1493
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1307
1494
      }
1308
1495
      if(interface == NULL){
1309
 
        perror("malloc");
 
1496
        perror_plus("malloc");
1310
1497
        free(direntries);
1311
1498
        exitcode = EXIT_FAILURE;
1312
1499
        goto end;
1334
1521
  sigemptyset(&sigterm_action.sa_mask);
1335
1522
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1336
1523
  if(ret == -1){
1337
 
    perror("sigaddset");
 
1524
    perror_plus("sigaddset");
1338
1525
    exitcode = EX_OSERR;
1339
1526
    goto end;
1340
1527
  }
1341
1528
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1342
1529
  if(ret == -1){
1343
 
    perror("sigaddset");
 
1530
    perror_plus("sigaddset");
1344
1531
    exitcode = EX_OSERR;
1345
1532
    goto end;
1346
1533
  }
1347
1534
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1348
1535
  if(ret == -1){
1349
 
    perror("sigaddset");
 
1536
    perror_plus("sigaddset");
1350
1537
    exitcode = EX_OSERR;
1351
1538
    goto end;
1352
1539
  }
1356
1543
  */
1357
1544
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1358
1545
  if(ret == -1){
1359
 
    perror("sigaction");
 
1546
    perror_plus("sigaction");
1360
1547
    return EX_OSERR;
1361
1548
  }
1362
1549
  if(old_sigterm_action.sa_handler != SIG_IGN){
1363
1550
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1364
1551
    if(ret == -1){
1365
 
      perror("sigaction");
 
1552
      perror_plus("sigaction");
1366
1553
      exitcode = EX_OSERR;
1367
1554
      goto end;
1368
1555
    }
1369
1556
  }
1370
1557
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1371
1558
  if(ret == -1){
1372
 
    perror("sigaction");
 
1559
    perror_plus("sigaction");
1373
1560
    return EX_OSERR;
1374
1561
  }
1375
1562
  if(old_sigterm_action.sa_handler != SIG_IGN){
1376
1563
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1377
1564
    if(ret == -1){
1378
 
      perror("sigaction");
 
1565
      perror_plus("sigaction");
1379
1566
      exitcode = EX_OSERR;
1380
1567
      goto end;
1381
1568
    }
1382
1569
  }
1383
1570
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1384
1571
  if(ret == -1){
1385
 
    perror("sigaction");
 
1572
    perror_plus("sigaction");
1386
1573
    return EX_OSERR;
1387
1574
  }
1388
1575
  if(old_sigterm_action.sa_handler != SIG_IGN){
1389
1576
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1390
1577
    if(ret == -1){
1391
 
      perror("sigaction");
 
1578
      perror_plus("sigaction");
1392
1579
      exitcode = EX_OSERR;
1393
1580
      goto end;
1394
1581
    }
1411
1598
    errno = 0;
1412
1599
    ret = seteuid(0);
1413
1600
    if(ret == -1){
1414
 
      perror("seteuid");
 
1601
      perror_plus("seteuid");
1415
1602
    }
1416
1603
    
1417
1604
#ifdef __linux__
1421
1608
    bool restore_loglevel = true;
1422
1609
    if(ret == -1){
1423
1610
      restore_loglevel = false;
1424
 
      perror("klogctl");
 
1611
      perror_plus("klogctl");
1425
1612
    }
1426
1613
#endif  /* __linux__ */
1427
1614
    
1428
1615
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1429
1616
    if(sd < 0){
1430
 
      perror("socket");
 
1617
      perror_plus("socket");
1431
1618
      exitcode = EX_OSERR;
1432
1619
#ifdef __linux__
1433
1620
      if(restore_loglevel){
1434
1621
        ret = klogctl(7, NULL, 0);
1435
1622
        if(ret == -1){
1436
 
          perror("klogctl");
 
1623
          perror_plus("klogctl");
1437
1624
        }
1438
1625
      }
1439
1626
#endif  /* __linux__ */
1441
1628
      errno = 0;
1442
1629
      ret = seteuid(uid);
1443
1630
      if(ret == -1){
1444
 
        perror("seteuid");
 
1631
        perror_plus("seteuid");
1445
1632
      }
1446
1633
      goto end;
1447
1634
    }
1448
1635
    strcpy(network.ifr_name, interface);
1449
1636
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1450
1637
    if(ret == -1){
1451
 
      perror("ioctl SIOCGIFFLAGS");
 
1638
      perror_plus("ioctl SIOCGIFFLAGS");
1452
1639
#ifdef __linux__
1453
1640
      if(restore_loglevel){
1454
1641
        ret = klogctl(7, NULL, 0);
1455
1642
        if(ret == -1){
1456
 
          perror("klogctl");
 
1643
          perror_plus("klogctl");
1457
1644
        }
1458
1645
      }
1459
1646
#endif  /* __linux__ */
1462
1649
      errno = 0;
1463
1650
      ret = seteuid(uid);
1464
1651
      if(ret == -1){
1465
 
        perror("seteuid");
 
1652
        perror_plus("seteuid");
1466
1653
      }
1467
1654
      goto end;
1468
1655
    }
1472
1659
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1473
1660
      if(ret == -1){
1474
1661
        take_down_interface = false;
1475
 
        perror("ioctl SIOCSIFFLAGS +IFF_UP");
 
1662
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1476
1663
        exitcode = EX_OSERR;
1477
1664
#ifdef __linux__
1478
1665
        if(restore_loglevel){
1479
1666
          ret = klogctl(7, NULL, 0);
1480
1667
          if(ret == -1){
1481
 
            perror("klogctl");
 
1668
            perror_plus("klogctl");
1482
1669
          }
1483
1670
        }
1484
1671
#endif  /* __linux__ */
1486
1673
        errno = 0;
1487
1674
        ret = seteuid(uid);
1488
1675
        if(ret == -1){
1489
 
          perror("seteuid");
 
1676
          perror_plus("seteuid");
1490
1677
        }
1491
1678
        goto end;
1492
1679
      }
1493
1680
    }
1494
 
    /* sleep checking until interface is running */
 
1681
    /* Sleep checking until interface is running.
 
1682
       Check every 0.25s, up to total time of delay */
1495
1683
    for(int i=0; i < delay * 4; i++){
1496
1684
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1497
1685
      if(ret == -1){
1498
 
        perror("ioctl SIOCGIFFLAGS");
 
1686
        perror_plus("ioctl SIOCGIFFLAGS");
1499
1687
      } else if(network.ifr_flags & IFF_RUNNING){
1500
1688
        break;
1501
1689
      }
1502
1690
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1503
1691
      ret = nanosleep(&sleeptime, NULL);
1504
1692
      if(ret == -1 and errno != EINTR){
1505
 
        perror("nanosleep");
 
1693
        perror_plus("nanosleep");
1506
1694
      }
1507
1695
    }
1508
1696
    if(not take_down_interface){
1509
1697
      /* We won't need the socket anymore */
1510
1698
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1511
1699
      if(ret == -1){
1512
 
        perror("close");
 
1700
        perror_plus("close");
1513
1701
      }
1514
1702
    }
1515
1703
#ifdef __linux__
1517
1705
      /* Restores kernel loglevel to default */
1518
1706
      ret = klogctl(7, NULL, 0);
1519
1707
      if(ret == -1){
1520
 
        perror("klogctl");
 
1708
        perror_plus("klogctl");
1521
1709
      }
1522
1710
    }
1523
1711
#endif  /* __linux__ */
1527
1715
      /* Lower privileges */
1528
1716
      ret = seteuid(uid);
1529
1717
      if(ret == -1){
1530
 
        perror("seteuid");
 
1718
        perror_plus("seteuid");
1531
1719
      }
1532
1720
    } else {
1533
1721
      /* Lower privileges permanently */
1534
1722
      ret = setuid(uid);
1535
1723
      if(ret == -1){
1536
 
        perror("setuid");
 
1724
        perror_plus("setuid");
1537
1725
      }
1538
1726
    }
1539
1727
  }
1555
1743
    goto end;
1556
1744
  }
1557
1745
  
 
1746
  if(mkdtemp(tempdir) == NULL){
 
1747
    perror_plus("mkdtemp");
 
1748
    goto end;
 
1749
  }
1558
1750
  tempdir_created = true;
1559
 
  if(mkdtemp(tempdir) == NULL){
1560
 
    tempdir_created = false;
1561
 
    perror("mkdtemp");
1562
 
    goto end;
1563
 
  }
1564
1751
  
1565
1752
  if(quit_now){
1566
1753
    goto end;
1608
1795
    
1609
1796
    port = (uint16_t)tmpmax;
1610
1797
    *address = '\0';
1611
 
    address = connect_to;
1612
1798
    /* Colon in address indicates IPv6 */
1613
1799
    int af;
1614
 
    if(strchr(address, ':') != NULL){
 
1800
    if(strchr(connect_to, ':') != NULL){
1615
1801
      af = AF_INET6;
 
1802
      /* Accept [] around IPv6 address - see RFC 5952 */
 
1803
      if(connect_to[0] == '[' and address[-1] == ']')
 
1804
        {
 
1805
          connect_to++;
 
1806
          address[-1] = '\0';
 
1807
        }
1616
1808
    } else {
1617
1809
      af = AF_INET;
1618
1810
    }
 
1811
    address = connect_to;
1619
1812
    
1620
1813
    if(quit_now){
1621
1814
      goto end;
1622
1815
    }
1623
 
 
 
1816
    
1624
1817
    while(not quit_now){
1625
1818
      ret = start_mandos_communication(address, port, if_index, af);
1626
1819
      if(quit_now or ret == 0){
1627
1820
        break;
1628
1821
      }
1629
 
      sleep(15);
1630
 
    };
1631
 
 
 
1822
      if(debug){
 
1823
        fprintf(stderr, "Retrying in %d seconds\n",
 
1824
                (int)retry_interval);
 
1825
      }
 
1826
      sleep((int)retry_interval);
 
1827
    }
 
1828
    
1632
1829
    if (not quit_now){
1633
1830
      exitcode = EXIT_SUCCESS;
1634
1831
    }
1690
1887
  if(debug){
1691
1888
    fprintf(stderr, "Starting Avahi loop search\n");
1692
1889
  }
1693
 
  
1694
 
  avahi_simple_poll_loop(mc.simple_poll);
 
1890
 
 
1891
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
1892
                                (int)(retry_interval * 1000));
 
1893
  if(debug){
 
1894
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
1895
            (ret == 0) ? "successfully" : "with error");
 
1896
  }
1695
1897
  
1696
1898
 end:
1697
1899
  
1718
1920
  if(gpgme_initialized){
1719
1921
    gpgme_release(mc.ctx);
1720
1922
  }
 
1923
 
 
1924
  /* Cleans up the circular linked list of Mandos servers the client
 
1925
     has seen */
 
1926
  if(mc.current_server != NULL){
 
1927
    mc.current_server->prev->next = NULL;
 
1928
    while(mc.current_server != NULL){
 
1929
      server *next = mc.current_server->next;
 
1930
      free(mc.current_server);
 
1931
      mc.current_server = next;
 
1932
    }
 
1933
  }
1721
1934
  
1722
1935
  /* Take down the network interface */
1723
1936
  if(take_down_interface){
1725
1938
    errno = 0;
1726
1939
    ret = seteuid(0);
1727
1940
    if(ret == -1){
1728
 
      perror("seteuid");
 
1941
      perror_plus("seteuid");
1729
1942
    }
1730
1943
    if(geteuid() == 0){
1731
1944
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1732
1945
      if(ret == -1){
1733
 
        perror("ioctl SIOCGIFFLAGS");
 
1946
        perror_plus("ioctl SIOCGIFFLAGS");
1734
1947
      } else if(network.ifr_flags & IFF_UP) {
1735
1948
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1736
1949
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1737
1950
        if(ret == -1){
1738
 
          perror("ioctl SIOCSIFFLAGS -IFF_UP");
 
1951
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1739
1952
        }
1740
1953
      }
1741
1954
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1742
1955
      if(ret == -1){
1743
 
        perror("close");
 
1956
        perror_plus("close");
1744
1957
      }
1745
1958
      /* Lower privileges permanently */
1746
1959
      errno = 0;
1747
1960
      ret = setuid(uid);
1748
1961
      if(ret == -1){
1749
 
        perror("setuid");
 
1962
        perror_plus("setuid");
1750
1963
      }
1751
1964
    }
1752
1965
  }
1753
1966
  
1754
 
  /* Removes the temp directory used by GPGME */
 
1967
  /* Removes the GPGME temp directory and all files inside */
1755
1968
  if(tempdir_created){
1756
 
    DIR *d;
1757
 
    struct dirent *direntry;
1758
 
    d = opendir(tempdir);
1759
 
    if(d == NULL){
1760
 
      if(errno != ENOENT){
1761
 
        perror("opendir");
1762
 
      }
1763
 
    } else {
1764
 
      while(true){
1765
 
        direntry = readdir(d);
1766
 
        if(direntry == NULL){
1767
 
          break;
1768
 
        }
1769
 
        /* Skip "." and ".." */
1770
 
        if(direntry->d_name[0] == '.'
1771
 
           and (direntry->d_name[1] == '\0'
1772
 
                or (direntry->d_name[1] == '.'
1773
 
                    and direntry->d_name[2] == '\0'))){
1774
 
          continue;
1775
 
        }
 
1969
    struct dirent **direntries = NULL;
 
1970
    struct dirent *direntry = NULL;
 
1971
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
1972
                             alphasort);
 
1973
    if (numentries > 0){
 
1974
      for(int i = 0; i < numentries; i++){
 
1975
        direntry = direntries[i];
1776
1976
        char *fullname = NULL;
1777
1977
        ret = asprintf(&fullname, "%s/%s", tempdir,
1778
1978
                       direntry->d_name);
1779
1979
        if(ret < 0){
1780
 
          perror("asprintf");
 
1980
          perror_plus("asprintf");
1781
1981
          continue;
1782
1982
        }
1783
1983
        ret = remove(fullname);
1787
1987
        }
1788
1988
        free(fullname);
1789
1989
      }
1790
 
      closedir(d);
 
1990
    }
 
1991
 
 
1992
    /* need to clean even if 0 because man page doesn't specify */
 
1993
    free(direntries);
 
1994
    if (numentries == -1){
 
1995
      perror_plus("scandir");
1791
1996
    }
1792
1997
    ret = rmdir(tempdir);
1793
1998
    if(ret == -1 and errno != ENOENT){
1794
 
      perror("rmdir");
 
1999
      perror_plus("rmdir");
1795
2000
    }
1796
2001
  }
1797
2002
  
1802
2007
                                            &old_sigterm_action,
1803
2008
                                            NULL));
1804
2009
    if(ret == -1){
1805
 
      perror("sigaction");
 
2010
      perror_plus("sigaction");
1806
2011
    }
1807
2012
    do {
1808
2013
      ret = raise(signal_received);
1809
2014
    } while(ret != 0 and errno == EINTR);
1810
2015
    if(ret != 0){
1811
 
      perror("raise");
 
2016
      perror_plus("raise");
1812
2017
      abort();
1813
2018
    }
1814
2019
    TEMP_FAILURE_RETRY(pause());