/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Björn Påhlsson
  • Date: 2011-11-14 18:03:35 UTC
  • mto: (505.3.9 client-network-hooks)
  • mto: This revision was merged to the branch mainline in revision 525.
  • Revision ID: belorn@fukt.bsnet.se-20111114180335-3j4x5mjr7lix2jyj
New convinence error printer: fprintf_plus

Show diffs side-by-side

added added

removed removed

Lines of Context:
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,
122
123
#define PATHDIR "/conf/conf.d/mandos"
123
124
#define SECKEY "seckey.txt"
124
125
#define PUBKEY "pubkey.txt"
 
126
#define HOOKDIR "/lib/mandos/network-hooks.d"
125
127
 
126
128
bool debug = false;
127
129
static const char mandos_protocol_version[] = "1";
128
130
const char *argp_program_version = "mandos-client " VERSION;
129
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
131
const char *argp_program_bug_address = "<mandos@recompile.se>";
130
132
static const char sys_class_net[] = "/sys/class/net";
131
133
char *connect_to = NULL;
132
134
 
 
135
/* Doubly linked list that need to be circularly linked when used */
 
136
typedef struct server{
 
137
  const char *ip;
 
138
  uint16_t port;
 
139
  AvahiIfIndex if_index;
 
140
  int af;
 
141
  struct timespec last_seen;
 
142
  struct server *next;
 
143
  struct server *prev;
 
144
} server;
 
145
 
133
146
/* Used for passing in values through the Avahi callback functions */
134
147
typedef struct {
135
148
  AvahiSimplePoll *simple_poll;
139
152
  gnutls_dh_params_t dh_params;
140
153
  const char *priority;
141
154
  gpgme_ctx_t ctx;
 
155
  server *current_server;
142
156
} mandos_context;
143
157
 
144
158
/* global context so signal handler can reach it*/
145
159
mandos_context mc = { .simple_poll = NULL, .server = NULL,
146
160
                      .dh_bits = 1024, .priority = "SECURE256"
147
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
161
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
162
                      .current_server = NULL };
148
163
 
149
164
sig_atomic_t quit_now = 0;
150
165
int signal_received = 0;
151
166
 
 
167
/* Function to use when printing errors */
 
168
void perror_plus(const char *print_text){
 
169
  fprintf(stderr, "Mandos plugin %s: ",
 
170
          program_invocation_short_name);
 
171
  perror(print_text);
 
172
}
 
173
 
 
174
int fprintf_plus(FILE *stream, const char *format, ...){
 
175
  va_list ap;
 
176
  va_start (ap, format);
 
177
  
 
178
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ", program_invocation_short_name));
 
179
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
180
}
 
181
 
152
182
/*
153
183
 * Make additional room in "buffer" for at least BUFFER_SIZE more
154
184
 * bytes. "buffer_capacity" is how much is currently allocated,
166
196
  return buffer_capacity;
167
197
}
168
198
 
 
199
/* Add server to set of servers to retry periodically */
 
200
int add_server(const char *ip, uint16_t port,
 
201
                 AvahiIfIndex if_index,
 
202
                 int af){
 
203
  int ret;
 
204
  server *new_server = malloc(sizeof(server));
 
205
  if(new_server == NULL){
 
206
    perror_plus("malloc");
 
207
    return -1;
 
208
  }
 
209
  *new_server = (server){ .ip = strdup(ip),
 
210
                         .port = port,
 
211
                         .if_index = if_index,
 
212
                         .af = af };
 
213
  if(new_server->ip == NULL){
 
214
    perror_plus("strdup");
 
215
    return -1;
 
216
  }
 
217
  /* Special case of first server */
 
218
  if (mc.current_server == NULL){
 
219
    new_server->next = new_server;
 
220
    new_server->prev = new_server;
 
221
    mc.current_server = new_server;
 
222
  /* Place the new server last in the list */
 
223
  } else {
 
224
    new_server->next = mc.current_server;
 
225
    new_server->prev = mc.current_server->prev;
 
226
    new_server->prev->next = new_server;
 
227
    mc.current_server->prev = new_server;
 
228
  }
 
229
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
230
  if(ret == -1){
 
231
    perror_plus("clock_gettime");
 
232
    return -1;
 
233
  }
 
234
  return 0;
 
235
}
 
236
 
169
237
/* 
170
238
 * Initialize GPGME.
171
239
 */
185
253
    
186
254
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
187
255
    if(fd == -1){
188
 
      perror("open");
 
256
      perror_plus("open");
189
257
      return false;
190
258
    }
191
259
    
205
273
    
206
274
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
207
275
    if(ret == -1){
208
 
      perror("close");
 
276
      perror_plus("close");
209
277
    }
210
278
    gpgme_data_release(pgp_data);
211
279
    return true;
224
292
    return false;
225
293
  }
226
294
  
227
 
    /* Set GPGME home directory for the OpenPGP engine only */
 
295
  /* Set GPGME home directory for the OpenPGP engine only */
228
296
  rc = gpgme_get_engine_info(&engine_info);
229
297
  if(rc != GPG_ERR_NO_ERROR){
230
298
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
336
404
  
337
405
  /* Seek back to the beginning of the GPGME plaintext data buffer */
338
406
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
339
 
    perror("gpgme_data_seek");
 
407
    perror_plus("gpgme_data_seek");
340
408
    plaintext_length = -1;
341
409
    goto decrypt_end;
342
410
  }
347
415
                                      (size_t)plaintext_length,
348
416
                                      plaintext_capacity);
349
417
    if(plaintext_capacity == 0){
350
 
        perror("incbuffer");
 
418
        perror_plus("incbuffer");
351
419
        plaintext_length = -1;
352
420
        goto decrypt_end;
353
421
    }
360
428
      break;
361
429
    }
362
430
    if(ret < 0){
363
 
      perror("gpgme_data_read");
 
431
      perror_plus("gpgme_data_read");
364
432
      plaintext_length = -1;
365
433
      goto decrypt_end;
366
434
    }
423
491
  }
424
492
  
425
493
  /* OpenPGP credentials */
426
 
  gnutls_certificate_allocate_credentials(&mc.cred);
 
494
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
427
495
  if(ret != GNUTLS_E_SUCCESS){
428
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
429
 
                                                    from
430
 
                                                    -Wunreachable-code
431
 
                                                 */
 
496
    fprintf(stderr, "GnuTLS memory error: %s\n",
432
497
            safer_gnutls_strerror(ret));
433
498
    gnutls_global_deinit();
434
499
    return -1;
589
654
  tcp_sd = socket(pf, SOCK_STREAM, 0);
590
655
  if(tcp_sd < 0){
591
656
    int e = errno;
592
 
    perror("socket");
 
657
    perror_plus("socket");
593
658
    errno = e;
594
659
    goto mandos_end;
595
660
  }
609
674
  }
610
675
  if(ret < 0 ){
611
676
    int e = errno;
612
 
    perror("inet_pton");
 
677
    perror_plus("inet_pton");
613
678
    errno = e;
614
679
    goto mandos_end;
615
680
  }
651
716
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
652
717
      char interface[IF_NAMESIZE];
653
718
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
654
 
        perror("if_indextoname");
 
719
        perror_plus("if_indextoname");
655
720
      } else {
656
721
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
657
722
                ip, interface, port);
671
736
                        sizeof(addrstr));
672
737
    }
673
738
    if(pcret == NULL){
674
 
      perror("inet_ntop");
 
739
      perror_plus("inet_ntop");
675
740
    } else {
676
741
      if(strcmp(addrstr, ip) != 0){
677
742
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
692
757
  if(ret < 0){
693
758
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
694
759
      int e = errno;
695
 
      perror("connect");
 
760
      perror_plus("connect");
696
761
      errno = e;
697
762
    }
698
763
    goto mandos_end;
711
776
                                   out_size - written));
712
777
    if(ret == -1){
713
778
      int e = errno;
714
 
      perror("write");
 
779
      perror_plus("write");
715
780
      errno = e;
716
781
      goto mandos_end;
717
782
    }
742
807
    goto mandos_end;
743
808
  }
744
809
  
 
810
  /* Spurious warning from -Wint-to-pointer-cast */
745
811
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
746
812
  
747
813
  if(quit_now){
784
850
                                   buffer_capacity);
785
851
    if(buffer_capacity == 0){
786
852
      int e = errno;
787
 
      perror("incbuffer");
 
853
      perror_plus("incbuffer");
788
854
      errno = e;
789
855
      goto mandos_end;
790
856
    }
895
961
      if(e == 0){
896
962
        e = errno;
897
963
      }
898
 
      perror("close");
 
964
      perror_plus("close");
899
965
    }
900
966
    gnutls_deinit(session);
 
967
    errno = e;
901
968
    if(quit_now){
902
 
      e = EINTR;
 
969
      errno = EINTR;
903
970
      retval = -1;
904
971
    }
905
 
    errno = e;
906
972
  }
907
973
  return retval;
908
974
}
951
1017
                                           avahi_proto_to_af(proto));
952
1018
      if(ret == 0){
953
1019
        avahi_simple_poll_quit(mc.simple_poll);
 
1020
      } else {
 
1021
        ret = add_server(ip, port, interface,
 
1022
                         avahi_proto_to_af(proto));
954
1023
      }
955
1024
    }
956
1025
  }
1010
1079
  }
1011
1080
}
1012
1081
 
1013
 
/* stop main loop after sigterm has been called */
 
1082
/* Signal handler that stops main loop after SIGTERM */
1014
1083
static void handle_sigterm(int sig){
1015
1084
  if(quit_now){
1016
1085
    return;
1018
1087
  quit_now = 1;
1019
1088
  signal_received = sig;
1020
1089
  int old_errno = errno;
 
1090
  /* set main loop to exit */
1021
1091
  if(mc.simple_poll != NULL){
1022
1092
    avahi_simple_poll_quit(mc.simple_poll);
1023
1093
  }
1024
1094
  errno = old_errno;
1025
1095
}
1026
1096
 
 
1097
bool get_flags(const char *ifname, struct ifreq *ifr){
 
1098
  int ret;
 
1099
  
 
1100
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1101
  if(s < 0){
 
1102
    perror_plus("socket");
 
1103
    return false;
 
1104
  }
 
1105
  strcpy(ifr->ifr_name, ifname);
 
1106
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
 
1107
  if(ret == -1){
 
1108
    if(debug){
 
1109
      perror_plus("ioctl SIOCGIFFLAGS");
 
1110
    }
 
1111
    return false;
 
1112
  }
 
1113
  return true;
 
1114
}
 
1115
 
 
1116
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1117
  
 
1118
  /* Reject the loopback device */
 
1119
  if(ifr->ifr_flags & IFF_LOOPBACK){
 
1120
    if(debug){
 
1121
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1122
              ifname);
 
1123
    }
 
1124
    return false;
 
1125
  }
 
1126
  /* Accept point-to-point devices only if connect_to is specified */
 
1127
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
 
1128
    if(debug){
 
1129
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1130
              ifname);
 
1131
    }
 
1132
    return true;
 
1133
  }
 
1134
  /* Otherwise, reject non-broadcast-capable devices */
 
1135
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
 
1136
    if(debug){
 
1137
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1138
              ifname);
 
1139
    }
 
1140
    return false;
 
1141
  }
 
1142
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1143
  if(ifr->ifr_flags & IFF_NOARP){
 
1144
    if(debug){
 
1145
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1146
    }
 
1147
    return false;
 
1148
  }
 
1149
  
 
1150
  /* Accept this device */
 
1151
  if(debug){
 
1152
    fprintf(stderr, "Interface \"%s\" is good\n", ifname);
 
1153
  }
 
1154
  return true;
 
1155
}
 
1156
 
1027
1157
/* 
1028
1158
 * This function determines if a directory entry in /sys/class/net
1029
1159
 * corresponds to an acceptable network device.
1030
1160
 * (This function is passed to scandir(3) as a filter function.)
1031
1161
 */
1032
1162
int good_interface(const struct dirent *if_entry){
 
1163
  int ret;
 
1164
  if(if_entry->d_name[0] == '.'){
 
1165
    return 0;
 
1166
  }
 
1167
  struct ifreq ifr;
 
1168
 
 
1169
  if(not get_flags(if_entry->d_name, &ifr)){
 
1170
    return 0;
 
1171
  }
 
1172
  
 
1173
  if(not good_flags(if_entry->d_name, &ifr)){
 
1174
    return 0;
 
1175
  }
 
1176
  return 1;
 
1177
}
 
1178
 
 
1179
/* 
 
1180
 * This function determines if a directory entry in /sys/class/net
 
1181
 * corresponds to an acceptable network device which is up.
 
1182
 * (This function is passed to scandir(3) as a filter function.)
 
1183
 */
 
1184
int up_interface(const struct dirent *if_entry){
1033
1185
  ssize_t ssret;
1034
1186
  char *flagname = NULL;
 
1187
  if(if_entry->d_name[0] == '.'){
 
1188
    return 0;
 
1189
  }
1035
1190
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
1036
1191
                     if_entry->d_name);
1037
1192
  if(ret < 0){
1038
 
    perror("asprintf");
1039
 
    return 0;
1040
 
  }
1041
 
  if(if_entry->d_name[0] == '.'){
 
1193
    perror_plus("asprintf");
1042
1194
    return 0;
1043
1195
  }
1044
1196
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
1045
1197
  if(flags_fd == -1){
1046
 
    perror("open");
 
1198
    perror_plus("open");
 
1199
    free(flagname);
1047
1200
    return 0;
1048
1201
  }
 
1202
  free(flagname);
1049
1203
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
1050
1204
  /* read line from flags_fd */
1051
 
  ssize_t to_read = (sizeof(ifreq_flags)*2)+3; /* "0x1003\n" */
 
1205
  ssize_t to_read = 2+(sizeof(ifreq_flags)*2)+1; /* "0x1003\n" */
1052
1206
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
1053
1207
  flagstring[(size_t)to_read] = '\0';
1054
1208
  if(flagstring == NULL){
1055
 
    perror("malloc");
 
1209
    perror_plus("malloc");
1056
1210
    close(flags_fd);
1057
1211
    return 0;
1058
1212
  }
1060
1214
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
1061
1215
                                             (size_t)to_read));
1062
1216
    if(ssret == -1){
1063
 
      perror("read");
 
1217
      perror_plus("read");
1064
1218
      free(flagstring);
1065
1219
      close(flags_fd);
1066
1220
      return 0;
1095
1249
    }
1096
1250
    return 0;
1097
1251
  }
 
1252
 
 
1253
  /* Reject down interfaces */
 
1254
  if(not (flags & IFF_UP)){
 
1255
    return 0;
 
1256
  }
 
1257
  
1098
1258
  /* Accept point-to-point devices only if connect_to is specified */
1099
1259
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1100
1260
    if(debug){
1111
1271
    }
1112
1272
    return 0;
1113
1273
  }
 
1274
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1275
  if(flags & IFF_NOARP){
 
1276
    if(debug){
 
1277
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1278
              if_entry->d_name);
 
1279
    }
 
1280
    return 0;
 
1281
  }
1114
1282
  /* Accept this device */
1115
1283
  if(debug){
1116
1284
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1119
1287
  return 1;
1120
1288
}
1121
1289
 
 
1290
int notdotentries(const struct dirent *direntry){
 
1291
  /* Skip "." and ".." */
 
1292
  if(direntry->d_name[0] == '.'
 
1293
     and (direntry->d_name[1] == '\0'
 
1294
          or (direntry->d_name[1] == '.'
 
1295
              and direntry->d_name[2] == '\0'))){
 
1296
    return 0;
 
1297
  }
 
1298
  return 1;
 
1299
}
 
1300
 
 
1301
/* Is this directory entry a runnable program? */
 
1302
int runnable_hook(const struct dirent *direntry){
 
1303
  int ret;
 
1304
  struct stat st;
 
1305
  
 
1306
  if((direntry->d_name)[0] == '\0'){
 
1307
    /* Empty name? */
 
1308
    return 0;
 
1309
  }
 
1310
  
 
1311
  /* Save pointer to last character */
 
1312
  char *end = strchr(direntry->d_name, '\0')-1;
 
1313
  
 
1314
  if(*end == '~'){
 
1315
    /* Backup name~ */
 
1316
    return 0;
 
1317
  }
 
1318
  
 
1319
  if(((direntry->d_name)[0] == '#')
 
1320
     and (*end == '#')){
 
1321
    /* Temporary #name# */
 
1322
    return 0;
 
1323
  }
 
1324
  
 
1325
  /* XXX more rules here */
 
1326
  
 
1327
  ret = stat(direntry->d_name, &st);
 
1328
  if(ret == -1){
 
1329
    if(debug){
 
1330
      perror_plus("Could not stat plugin");
 
1331
    }
 
1332
    return 0;
 
1333
  }
 
1334
  if(not (st.st_mode & S_ISREG)){
 
1335
    /* Not a regular file */
 
1336
    return 0;
 
1337
  }
 
1338
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
 
1339
    /* Not executable */
 
1340
    return 0;
 
1341
  }
 
1342
  return 1;
 
1343
}
 
1344
 
 
1345
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1346
  int ret;
 
1347
  struct timespec now;
 
1348
  struct timespec waited_time;
 
1349
  intmax_t block_time;
 
1350
  
 
1351
  while(true){
 
1352
    if(mc.current_server == NULL){
 
1353
      if (debug){
 
1354
        fprintf(stderr,
 
1355
                "Wait until first server is found. No timeout!\n");
 
1356
      }
 
1357
      ret = avahi_simple_poll_iterate(s, -1);
 
1358
    } else {
 
1359
      if (debug){
 
1360
        fprintf(stderr, "Check current_server if we should run it,"
 
1361
                " or wait\n");
 
1362
      }
 
1363
      /* the current time */
 
1364
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
 
1365
      if(ret == -1){
 
1366
        perror_plus("clock_gettime");
 
1367
        return -1;
 
1368
      }
 
1369
      /* Calculating in ms how long time between now and server
 
1370
         who we visted longest time ago. Now - last seen.  */
 
1371
      waited_time.tv_sec = (now.tv_sec
 
1372
                            - mc.current_server->last_seen.tv_sec);
 
1373
      waited_time.tv_nsec = (now.tv_nsec
 
1374
                             - mc.current_server->last_seen.tv_nsec);
 
1375
      /* total time is 10s/10,000ms.
 
1376
         Converting to s from ms by dividing by 1,000,
 
1377
         and ns to ms by dividing by 1,000,000. */
 
1378
      block_time = ((retry_interval
 
1379
                     - ((intmax_t)waited_time.tv_sec * 1000))
 
1380
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
 
1381
      
 
1382
      if (debug){
 
1383
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
 
1384
      }
 
1385
      
 
1386
      if(block_time <= 0){
 
1387
        ret = start_mandos_communication(mc.current_server->ip,
 
1388
                                         mc.current_server->port,
 
1389
                                         mc.current_server->if_index,
 
1390
                                         mc.current_server->af);
 
1391
        if(ret == 0){
 
1392
          avahi_simple_poll_quit(mc.simple_poll);
 
1393
          return 0;
 
1394
        }
 
1395
        ret = clock_gettime(CLOCK_MONOTONIC,
 
1396
                            &mc.current_server->last_seen);
 
1397
        if(ret == -1){
 
1398
          perror_plus("clock_gettime");
 
1399
          return -1;
 
1400
        }
 
1401
        mc.current_server = mc.current_server->next;
 
1402
        block_time = 0;         /* Call avahi to find new Mandos
 
1403
                                   servers, but don't block */
 
1404
      }
 
1405
      
 
1406
      ret = avahi_simple_poll_iterate(s, (int)block_time);
 
1407
    }
 
1408
    if(ret != 0){
 
1409
      if (ret > 0 or errno != EINTR) {
 
1410
        return (ret != 1) ? ret : 0;
 
1411
      }
 
1412
    }
 
1413
  }
 
1414
}
 
1415
 
1122
1416
int main(int argc, char *argv[]){
1123
1417
  AvahiSServiceBrowser *sb = NULL;
1124
1418
  int error;
1141
1435
  bool gnutls_initialized = false;
1142
1436
  bool gpgme_initialized = false;
1143
1437
  float delay = 2.5f;
 
1438
  double retry_interval = 10; /* 10s between trying a server and
 
1439
                                 retrying the same server again */
1144
1440
  
1145
1441
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1146
1442
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1152
1448
  errno = 0;
1153
1449
  ret = setgid(gid);
1154
1450
  if(ret == -1){
1155
 
    perror("setgid");
 
1451
    perror_plus("setgid");
1156
1452
  }
1157
1453
  
1158
1454
  /* Lower user privileges (temporarily) */
1159
1455
  errno = 0;
1160
1456
  ret = seteuid(uid);
1161
1457
  if(ret == -1){
1162
 
    perror("seteuid");
 
1458
    perror_plus("seteuid");
1163
1459
  }
1164
1460
  
1165
1461
  if(quit_now){
1200
1496
        .arg = "SECONDS",
1201
1497
        .doc = "Maximum delay to wait for interface startup",
1202
1498
        .group = 2 },
 
1499
      { .name = "retry", .key = 132,
 
1500
        .arg = "SECONDS",
 
1501
        .doc = "Retry interval used when denied by the mandos server",
 
1502
        .group = 2 },
1203
1503
      /*
1204
1504
       * These reproduce what we would get without ARGP_NO_HELP
1205
1505
       */
1249
1549
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1250
1550
          argp_error(state, "Bad delay");
1251
1551
        }
 
1552
      case 132:                 /* --retry */
 
1553
        errno = 0;
 
1554
        retry_interval = strtod(arg, &tmp);
 
1555
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1556
           or (retry_interval * 1000) > INT_MAX
 
1557
           or retry_interval < 0){
 
1558
          argp_error(state, "Bad retry interval");
 
1559
        }
1252
1560
        break;
1253
1561
        /*
1254
1562
         * These reproduce what we would get without ARGP_NO_HELP
1282
1590
    case ENOMEM:
1283
1591
    default:
1284
1592
      errno = ret;
1285
 
      perror("argp_parse");
 
1593
      perror_plus("argp_parse");
1286
1594
      exitcode = EX_OSERR;
1287
1595
      goto end;
1288
1596
    case EINVAL:
1290
1598
      goto end;
1291
1599
    }
1292
1600
  }
 
1601
    
 
1602
  {
 
1603
    /* Work around Debian bug #633582:
 
1604
       <http://bugs.debian.org/633582> */
 
1605
    struct stat st;
 
1606
    
 
1607
    /* Re-raise priviliges */
 
1608
    errno = 0;
 
1609
    ret = seteuid(0);
 
1610
    if(ret == -1){
 
1611
      perror_plus("seteuid");
 
1612
    }
 
1613
    
 
1614
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1615
      int seckey_fd = open(seckey, O_RDONLY);
 
1616
      if(seckey_fd == -1){
 
1617
        perror_plus("open");
 
1618
      } else {
 
1619
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1620
        if(ret == -1){
 
1621
          perror_plus("fstat");
 
1622
        } else {
 
1623
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1624
            ret = fchown(seckey_fd, uid, gid);
 
1625
            if(ret == -1){
 
1626
              perror_plus("fchown");
 
1627
            }
 
1628
          }
 
1629
        }
 
1630
        TEMP_FAILURE_RETRY(close(seckey_fd));
 
1631
      }
 
1632
    }
 
1633
    
 
1634
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1635
      int pubkey_fd = open(pubkey, O_RDONLY);
 
1636
      if(pubkey_fd == -1){
 
1637
        perror_plus("open");
 
1638
      } else {
 
1639
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1640
        if(ret == -1){
 
1641
          perror_plus("fstat");
 
1642
        } else {
 
1643
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1644
            ret = fchown(pubkey_fd, uid, gid);
 
1645
            if(ret == -1){
 
1646
              perror_plus("fchown");
 
1647
            }
 
1648
          }
 
1649
        }
 
1650
        TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1651
      }
 
1652
    }
 
1653
    
 
1654
    /* Lower privileges */
 
1655
    errno = 0;
 
1656
    ret = seteuid(uid);
 
1657
    if(ret == -1){
 
1658
      perror_plus("seteuid");
 
1659
    }
 
1660
  }
 
1661
  
 
1662
  /* Find network hooks and run them */
 
1663
  {
 
1664
    struct dirent **direntries;
 
1665
    struct dirent *direntry;
 
1666
    int numhooks = scandir(HOOKDIR, &direntries, runnable_hook,
 
1667
                           alphasort);
 
1668
    int devnull = open("/dev/null", O_RDONLY);
 
1669
    for(int i = 0; i < numhooks; i++){
 
1670
      direntry = direntries[0];
 
1671
      char *fullname = NULL;
 
1672
      ret = asprintf(&fullname, "%s/%s", tempdir,
 
1673
                     direntry->d_name);
 
1674
      if(ret < 0){
 
1675
        perror_plus("asprintf");
 
1676
        continue;
 
1677
      }
 
1678
      pid_t hook_pid = fork();
 
1679
      if(hook_pid == 0){
 
1680
        /* Child */
 
1681
        dup2(devnull, STDIN_FILENO);
 
1682
        close(devnull);
 
1683
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1684
        setenv("DEVICE", interface, 1);
 
1685
        setenv("VERBOSE", debug ? "1" : "0", 1);
 
1686
        setenv("MODE", "start", 1);
 
1687
        /* setenv( XXX more here */
 
1688
        ret = execl(fullname, direntry->d_name, "start");
 
1689
        perror_plus("execl");
 
1690
      }
 
1691
      free(fullname);
 
1692
      if(quit_now){
 
1693
        goto end;
 
1694
      }
 
1695
    }
 
1696
    close(devnull);
 
1697
  }
1293
1698
  
1294
1699
  if(not debug){
1295
1700
    avahi_set_log_function(empty_log);
1296
1701
  }
1297
 
 
 
1702
  
1298
1703
  if(interface[0] == '\0'){
1299
1704
    struct dirent **direntries;
1300
1705
    ret = scandir(sys_class_net, &direntries, good_interface,
1306
1711
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1307
1712
      }
1308
1713
      if(interface == NULL){
1309
 
        perror("malloc");
 
1714
        perror_plus("malloc");
1310
1715
        free(direntries);
1311
1716
        exitcode = EXIT_FAILURE;
1312
1717
        goto end;
1334
1739
  sigemptyset(&sigterm_action.sa_mask);
1335
1740
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1336
1741
  if(ret == -1){
1337
 
    perror("sigaddset");
 
1742
    perror_plus("sigaddset");
1338
1743
    exitcode = EX_OSERR;
1339
1744
    goto end;
1340
1745
  }
1341
1746
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1342
1747
  if(ret == -1){
1343
 
    perror("sigaddset");
 
1748
    perror_plus("sigaddset");
1344
1749
    exitcode = EX_OSERR;
1345
1750
    goto end;
1346
1751
  }
1347
1752
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1348
1753
  if(ret == -1){
1349
 
    perror("sigaddset");
 
1754
    perror_plus("sigaddset");
1350
1755
    exitcode = EX_OSERR;
1351
1756
    goto end;
1352
1757
  }
1356
1761
  */
1357
1762
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1358
1763
  if(ret == -1){
1359
 
    perror("sigaction");
 
1764
    perror_plus("sigaction");
1360
1765
    return EX_OSERR;
1361
1766
  }
1362
1767
  if(old_sigterm_action.sa_handler != SIG_IGN){
1363
1768
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1364
1769
    if(ret == -1){
1365
 
      perror("sigaction");
 
1770
      perror_plus("sigaction");
1366
1771
      exitcode = EX_OSERR;
1367
1772
      goto end;
1368
1773
    }
1369
1774
  }
1370
1775
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1371
1776
  if(ret == -1){
1372
 
    perror("sigaction");
 
1777
    perror_plus("sigaction");
1373
1778
    return EX_OSERR;
1374
1779
  }
1375
1780
  if(old_sigterm_action.sa_handler != SIG_IGN){
1376
1781
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1377
1782
    if(ret == -1){
1378
 
      perror("sigaction");
 
1783
      perror_plus("sigaction");
1379
1784
      exitcode = EX_OSERR;
1380
1785
      goto end;
1381
1786
    }
1382
1787
  }
1383
1788
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1384
1789
  if(ret == -1){
1385
 
    perror("sigaction");
 
1790
    perror_plus("sigaction");
1386
1791
    return EX_OSERR;
1387
1792
  }
1388
1793
  if(old_sigterm_action.sa_handler != SIG_IGN){
1389
1794
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1390
1795
    if(ret == -1){
1391
 
      perror("sigaction");
 
1796
      perror_plus("sigaction");
1392
1797
      exitcode = EX_OSERR;
1393
1798
      goto end;
1394
1799
    }
1411
1816
    errno = 0;
1412
1817
    ret = seteuid(0);
1413
1818
    if(ret == -1){
1414
 
      perror("seteuid");
 
1819
      perror_plus("seteuid");
1415
1820
    }
1416
1821
    
1417
1822
#ifdef __linux__
1421
1826
    bool restore_loglevel = true;
1422
1827
    if(ret == -1){
1423
1828
      restore_loglevel = false;
1424
 
      perror("klogctl");
 
1829
      perror_plus("klogctl");
1425
1830
    }
1426
1831
#endif  /* __linux__ */
1427
1832
    
1428
1833
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1429
1834
    if(sd < 0){
1430
 
      perror("socket");
 
1835
      perror_plus("socket");
1431
1836
      exitcode = EX_OSERR;
1432
1837
#ifdef __linux__
1433
1838
      if(restore_loglevel){
1434
1839
        ret = klogctl(7, NULL, 0);
1435
1840
        if(ret == -1){
1436
 
          perror("klogctl");
 
1841
          perror_plus("klogctl");
1437
1842
        }
1438
1843
      }
1439
1844
#endif  /* __linux__ */
1441
1846
      errno = 0;
1442
1847
      ret = seteuid(uid);
1443
1848
      if(ret == -1){
1444
 
        perror("seteuid");
 
1849
        perror_plus("seteuid");
1445
1850
      }
1446
1851
      goto end;
1447
1852
    }
1448
1853
    strcpy(network.ifr_name, interface);
1449
1854
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1450
1855
    if(ret == -1){
1451
 
      perror("ioctl SIOCGIFFLAGS");
 
1856
      perror_plus("ioctl SIOCGIFFLAGS");
1452
1857
#ifdef __linux__
1453
1858
      if(restore_loglevel){
1454
1859
        ret = klogctl(7, NULL, 0);
1455
1860
        if(ret == -1){
1456
 
          perror("klogctl");
 
1861
          perror_plus("klogctl");
1457
1862
        }
1458
1863
      }
1459
1864
#endif  /* __linux__ */
1462
1867
      errno = 0;
1463
1868
      ret = seteuid(uid);
1464
1869
      if(ret == -1){
1465
 
        perror("seteuid");
 
1870
        perror_plus("seteuid");
1466
1871
      }
1467
1872
      goto end;
1468
1873
    }
1472
1877
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1473
1878
      if(ret == -1){
1474
1879
        take_down_interface = false;
1475
 
        perror("ioctl SIOCSIFFLAGS +IFF_UP");
 
1880
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1476
1881
        exitcode = EX_OSERR;
1477
1882
#ifdef __linux__
1478
1883
        if(restore_loglevel){
1479
1884
          ret = klogctl(7, NULL, 0);
1480
1885
          if(ret == -1){
1481
 
            perror("klogctl");
 
1886
            perror_plus("klogctl");
1482
1887
          }
1483
1888
        }
1484
1889
#endif  /* __linux__ */
1486
1891
        errno = 0;
1487
1892
        ret = seteuid(uid);
1488
1893
        if(ret == -1){
1489
 
          perror("seteuid");
 
1894
          perror_plus("seteuid");
1490
1895
        }
1491
1896
        goto end;
1492
1897
      }
1493
1898
    }
1494
 
    /* sleep checking until interface is running */
 
1899
    /* Sleep checking until interface is running.
 
1900
       Check every 0.25s, up to total time of delay */
1495
1901
    for(int i=0; i < delay * 4; i++){
1496
1902
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1497
1903
      if(ret == -1){
1498
 
        perror("ioctl SIOCGIFFLAGS");
 
1904
        perror_plus("ioctl SIOCGIFFLAGS");
1499
1905
      } else if(network.ifr_flags & IFF_RUNNING){
1500
1906
        break;
1501
1907
      }
1502
1908
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1503
1909
      ret = nanosleep(&sleeptime, NULL);
1504
1910
      if(ret == -1 and errno != EINTR){
1505
 
        perror("nanosleep");
 
1911
        perror_plus("nanosleep");
1506
1912
      }
1507
1913
    }
1508
1914
    if(not take_down_interface){
1509
1915
      /* We won't need the socket anymore */
1510
1916
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1511
1917
      if(ret == -1){
1512
 
        perror("close");
 
1918
        perror_plus("close");
1513
1919
      }
1514
1920
    }
1515
1921
#ifdef __linux__
1517
1923
      /* Restores kernel loglevel to default */
1518
1924
      ret = klogctl(7, NULL, 0);
1519
1925
      if(ret == -1){
1520
 
        perror("klogctl");
 
1926
        perror_plus("klogctl");
1521
1927
      }
1522
1928
    }
1523
1929
#endif  /* __linux__ */
1527
1933
      /* Lower privileges */
1528
1934
      ret = seteuid(uid);
1529
1935
      if(ret == -1){
1530
 
        perror("seteuid");
 
1936
        perror_plus("seteuid");
1531
1937
      }
1532
1938
    } else {
1533
1939
      /* Lower privileges permanently */
1534
1940
      ret = setuid(uid);
1535
1941
      if(ret == -1){
1536
 
        perror("setuid");
 
1942
        perror_plus("setuid");
1537
1943
      }
1538
1944
    }
1539
1945
  }
1555
1961
    goto end;
1556
1962
  }
1557
1963
  
 
1964
  if(mkdtemp(tempdir) == NULL){
 
1965
    perror_plus("mkdtemp");
 
1966
    goto end;
 
1967
  }
1558
1968
  tempdir_created = true;
1559
 
  if(mkdtemp(tempdir) == NULL){
1560
 
    tempdir_created = false;
1561
 
    perror("mkdtemp");
1562
 
    goto end;
1563
 
  }
1564
1969
  
1565
1970
  if(quit_now){
1566
1971
    goto end;
1608
2013
    
1609
2014
    port = (uint16_t)tmpmax;
1610
2015
    *address = '\0';
1611
 
    address = connect_to;
1612
2016
    /* Colon in address indicates IPv6 */
1613
2017
    int af;
1614
 
    if(strchr(address, ':') != NULL){
 
2018
    if(strchr(connect_to, ':') != NULL){
1615
2019
      af = AF_INET6;
 
2020
      /* Accept [] around IPv6 address - see RFC 5952 */
 
2021
      if(connect_to[0] == '[' and address[-1] == ']')
 
2022
        {
 
2023
          connect_to++;
 
2024
          address[-1] = '\0';
 
2025
        }
1616
2026
    } else {
1617
2027
      af = AF_INET;
1618
2028
    }
 
2029
    address = connect_to;
1619
2030
    
1620
2031
    if(quit_now){
1621
2032
      goto end;
1622
2033
    }
1623
 
 
 
2034
    
1624
2035
    while(not quit_now){
1625
2036
      ret = start_mandos_communication(address, port, if_index, af);
1626
2037
      if(quit_now or ret == 0){
1627
2038
        break;
1628
2039
      }
1629
 
      sleep(15);
1630
 
    };
1631
 
 
 
2040
      if(debug){
 
2041
        fprintf(stderr, "Retrying in %d seconds\n",
 
2042
                (int)retry_interval);
 
2043
      }
 
2044
      sleep((int)retry_interval);
 
2045
    }
 
2046
    
1632
2047
    if (not quit_now){
1633
2048
      exitcode = EXIT_SUCCESS;
1634
2049
    }
1635
 
 
 
2050
    
1636
2051
    goto end;
1637
2052
  }
1638
2053
  
1690
2105
  if(debug){
1691
2106
    fprintf(stderr, "Starting Avahi loop search\n");
1692
2107
  }
1693
 
  
1694
 
  avahi_simple_poll_loop(mc.simple_poll);
 
2108
 
 
2109
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
2110
                                (int)(retry_interval * 1000));
 
2111
  if(debug){
 
2112
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
2113
            (ret == 0) ? "successfully" : "with error");
 
2114
  }
1695
2115
  
1696
2116
 end:
1697
2117
  
1718
2138
  if(gpgme_initialized){
1719
2139
    gpgme_release(mc.ctx);
1720
2140
  }
 
2141
 
 
2142
  /* Cleans up the circular linked list of Mandos servers the client
 
2143
     has seen */
 
2144
  if(mc.current_server != NULL){
 
2145
    mc.current_server->prev->next = NULL;
 
2146
    while(mc.current_server != NULL){
 
2147
      server *next = mc.current_server->next;
 
2148
      free(mc.current_server);
 
2149
      mc.current_server = next;
 
2150
    }
 
2151
  }
 
2152
  
 
2153
  /* XXX run network hooks "stop" here  */
1721
2154
  
1722
2155
  /* Take down the network interface */
1723
2156
  if(take_down_interface){
1725
2158
    errno = 0;
1726
2159
    ret = seteuid(0);
1727
2160
    if(ret == -1){
1728
 
      perror("seteuid");
 
2161
      perror_plus("seteuid");
1729
2162
    }
1730
2163
    if(geteuid() == 0){
1731
2164
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1732
2165
      if(ret == -1){
1733
 
        perror("ioctl SIOCGIFFLAGS");
 
2166
        perror_plus("ioctl SIOCGIFFLAGS");
1734
2167
      } else if(network.ifr_flags & IFF_UP) {
1735
2168
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1736
2169
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1737
2170
        if(ret == -1){
1738
 
          perror("ioctl SIOCSIFFLAGS -IFF_UP");
 
2171
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1739
2172
        }
1740
2173
      }
1741
2174
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1742
2175
      if(ret == -1){
1743
 
        perror("close");
 
2176
        perror_plus("close");
1744
2177
      }
1745
2178
      /* Lower privileges permanently */
1746
2179
      errno = 0;
1747
2180
      ret = setuid(uid);
1748
2181
      if(ret == -1){
1749
 
        perror("setuid");
 
2182
        perror_plus("setuid");
1750
2183
      }
1751
2184
    }
1752
2185
  }
1753
2186
  
1754
 
  /* Removes the temp directory used by GPGME */
 
2187
  /* Removes the GPGME temp directory and all files inside */
1755
2188
  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
 
        }
 
2189
    struct dirent **direntries = NULL;
 
2190
    struct dirent *direntry = NULL;
 
2191
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2192
                             alphasort);
 
2193
    if (numentries > 0){
 
2194
      for(int i = 0; i < numentries; i++){
 
2195
        direntry = direntries[i];
1776
2196
        char *fullname = NULL;
1777
2197
        ret = asprintf(&fullname, "%s/%s", tempdir,
1778
2198
                       direntry->d_name);
1779
2199
        if(ret < 0){
1780
 
          perror("asprintf");
 
2200
          perror_plus("asprintf");
1781
2201
          continue;
1782
2202
        }
1783
2203
        ret = remove(fullname);
1787
2207
        }
1788
2208
        free(fullname);
1789
2209
      }
1790
 
      closedir(d);
 
2210
    }
 
2211
 
 
2212
    /* need to clean even if 0 because man page doesn't specify */
 
2213
    free(direntries);
 
2214
    if (numentries == -1){
 
2215
      perror_plus("scandir");
1791
2216
    }
1792
2217
    ret = rmdir(tempdir);
1793
2218
    if(ret == -1 and errno != ENOENT){
1794
 
      perror("rmdir");
 
2219
      perror_plus("rmdir");
1795
2220
    }
1796
2221
  }
1797
2222
  
1802
2227
                                            &old_sigterm_action,
1803
2228
                                            NULL));
1804
2229
    if(ret == -1){
1805
 
      perror("sigaction");
 
2230
      perror_plus("sigaction");
1806
2231
    }
1807
2232
    do {
1808
2233
      ret = raise(signal_received);
1809
2234
    } while(ret != 0 and errno == EINTR);
1810
2235
    if(ret != 0){
1811
 
      perror("raise");
 
2236
      perror_plus("raise");
1812
2237
      abort();
1813
2238
    }
1814
2239
    TEMP_FAILURE_RETRY(pause());