/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2011-07-27 18:27:02 UTC
  • mfrom: (237.4.16 release)
  • Revision ID: teddy@fukt.bsnet.se-20110727182702-lmoxs1l571yikkl0
Merge from release branch.

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