view src/pf.c @ 0:9f8d79c98fd2 0.4.0

initial public release
author Arkadiusz Juszczyk <ark@wobblyhead.net>
date 2026-10-26 11:29 +0100
parents
children
line wrap: on
line source

/*
 * Copyright (c) 2026 Arkadiusz Juszczyk <ark@wobblyhead.net>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <sys/types.h>
#include <sys/wait.h>

#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <spawn.h>
#include <stdint.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>

#include "botblockd.h"

#define PFCTL_PATH  "/sbin/pfctl"

extern char **environ;

/*
 * pfctl - run pfctl with the given arguments, report success
 *
 * pfctl is started directly, without a shell, and inherits our
 * environment, stdin, stdout and stderr, so -T show output reaches the
 * terminal for the list verb.  All signals are reset to their default
 * action and unblocked in the child, so the SIGPIPE we ignore does not
 * carry over.
 *
 * Parameters:
 *   argv    - NULL-terminated argument vector, argv[0] is "pfctl"
 *   discard - true to send pfctl's stdout to /dev/null, stderr is kept
 *
 * Returns: 0 if pfctl ran and exited with status 0, -1 otherwise
 */
static int
pfctl(const char *argv[], bool discard)
{
    posix_spawn_file_actions_t fa;
    posix_spawnattr_t attr;
    sigset_t sigs;
    pid_t pid;
    int err, status;

    posix_spawn_file_actions_init(&fa);
    if (discard)
        posix_spawn_file_actions_addopen(&fa, STDOUT_FILENO,
            "/dev/null", O_WRONLY, 0);
    posix_spawnattr_init(&attr);
    posix_spawnattr_setflags(&attr,
        POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK);
    sigfillset(&sigs);
    posix_spawnattr_setsigdefault(&attr, &sigs);
    sigemptyset(&sigs);
    posix_spawnattr_setsigmask(&attr, &sigs);

    err = posix_spawn(&pid, PFCTL_PATH, &fa, &attr,
        __DECONST(char **, argv), environ);
    posix_spawnattr_destroy(&attr);
    posix_spawn_file_actions_destroy(&fa);
    if (err != 0) {
        syslog(LOG_ERR, "cannot run %s: %s", PFCTL_PATH, strerror(err));
        return (-1);
    }

    /* a signal arriving while pfctl runs must not abandon the child */
    while (waitpid(pid, &status, 0) == -1) {
        if (errno != EINTR) {
            syslog(LOG_ERR, "waitpid: %s", strerror(errno));
            return (-1);
        }
    }
    if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
        return (-1);
    return (0);
}

/*
 * pf_table_op - run "pfctl -q -t <table> -T <op> [arg]", report success
 *
 * -q drops pfctl's "N addresses added/deleted" messages but keeps
 * errors and the output of -T show.
 *
 * Parameters:
 *   op      - pfctl table operation (add, delete, show, flush)
 *   arg     - address argument, or NULL for whole-table operations
 *   discard - true to send pfctl's stdout to /dev/null
 *
 * Returns: 0 on success, -1 on failure
 */
static int
pf_table_op(const char *op, const char *arg, bool discard)
{
    /* a NULL arg ends the vector early */
    const char *argv[] = {
        "pfctl", "-q", "-t", PF_TABLE, "-T", op, arg, NULL
    };

    return (pfctl(argv, discard));
}

/*
 * pf_kill_states - remove all pf states originating from an address
 *
 * The block rule only applies to packets without a state, so
 * connections already established by the address would otherwise
 * survive the block.  -q drops pfctl's "killed N states" message.
 *
 * Parameters:
 *   ips - IPv4 address as a string
 *
 * Returns: 0 on success, -1 on failure
 */
static int
pf_kill_states(const char *ips)
{
    const char *argv[] = { "pfctl", "-q", "-k", ips, NULL };

    return (pfctl(argv, false));
}

/*
 * pf_block - add an IP to the pf block table and cut its connections
 *
 * The address is added to the table before its states are killed, so
 * it cannot open a new connection in between.  A failure to kill the
 * states is logged but does not fail the block.
 *
 * Parameters:
 *   ip - IPv4 address (network byte order)
 *
 * Returns: 0 on success, -1 on failure
 */
int
pf_block(uint32_t ip)
{
    const char *ips = ip_str(ip);

    if (pf_table_op("add", ips, false) != 0) {
        syslog(LOG_ERR, "pf block failed for %s", ips);
        return (-1);
    }
    if (pf_kill_states(ips) != 0)
        syslog(LOG_WARNING, "cannot kill pf states for %s", ips);
    syslog(LOG_NOTICE, "%s blocked", ips);
    return (0);
}

/*
 * pf_unblock - remove an IP from the pf block table
 *
 * Parameters:
 *   ip - IPv4 address (network byte order)
 *
 * Returns: 0 on success, -1 on failure
 */
int
pf_unblock(uint32_t ip)
{
    return (pf_table_op("delete", ip_str(ip), false));
}

/*
 * pf_show - print the block table, or only check that it is available
 *
 * With quiet, the check verb catches a missing table up front rather
 * than having the first block attempt fail at runtime.  stdout is
 * discarded so the table's contents are not printed, but pfctl's
 * stderr is kept so its diagnostic (a missing table, pf disabled, or a
 * permission error) reaches the operator.
 *
 * Parameters:
 *   quiet - true to check the table without printing it
 *
 * Returns: 0 if the table is present and readable, -1 otherwise
 */
int
pf_show(bool quiet)
{
    return (pf_table_op("show", NULL, quiet));
}

/*
 * pf_flush - remove every entry from the block table
 *
 * Used by the "unblock -a" CLI verb, and at daemon startup and
 * shutdown to leave no blocks without a record behind.  Flushing the
 * whole table is correct in all cases: botblockd owns the table, so
 * any entry in it is one it placed.
 *
 * Returns: 0 on success, -1 on failure
 */
int
pf_flush(void)
{
    return (pf_table_op("flush", NULL, false));
}