iblock/main.c

56 lines
1.3 KiB
C
Raw Normal View History

2021-02-25 23:10:12 +00:00
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2021-02-25 23:10:12 +00:00
#include <netdb.h>
#include <netinet/in.h>
2021-02-28 09:54:36 +00:00
#include <syslog.h>
#include <unistd.h>
2021-02-25 23:10:12 +00:00
#include <sys/socket.h>
2022-08-22 12:50:40 +00:00
#define DEFAULT_TABLE "iblocked"
2022-08-22 12:50:27 +00:00
#define TABLE_LEN 32 /* see PF_TABLE_NAME_SIZE in net/pfvar.h */
int main(int argc, char *argv[]){
struct sockaddr_storage sock = {0};
socklen_t slen = sizeof(sock);
char ip[INET6_ADDRSTRLEN] = {'\0'}; /* INET6_ADDRSTRLEN > INET_ADDRSTRLEN */
char table[TABLE_LEN] = DEFAULT_TABLE;
int status = 0;
if (unveil("/usr/bin/doas", "rx") != 0)
err(1, "unveil");
if (pledge("exec inet stdio", NULL) != 0)
err(1, "pledge");
/* configuration */
2022-08-22 12:55:45 +00:00
if (argc == 2)
if (strlcpy(table, argv[1], TABLE_LEN) >= sizeof(table))
errx(1, "table name is too long");
2021-02-25 23:10:12 +00:00
/* get socket structure */
2022-08-22 12:56:21 +00:00
if (getpeername(STDIN_FILENO, (struct sockaddr *)&sock, &slen))
err(1, "getpeername");
/* get ip */
status = getnameinfo((struct sockaddr *)&sock, slen, ip, sizeof(ip),
NULL, 0, NI_NUMERICHOST);
2022-08-22 12:56:21 +00:00
if (status != 0) {
syslog(LOG_DAEMON, "getnameinfo error");
exit(1);
}
syslog(LOG_DAEMON, "blocking %s", ip);
2022-08-22 12:56:21 +00:00
switch (sock.ss_family) {
case AF_INET: /* FALLTHROUGHT */
case AF_INET6:
execlp("/usr/bin/doas", "doas", "/sbin/pfctl", "-t", table, "-T", "add", ip, NULL);
break;
default:
exit(2);
}
2021-02-25 23:10:12 +00:00
}