/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: 2009-11-09 07:35:16 UTC
  • Revision ID: teddy@fukt.bsnet.se-20091109073516-v1vem352uz0vuwrd
* dbus-mandos.conf: New; to be copied to
                    "/etc/dbus-1/system.d/mandos.conf".

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
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,
128
127
static const char mandos_protocol_version[] = "1";
129
128
const char *argp_program_version = "mandos-client " VERSION;
130
129
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;
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
 
/* 
1089
 
 * This function determines if a directory entry in /sys/class/net
1090
 
 * corresponds to an acceptable network device.
1091
 
 * (This function is passed to scandir(3) as a filter function.)
1092
 
 */
1093
 
int good_interface(const struct dirent *if_entry){
1094
 
  ssize_t ssret;
1095
 
  char *flagname = NULL;
1096
 
  if(if_entry->d_name[0] == '.'){
1097
 
    return 0;
1098
 
  }
1099
 
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
1100
 
                     if_entry->d_name);
1101
 
  if(ret < 0){
1102
 
    perror_plus("asprintf");
1103
 
    return 0;
1104
 
  }
1105
 
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
1106
 
  if(flags_fd == -1){
1107
 
    perror_plus("open");
1108
 
    free(flagname);
1109
 
    return 0;
1110
 
  }
1111
 
  free(flagname);
1112
 
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
1113
 
  /* read line from flags_fd */
1114
 
  ssize_t to_read = 2+(sizeof(ifreq_flags)*2)+1; /* "0x1003\n" */
1115
 
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
1116
 
  flagstring[(size_t)to_read] = '\0';
1117
 
  if(flagstring == NULL){
1118
 
    perror_plus("malloc");
1119
 
    close(flags_fd);
1120
 
    return 0;
1121
 
  }
1122
 
  while(to_read > 0){
1123
 
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
1124
 
                                             (size_t)to_read));
1125
 
    if(ssret == -1){
1126
 
      perror_plus("read");
1127
 
      free(flagstring);
1128
 
      close(flags_fd);
1129
 
      return 0;
1130
 
    }
1131
 
    to_read -= ssret;
1132
 
    if(ssret == 0){
1133
 
      break;
1134
 
    }
1135
 
  }
1136
 
  close(flags_fd);
1137
 
  intmax_t tmpmax;
1138
 
  char *tmp;
1139
 
  errno = 0;
1140
 
  tmpmax = strtoimax(flagstring, &tmp, 0);
1141
 
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
1142
 
                                         and not (isspace(*tmp)))
1143
 
     or tmpmax != (ifreq_flags)tmpmax){
1144
 
    if(debug){
1145
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1146
 
              flagstring, if_entry->d_name);
1147
 
    }
1148
 
    free(flagstring);
1149
 
    return 0;
1150
 
  }
1151
 
  free(flagstring);
1152
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
1153
 
  /* Reject the loopback device */
1154
 
  if(flags & IFF_LOOPBACK){
1155
 
    if(debug){
1156
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1157
 
              if_entry->d_name);
1158
 
    }
1159
 
    return 0;
1160
 
  }
1161
 
  /* Accept point-to-point devices only if connect_to is specified */
1162
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1163
 
    if(debug){
1164
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1165
 
              if_entry->d_name);
1166
 
    }
1167
 
    return 1;
1168
 
  }
1169
 
  /* Otherwise, reject non-broadcast-capable devices */
1170
 
  if(not (flags & IFF_BROADCAST)){
1171
 
    if(debug){
1172
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1173
 
              if_entry->d_name);
1174
 
    }
1175
 
    return 0;
1176
 
  }
1177
 
  /* Reject non-ARP interfaces (including dummy interfaces) */
1178
 
  if(flags & IFF_NOARP){
1179
 
    if(debug){
1180
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
1181
 
              if_entry->d_name);
1182
 
    }
1183
 
    return 0;
1184
 
  }
1185
 
  /* Accept this device */
1186
 
  if(debug){
1187
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1188
 
            if_entry->d_name);
1189
 
  }
1190
 
  return 1;
1191
 
}
1192
 
 
1193
 
int notdotentries(const struct dirent *direntry){
1194
 
  /* Skip "." and ".." */
1195
 
  if(direntry->d_name[0] == '.'
1196
 
     and (direntry->d_name[1] == '\0'
1197
 
          or (direntry->d_name[1] == '.'
1198
 
              and direntry->d_name[2] == '\0'))){
1199
 
    return 0;
1200
 
  }
1201
 
  return 1;
1202
 
}
1203
 
 
1204
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1205
 
  int ret;
1206
 
  struct timespec now;
1207
 
  struct timespec waited_time;
1208
 
  intmax_t block_time;
1209
 
  
1210
 
  while(true){
1211
 
    if(mc.current_server == NULL){
1212
 
      if (debug){
1213
 
        fprintf(stderr,
1214
 
                "Wait until first server is found. No timeout!\n");
1215
 
      }
1216
 
      ret = avahi_simple_poll_iterate(s, -1);
1217
 
    } else {
1218
 
      if (debug){
1219
 
        fprintf(stderr, "Check current_server if we should run it,"
1220
 
                " or wait\n");
1221
 
      }
1222
 
      /* the current time */
1223
 
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1224
 
      if(ret == -1){
1225
 
        perror_plus("clock_gettime");
1226
 
        return -1;
1227
 
      }
1228
 
      /* Calculating in ms how long time between now and server
1229
 
         who we visted longest time ago. Now - last seen.  */
1230
 
      waited_time.tv_sec = (now.tv_sec
1231
 
                            - mc.current_server->last_seen.tv_sec);
1232
 
      waited_time.tv_nsec = (now.tv_nsec
1233
 
                             - mc.current_server->last_seen.tv_nsec);
1234
 
      /* total time is 10s/10,000ms.
1235
 
         Converting to s from ms by dividing by 1,000,
1236
 
         and ns to ms by dividing by 1,000,000. */
1237
 
      block_time = ((retry_interval
1238
 
                     - ((intmax_t)waited_time.tv_sec * 1000))
1239
 
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1240
 
      
1241
 
      if (debug){
1242
 
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
1243
 
      }
1244
 
      
1245
 
      if(block_time <= 0){
1246
 
        ret = start_mandos_communication(mc.current_server->ip,
1247
 
                                         mc.current_server->port,
1248
 
                                         mc.current_server->if_index,
1249
 
                                         mc.current_server->af);
1250
 
        if(ret == 0){
1251
 
          avahi_simple_poll_quit(mc.simple_poll);
1252
 
          return 0;
1253
 
        }
1254
 
        ret = clock_gettime(CLOCK_MONOTONIC,
1255
 
                            &mc.current_server->last_seen);
1256
 
        if(ret == -1){
1257
 
          perror_plus("clock_gettime");
1258
 
          return -1;
1259
 
        }
1260
 
        mc.current_server = mc.current_server->next;
1261
 
        block_time = 0;         /* Call avahi to find new Mandos
1262
 
                                   servers, but don't block */
1263
 
      }
1264
 
      
1265
 
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1266
 
    }
1267
 
    if(ret != 0){
1268
 
      if (ret > 0 or errno != EINTR) {
1269
 
        return (ret != 1) ? ret : 0;
1270
 
      }
1271
 
    }
1272
 
  }
1273
 
}
1274
 
 
1275
1023
int main(int argc, char *argv[]){
1276
1024
  AvahiSServiceBrowser *sb = NULL;
1277
1025
  int error;
1279
1027
  intmax_t tmpmax;
1280
1028
  char *tmp;
1281
1029
  int exitcode = EXIT_SUCCESS;
1282
 
  const char *interface = "";
 
1030
  const char *interface = "eth0";
1283
1031
  struct ifreq network;
1284
1032
  int sd = -1;
1285
1033
  bool take_down_interface = false;
1286
1034
  uid_t uid;
1287
1035
  gid_t gid;
 
1036
  char *connect_to = NULL;
1288
1037
  char tempdir[] = "/tmp/mandosXXXXXX";
1289
1038
  bool tempdir_created = false;
1290
1039
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1294
1043
  bool gnutls_initialized = false;
1295
1044
  bool gpgme_initialized = false;
1296
1045
  float delay = 2.5f;
1297
 
  double retry_interval = 10; /* 10s between trying a server and
1298
 
                                 retrying the same server again */
1299
1046
  
1300
1047
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1301
1048
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1307
1054
  errno = 0;
1308
1055
  ret = setgid(gid);
1309
1056
  if(ret == -1){
1310
 
    perror_plus("setgid");
 
1057
    perror("setgid");
1311
1058
  }
1312
1059
  
1313
1060
  /* Lower user privileges (temporarily) */
1314
1061
  errno = 0;
1315
1062
  ret = seteuid(uid);
1316
1063
  if(ret == -1){
1317
 
    perror_plus("seteuid");
 
1064
    perror("seteuid");
1318
1065
  }
1319
1066
  
1320
1067
  if(quit_now){
1355
1102
        .arg = "SECONDS",
1356
1103
        .doc = "Maximum delay to wait for interface startup",
1357
1104
        .group = 2 },
1358
 
      { .name = "retry", .key = 132,
1359
 
        .arg = "SECONDS",
1360
 
        .doc = "Retry interval used when denied by the mandos server",
1361
 
        .group = 2 },
1362
1105
      /*
1363
1106
       * These reproduce what we would get without ARGP_NO_HELP
1364
1107
       */
1408
1151
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1409
1152
          argp_error(state, "Bad delay");
1410
1153
        }
1411
 
      case 132:                 /* --retry */
1412
 
        errno = 0;
1413
 
        retry_interval = strtod(arg, &tmp);
1414
 
        if(errno != 0 or tmp == arg or *tmp != '\0'
1415
 
           or (retry_interval * 1000) > INT_MAX
1416
 
           or retry_interval < 0){
1417
 
          argp_error(state, "Bad retry interval");
1418
 
        }
1419
1154
        break;
1420
1155
        /*
1421
1156
         * These reproduce what we would get without ARGP_NO_HELP
1449
1184
    case ENOMEM:
1450
1185
    default:
1451
1186
      errno = ret;
1452
 
      perror_plus("argp_parse");
 
1187
      perror("argp_parse");
1453
1188
      exitcode = EX_OSERR;
1454
1189
      goto end;
1455
1190
    case EINVAL:
1457
1192
      goto end;
1458
1193
    }
1459
1194
  }
1460
 
    
1461
 
  {
1462
 
    /* Work around Debian bug #633582:
1463
 
       <http://bugs.debian.org/633582> */
1464
 
    struct stat st;
1465
 
    
1466
 
    /* Re-raise priviliges */
1467
 
    errno = 0;
1468
 
    ret = seteuid(0);
1469
 
    if(ret == -1){
1470
 
      perror_plus("seteuid");
1471
 
    }
1472
 
    
1473
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1474
 
      int seckey_fd = open(seckey, O_RDONLY);
1475
 
      if(seckey_fd == -1){
1476
 
        perror_plus("open");
1477
 
      } else {
1478
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1479
 
        if(ret == -1){
1480
 
          perror_plus("fstat");
1481
 
        } else {
1482
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1483
 
            ret = fchown(seckey_fd, uid, gid);
1484
 
            if(ret == -1){
1485
 
              perror_plus("fchown");
1486
 
            }
1487
 
          }
1488
 
        }
1489
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1490
 
      }
1491
 
    }
1492
 
    
1493
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1494
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1495
 
      if(pubkey_fd == -1){
1496
 
        perror_plus("open");
1497
 
      } else {
1498
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1499
 
        if(ret == -1){
1500
 
          perror_plus("fstat");
1501
 
        } else {
1502
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1503
 
            ret = fchown(pubkey_fd, uid, gid);
1504
 
            if(ret == -1){
1505
 
              perror_plus("fchown");
1506
 
            }
1507
 
          }
1508
 
        }
1509
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1510
 
      }
1511
 
    }
1512
 
    
1513
 
    /* Lower privileges */
1514
 
    errno = 0;
1515
 
    ret = seteuid(uid);
1516
 
    if(ret == -1){
1517
 
      perror_plus("seteuid");
1518
 
    }
1519
 
  }
1520
1195
  
1521
1196
  if(not debug){
1522
1197
    avahi_set_log_function(empty_log);
1523
1198
  }
1524
 
 
1525
 
  if(interface[0] == '\0'){
1526
 
    struct dirent **direntries;
1527
 
    ret = scandir(sys_class_net, &direntries, good_interface,
1528
 
                  alphasort);
1529
 
    if(ret >= 1){
1530
 
      /* Pick the first good interface */
1531
 
      interface = strdup(direntries[0]->d_name);
1532
 
      if(debug){
1533
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1534
 
      }
1535
 
      if(interface == NULL){
1536
 
        perror_plus("malloc");
1537
 
        free(direntries);
1538
 
        exitcode = EXIT_FAILURE;
1539
 
        goto end;
1540
 
      }
1541
 
      free(direntries);
1542
 
    } else {
1543
 
      free(direntries);
1544
 
      fprintf(stderr, "Could not find a network interface\n");
1545
 
      exitcode = EXIT_FAILURE;
1546
 
      goto end;
1547
 
    }
1548
 
  }
1549
1199
  
1550
1200
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1551
1201
     from the signal handler */
1561
1211
  sigemptyset(&sigterm_action.sa_mask);
1562
1212
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1563
1213
  if(ret == -1){
1564
 
    perror_plus("sigaddset");
 
1214
    perror("sigaddset");
1565
1215
    exitcode = EX_OSERR;
1566
1216
    goto end;
1567
1217
  }
1568
1218
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1569
1219
  if(ret == -1){
1570
 
    perror_plus("sigaddset");
 
1220
    perror("sigaddset");
1571
1221
    exitcode = EX_OSERR;
1572
1222
    goto end;
1573
1223
  }
1574
1224
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1575
1225
  if(ret == -1){
1576
 
    perror_plus("sigaddset");
 
1226
    perror("sigaddset");
1577
1227
    exitcode = EX_OSERR;
1578
1228
    goto end;
1579
1229
  }
1583
1233
  */
1584
1234
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1585
1235
  if(ret == -1){
1586
 
    perror_plus("sigaction");
 
1236
    perror("sigaction");
1587
1237
    return EX_OSERR;
1588
1238
  }
1589
1239
  if(old_sigterm_action.sa_handler != SIG_IGN){
1590
1240
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1591
1241
    if(ret == -1){
1592
 
      perror_plus("sigaction");
 
1242
      perror("sigaction");
1593
1243
      exitcode = EX_OSERR;
1594
1244
      goto end;
1595
1245
    }
1596
1246
  }
1597
1247
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1598
1248
  if(ret == -1){
1599
 
    perror_plus("sigaction");
 
1249
    perror("sigaction");
1600
1250
    return EX_OSERR;
1601
1251
  }
1602
1252
  if(old_sigterm_action.sa_handler != SIG_IGN){
1603
1253
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1604
1254
    if(ret == -1){
1605
 
      perror_plus("sigaction");
 
1255
      perror("sigaction");
1606
1256
      exitcode = EX_OSERR;
1607
1257
      goto end;
1608
1258
    }
1609
1259
  }
1610
1260
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1611
1261
  if(ret == -1){
1612
 
    perror_plus("sigaction");
 
1262
    perror("sigaction");
1613
1263
    return EX_OSERR;
1614
1264
  }
1615
1265
  if(old_sigterm_action.sa_handler != SIG_IGN){
1616
1266
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1617
1267
    if(ret == -1){
1618
 
      perror_plus("sigaction");
 
1268
      perror("sigaction");
1619
1269
      exitcode = EX_OSERR;
1620
1270
      goto end;
1621
1271
    }
1622
1272
  }
1623
1273
  
1624
1274
  /* If the interface is down, bring it up */
1625
 
  if(strcmp(interface, "none") != 0){
 
1275
  if(interface[0] != '\0'){
1626
1276
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1627
1277
    if(if_index == 0){
1628
1278
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1638
1288
    errno = 0;
1639
1289
    ret = seteuid(0);
1640
1290
    if(ret == -1){
1641
 
      perror_plus("seteuid");
 
1291
      perror("seteuid");
1642
1292
    }
1643
1293
    
1644
1294
#ifdef __linux__
1648
1298
    bool restore_loglevel = true;
1649
1299
    if(ret == -1){
1650
1300
      restore_loglevel = false;
1651
 
      perror_plus("klogctl");
 
1301
      perror("klogctl");
1652
1302
    }
1653
1303
#endif  /* __linux__ */
1654
1304
    
1655
1305
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1656
1306
    if(sd < 0){
1657
 
      perror_plus("socket");
 
1307
      perror("socket");
1658
1308
      exitcode = EX_OSERR;
1659
1309
#ifdef __linux__
1660
1310
      if(restore_loglevel){
1661
1311
        ret = klogctl(7, NULL, 0);
1662
1312
        if(ret == -1){
1663
 
          perror_plus("klogctl");
 
1313
          perror("klogctl");
1664
1314
        }
1665
1315
      }
1666
1316
#endif  /* __linux__ */
1668
1318
      errno = 0;
1669
1319
      ret = seteuid(uid);
1670
1320
      if(ret == -1){
1671
 
        perror_plus("seteuid");
 
1321
        perror("seteuid");
1672
1322
      }
1673
1323
      goto end;
1674
1324
    }
1675
1325
    strcpy(network.ifr_name, interface);
1676
1326
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1677
1327
    if(ret == -1){
1678
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1328
      perror("ioctl SIOCGIFFLAGS");
1679
1329
#ifdef __linux__
1680
1330
      if(restore_loglevel){
1681
1331
        ret = klogctl(7, NULL, 0);
1682
1332
        if(ret == -1){
1683
 
          perror_plus("klogctl");
 
1333
          perror("klogctl");
1684
1334
        }
1685
1335
      }
1686
1336
#endif  /* __linux__ */
1689
1339
      errno = 0;
1690
1340
      ret = seteuid(uid);
1691
1341
      if(ret == -1){
1692
 
        perror_plus("seteuid");
 
1342
        perror("seteuid");
1693
1343
      }
1694
1344
      goto end;
1695
1345
    }
1699
1349
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1700
1350
      if(ret == -1){
1701
1351
        take_down_interface = false;
1702
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1352
        perror("ioctl SIOCSIFFLAGS");
1703
1353
        exitcode = EX_OSERR;
1704
1354
#ifdef __linux__
1705
1355
        if(restore_loglevel){
1706
1356
          ret = klogctl(7, NULL, 0);
1707
1357
          if(ret == -1){
1708
 
            perror_plus("klogctl");
 
1358
            perror("klogctl");
1709
1359
          }
1710
1360
        }
1711
1361
#endif  /* __linux__ */
1713
1363
        errno = 0;
1714
1364
        ret = seteuid(uid);
1715
1365
        if(ret == -1){
1716
 
          perror_plus("seteuid");
 
1366
          perror("seteuid");
1717
1367
        }
1718
1368
        goto end;
1719
1369
      }
1720
1370
    }
1721
 
    /* Sleep checking until interface is running.
1722
 
       Check every 0.25s, up to total time of delay */
 
1371
    /* sleep checking until interface is running */
1723
1372
    for(int i=0; i < delay * 4; i++){
1724
1373
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1725
1374
      if(ret == -1){
1726
 
        perror_plus("ioctl SIOCGIFFLAGS");
 
1375
        perror("ioctl SIOCGIFFLAGS");
1727
1376
      } else if(network.ifr_flags & IFF_RUNNING){
1728
1377
        break;
1729
1378
      }
1730
1379
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1731
1380
      ret = nanosleep(&sleeptime, NULL);
1732
1381
      if(ret == -1 and errno != EINTR){
1733
 
        perror_plus("nanosleep");
 
1382
        perror("nanosleep");
1734
1383
      }
1735
1384
    }
1736
1385
    if(not take_down_interface){
1737
1386
      /* We won't need the socket anymore */
1738
1387
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1739
1388
      if(ret == -1){
1740
 
        perror_plus("close");
 
1389
        perror("close");
1741
1390
      }
1742
1391
    }
1743
1392
#ifdef __linux__
1745
1394
      /* Restores kernel loglevel to default */
1746
1395
      ret = klogctl(7, NULL, 0);
1747
1396
      if(ret == -1){
1748
 
        perror_plus("klogctl");
 
1397
        perror("klogctl");
1749
1398
      }
1750
1399
    }
1751
1400
#endif  /* __linux__ */
1755
1404
      /* Lower privileges */
1756
1405
      ret = seteuid(uid);
1757
1406
      if(ret == -1){
1758
 
        perror_plus("seteuid");
 
1407
        perror("seteuid");
1759
1408
      }
1760
1409
    } else {
1761
1410
      /* Lower privileges permanently */
1762
1411
      ret = setuid(uid);
1763
1412
      if(ret == -1){
1764
 
        perror_plus("setuid");
 
1413
        perror("setuid");
1765
1414
      }
1766
1415
    }
1767
1416
  }
1783
1432
    goto end;
1784
1433
  }
1785
1434
  
 
1435
  tempdir_created = true;
1786
1436
  if(mkdtemp(tempdir) == NULL){
1787
 
    perror_plus("mkdtemp");
 
1437
    tempdir_created = false;
 
1438
    perror("mkdtemp");
1788
1439
    goto end;
1789
1440
  }
1790
 
  tempdir_created = true;
1791
1441
  
1792
1442
  if(quit_now){
1793
1443
    goto end;
1835
1485
    
1836
1486
    port = (uint16_t)tmpmax;
1837
1487
    *address = '\0';
 
1488
    address = connect_to;
1838
1489
    /* Colon in address indicates IPv6 */
1839
1490
    int af;
1840
 
    if(strchr(connect_to, ':') != NULL){
 
1491
    if(strchr(address, ':') != NULL){
1841
1492
      af = AF_INET6;
1842
 
      /* Accept [] around IPv6 address - see RFC 5952 */
1843
 
      if(connect_to[0] == '[' and address[-1] == ']')
1844
 
        {
1845
 
          connect_to++;
1846
 
          address[-1] = '\0';
1847
 
        }
1848
1493
    } else {
1849
1494
      af = AF_INET;
1850
1495
    }
1851
 
    address = connect_to;
1852
1496
    
1853
1497
    if(quit_now){
1854
1498
      goto end;
1855
1499
    }
1856
1500
    
1857
 
    while(not quit_now){
1858
 
      ret = start_mandos_communication(address, port, if_index, af);
1859
 
      if(quit_now or ret == 0){
1860
 
        break;
1861
 
      }
1862
 
      if(debug){
1863
 
        fprintf(stderr, "Retrying in %d seconds\n",
1864
 
                (int)retry_interval);
1865
 
      }
1866
 
      sleep((int)retry_interval);
1867
 
    }
1868
 
    
1869
 
    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 {
1870
1523
      exitcode = EXIT_SUCCESS;
1871
1524
    }
1872
 
 
1873
1525
    goto end;
1874
1526
  }
1875
1527
  
1927
1579
  if(debug){
1928
1580
    fprintf(stderr, "Starting Avahi loop search\n");
1929
1581
  }
1930
 
 
1931
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
1932
 
                                (int)(retry_interval * 1000));
1933
 
  if(debug){
1934
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
1935
 
            (ret == 0) ? "successfully" : "with error");
1936
 
  }
 
1582
  
 
1583
  avahi_simple_poll_loop(mc.simple_poll);
1937
1584
  
1938
1585
 end:
1939
1586
  
1960
1607
  if(gpgme_initialized){
1961
1608
    gpgme_release(mc.ctx);
1962
1609
  }
1963
 
 
1964
 
  /* Cleans up the circular linked list of Mandos servers the client
1965
 
     has seen */
1966
 
  if(mc.current_server != NULL){
1967
 
    mc.current_server->prev->next = NULL;
1968
 
    while(mc.current_server != NULL){
1969
 
      server *next = mc.current_server->next;
1970
 
      free(mc.current_server);
1971
 
      mc.current_server = next;
1972
 
    }
1973
 
  }
1974
1610
  
1975
1611
  /* Take down the network interface */
1976
1612
  if(take_down_interface){
1978
1614
    errno = 0;
1979
1615
    ret = seteuid(0);
1980
1616
    if(ret == -1){
1981
 
      perror_plus("seteuid");
 
1617
      perror("seteuid");
1982
1618
    }
1983
1619
    if(geteuid() == 0){
1984
1620
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1985
1621
      if(ret == -1){
1986
 
        perror_plus("ioctl SIOCGIFFLAGS");
 
1622
        perror("ioctl SIOCGIFFLAGS");
1987
1623
      } else if(network.ifr_flags & IFF_UP) {
1988
1624
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1989
1625
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1990
1626
        if(ret == -1){
1991
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1627
          perror("ioctl SIOCSIFFLAGS");
1992
1628
        }
1993
1629
      }
1994
1630
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1995
1631
      if(ret == -1){
1996
 
        perror_plus("close");
 
1632
        perror("close");
1997
1633
      }
1998
1634
      /* Lower privileges permanently */
1999
1635
      errno = 0;
2000
1636
      ret = setuid(uid);
2001
1637
      if(ret == -1){
2002
 
        perror_plus("setuid");
 
1638
        perror("setuid");
2003
1639
      }
2004
1640
    }
2005
1641
  }
2006
1642
  
2007
 
  /* Removes the GPGME temp directory and all files inside */
 
1643
  /* Removes the temp directory used by GPGME */
2008
1644
  if(tempdir_created){
2009
 
    struct dirent **direntries = NULL;
2010
 
    struct dirent *direntry = NULL;
2011
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
2012
 
                             alphasort);
2013
 
    if (numentries > 0){
2014
 
      for(int i = 0; i < numentries; i++){
2015
 
        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
        }
2016
1665
        char *fullname = NULL;
2017
1666
        ret = asprintf(&fullname, "%s/%s", tempdir,
2018
1667
                       direntry->d_name);
2019
1668
        if(ret < 0){
2020
 
          perror_plus("asprintf");
 
1669
          perror("asprintf");
2021
1670
          continue;
2022
1671
        }
2023
1672
        ret = remove(fullname);
2027
1676
        }
2028
1677
        free(fullname);
2029
1678
      }
2030
 
    }
2031
 
 
2032
 
    /* need to clean even if 0 because man page doesn't specify */
2033
 
    free(direntries);
2034
 
    if (numentries == -1){
2035
 
      perror_plus("scandir");
 
1679
      closedir(d);
2036
1680
    }
2037
1681
    ret = rmdir(tempdir);
2038
1682
    if(ret == -1 and errno != ENOENT){
2039
 
      perror_plus("rmdir");
 
1683
      perror("rmdir");
2040
1684
    }
2041
1685
  }
2042
1686
  
2047
1691
                                            &old_sigterm_action,
2048
1692
                                            NULL));
2049
1693
    if(ret == -1){
2050
 
      perror_plus("sigaction");
 
1694
      perror("sigaction");
2051
1695
    }
2052
1696
    do {
2053
1697
      ret = raise(signal_received);
2054
1698
    } while(ret != 0 and errno == EINTR);
2055
1699
    if(ret != 0){
2056
 
      perror_plus("raise");
 
1700
      perror("raise");
2057
1701
      abort();
2058
1702
    }
2059
1703
    TEMP_FAILURE_RETRY(pause());