summaryrefslogtreecommitdiff
path: root/srcx/jkill.c
blob: 06854c52e1242512541b3c78041ec0aef2dd3acc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
/*
 * Copyright (c) 2004, Nate Nielsen
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     * Redistributions of source code must retain the above
 *       copyright notice, this list of conditions and the
 *       following disclaimer.
 *     * Redistributions in binary form must reproduce the
 *       above copyright notice, this list of conditions and
 *       the following disclaimer in the documentation and/or
 *       other materials provided with the distribution.
 *     * The names of contributors to this software may not be
 *       used to endorse or promote products derived from this
 *       software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 *
 *
 * CONTRIBUTORS
 *  Nate Nielsen <nielsen@memberwebs.com>
 *
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <sys/sysctl.h>
#include <sys/proc.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <sys/jail.h>

#include <paths.h>
#include <signal.h>
#include <stdio.h>
#include <syslog.h>
#include <err.h>
#include <errno.h>
#include <stdarg.h>
#include <unistd.h>
#include <kvm.h>
#include <limits.h>
#include <fcntl.h>

#include "util.h"

#ifdef HAVE_CONFIG_H
#include "../config.h"
#endif

/* The timeout to wait between kills */
#define        DEFAULT_TIMEOUT        3
int g_timeout = DEFAULT_TIMEOUT;

int g_quiet = 0;        /* Supress warnings */
int g_verbose = 0;      /* Print output from scripts */
int g_force = 0;        /* Use SIGKILL after if processes don't exit */
int g_usescripts = 1;   /* Call startup and shutdown scripts */
int g_restart = 0;      /* Restart jail after stop */

static int kill_jail(const char* jail);
static void kill_jail_processes(kvm_t* kd, int sig);
static int check_running_processes(kvm_t* kd);

static void parse_jail_opts(int argc, char* argv[]);
static void parse_host_opts(int argc, char* argv[]);

static void usage();
static void usage_jail();
static void usage_hr(const char* name);

int main(int argc, char* argv[])
{
    struct xprison* sxp = NULL;
    struct xprison* xp = NULL;
    size_t len;
    int jid, r, ret = 0;
    pid_t child;

    if(getuid() != 0)
        errx(1, "must run as root");

    /*
     * When running in a jail we do things slightly
     * differently, and accept different args
     */
    if(running_in_jail() != 0)
    {
        parse_jail_opts(argc, argv);

        /*
         * Turn into a daemon, so that we don't get disconnected
         * when we kill our parent program.
         */
        if(daemon(0, 1) == -1)
            err(1, "couldn't disconnect from console");

        r = kill_jail(argv[0]);
        exit(r);
    }

    else
    {
        parse_host_opts(argc, argv);

        argc -= optind;
        argv += optind;

        len = get_jail_sysctl(&sxp);

        /* For each jail */
        for(; argc > 0; argc--, argv++)
        {
            xp = find_jail(argv[0], len, sxp);

            if(xp == NULL)
            {
                warnx("unknown jail host name: %s", argv[0]);
                ret = 1;
                continue;
            }

            /* This makes sure we can use kvm funcs in jail */
            kvm_prepare_jail(xp);

            /*
             * We fork and the child goes into the jail and
             * does the dirty work. Unless in debug mode where
             * we just do one jail.
              */
#ifdef _DEBUG
            switch((child = fork()))
            {
            /* Error condition */
            case -1:
                err(1, "couldn't fork child process");
                break;

            /* The child */
            case 0:
#endif
                jid = xp->pr_id;

                /* Always free jail info before going into jail */
                free_jail_sysctl(len, sxp);

                if(jail_attach(jid) == -1)
                    err(1, "couldn't attach to jail");

                 r = kill_jail(argv[0]);
                 exit(r);
#ifdef _DEBUG
                 break;

            /* The parent */
            default:
                if(waitpid(child, &r, 0) == -1)
                     err(1, "error waiting for child process");

                if(WEXITSTATUS(r) != 0)
                    ret = WEXITSTATUS(r);
                break;
            };
#endif

            argc--;
            argv++;
        }

        free_jail_sysctl(len, sxp);
        return ret;
    }
}

static void parse_jail_opts(int argc, char* argv[])
{
    char* t;
    int ch;
    int ishr = 0;

    t = strchr(argv[0], '/');
    t = t ? t + 1 : argv[0];

    g_verbose = 1;
    g_force = 1;
    g_usescripts = 1;

    if(strcmp(t, "halt") == 0)
    {
        g_restart = 0;
        ishr = 1;
    }

    else if(strcmp(t, "reboot") == 0)
    {
        g_restart = 1;
        ishr = 1;
    }

    /* Options for jkill */
    if(!ishr)
    {
        while((ch = getopt(argc, argv, "rt:")) != -1)
        {
            switch(ch)
            {
            case 'r':
                g_restart = 1;
                break;

            /* Timeout to use between kills */
            case 't':
                g_timeout = atoi(optarg);
                if(g_timeout <= 0)
                    errx(2, "invalid timeout argument: %s", optarg);
                break;

            case '?':
            default:
                usage_jail();
                break;
            }
        }
    }

    /* These are the options for 'halt' and 'reboot' */
    else
    {
        while((ch = getopt(argc, argv, "dk:lnqp")) != -1)
        {
            switch(ch)
            {
            case 'd':
            case 'k':
            case 'l':
            case 'n':
            case 'q':
            case 'p':
                warnx("the '-%c' option is not supported from inside a jail", (char)ch);
                break;

            case '?':
            default:
                usage_hr(t);
                break;
            }
        }
    }

    argc -= optind;
    argv += optind;

    if(argc > 0)
    {
        if(ishr)
            usage_hr(t);
        else
            usage_jail();
    }
}

static void parse_host_opts(int argc, char* argv[])
{
    int ch;

    while((ch = getopt(argc, argv, "fhkqrt:v")) != -1)
    {
        switch(ch)
        {
        case 'f':
            g_force = 1;
            break;

        case 'h':
            /* dummy for compatibility with killjail */
            warnx("the '-h' option has been depreciated");
            break;

        case 'k':
            g_usescripts = 0;
            break;

        case 'q':
            g_quiet = 1;
            g_verbose = 0;
            break;

        case 'r':
            g_restart = 1;
            break;

        /* Timeout to use between kills */
        case 't':
            g_timeout = atoi(optarg);
            if(g_timeout <= 0)
                errx(2, "invalid timeout argument: %s", optarg);
            break;

        case 'v':
            g_verbose = 1;
            g_quiet = 0;
            break;

        case '?':
        default:
            usage();
            break;
        }
    }

    if(!g_usescripts && g_restart)
        usage();

    argc -= optind;
    argv += optind;

    if(argc <= 0)
        usage();
}

#define SHUTDOWN_SCRIPT "/etc/rc.shutdown"
static char* SHUTDOWN_ARGS[] = {    _PATH_BSHELL, SHUTDOWN_SCRIPT };

#define START_SCRIPT "/etc/rc"
static char* START_ARGS[] = {    _PATH_BSHELL, START_SCRIPT };

static int kill_jail(const char* jail)
{
    kvm_t* kd = NULL;
    char errbuf[_POSIX2_LINE_MAX];
    int pass = 0;
    int timeout = 0;
    int ret = 0;
    int cmdargs = JAIL_RUN_CONSOLE;

    /* Open the kernel interface */
    kd = kvm_openfiles(_PATH_DEVNULL, _PATH_DEVNULL, NULL, O_RDONLY, errbuf);
    if(kd == NULL)
        errx(1, "couldn't connect to kernel: %s", errbuf);

    if(g_verbose)
        cmdargs |= JAIL_RUN_STDERR;

    /*
     * Multiple passes are used to do different things.
     * Each time the jails processes are listed.
     */
    while(1)
    {
        while(timeout > 0)
        {
            sleep(1);
            timeout--;

            if(!check_running_processes(kd))
                goto done;
        }

        switch(pass)
        {
        /* First pass is an orderly shutdown */
        case 0:

            /* Check if we have an executable shutdown script */
            if(g_usescripts && check_jail_command(jail, SHUTDOWN_SCRIPT))
                run_jail_command(jail, SHUTDOWN_ARGS[0], SHUTDOWN_ARGS, cmdargs);

            break;

        /* Okay now quit all processes in jail */
        case 1:
            kill_jail_processes(kd, SIGTERM);
            timeout = g_timeout;
            break;

        /* ... and again ... */
        case 2:
            kill_jail_processes(kd, SIGTERM);
            timeout = g_timeout;
            break;

        /* Okay now we force kill the processes if necessary */
        case 3:

            if(g_force)
            {
                /* If we get here, jailer looks like it's really irresponsive */
                if(!g_quiet)
                    warnx("%s: jail won't stop. forcing jail termination...", jail);

                kill_jail_processes(kd, SIGKILL);
                timeout = g_timeout;
            }

            break;

        case 4:

            /* And if that didn't do it, well then give up */
            if(!g_quiet)
                warnx("%s: couldn't stop jail, processes wouldn't die", jail);

            ret = 1;
            goto done;
        }

        pass++;

        if(!check_running_processes(kd))
            goto done;
    }

done:
    if(g_restart)
    {
        /* Check if we have an executable shutdown script */
        if(check_jail_command(jail, START_SCRIPT))
            run_jail_command(jail, START_ARGS[0], START_ARGS, cmdargs);
    }

    if(kd != NULL)
        kvm_close(kd);

    return ret;
}

static void kill_jail_processes(kvm_t* kd, int sig)
{
    struct kinfo_proc* kp;
    int nentries, i;
    pid_t cur;

    cur = getpid();

    /* Get a process listing */
    if((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == 0)
        errx(1, "couldn't list processes: %s", kvm_geterr(kd));

    /* Okay now loop and look at each process' jail */
    for(i = 0; i < nentries; i++)
    {
        if(kp[i].ki_pid == cur)
            continue;

        if(kill(kp[i].ki_pid, sig) == -1)
        {
            if(errno != ESRCH)
                errx(1, "couldn't signal process: %d", (int)kp[i].ki_pid);
        }
    }
}

static int check_running_processes(kvm_t* kd)
{
    struct kinfo_proc* kp;
    int nentries, i;
    pid_t cur;

    cur = getpid();

    /* Get a process listing */
    if((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == 0)
        errx(1, "couldn't list processes: %s", kvm_geterr(kd));

    if(nentries != 1)
        return 1;

    /* Okay now loop and look at each process' jail */
    for(i = 0; i < nentries; i++)
    {
        if(kp[i].ki_pid != cur)
            return 1;
    }

    return 0;
}

static void usage()
{
    fprintf(stderr, "usage: jkill [-fkqv] [-t timeout] jail ...\n");
    fprintf(stderr, "       jkill -r [-fqv] [-t timeout] jail ...\n");
    exit(2);
}

static void usage_jail()
{
    fprintf(stderr, "usage: jkill [-r] [-t timeout]\n");
    exit(2);
}

static void usage_hr(const char* name)
{
    fprintf(stderr, "usage: %s\n", name);
    exit(2);
}