├── .gitignore ├── demo.gif ├── kernel ├── arch │ ├── 0001-snitch.patch │ ├── PKGBUILD │ ├── config │ ├── config.sh │ └── readme.md └── debian │ └── todo ├── license.txt ├── readme.md ├── snitch-prompt ├── color ├── count-last ├── setup.py └── snitch-prompt └── snitch ├── build.sh ├── snitch.c ├── snitch.sh ├── util ├── array.h ├── map.h ├── nft.h ├── nl.h ├── queue.h └── util.h └── vendor ├── xxh3.h └── xxhash.h /.gitignore: -------------------------------------------------------------------------------- 1 | snitch/snitch 2 | *.egg-info 3 | src/ 4 | pkg/ 5 | archlinux-linux 6 | linux-* 7 | -------------------------------------------------------------------------------- /demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nathants/mighty-snitch/5cf7d3cf010d58d3c4334b7f0dbdb5cd50f9f4ab/demo.gif -------------------------------------------------------------------------------- /kernel/arch/0001-snitch.patch: -------------------------------------------------------------------------------- 1 | diff --git a/include/uapi/linux/lsm.h b/include/uapi/linux/lsm.h 2 | index 938593dfd..78af7ff83 100644 3 | --- a/include/uapi/linux/lsm.h 4 | +++ b/include/uapi/linux/lsm.h 5 | @@ -64,7 +64,8 @@ struct lsm_ctx { 6 | #define LSM_ID_LANDLOCK 110 7 | #define LSM_ID_IMA 111 8 | #define LSM_ID_EVM 112 9 | -#define LSM_ID_IPE 113 10 | +#define LSM_ID_IPE 113 11 | +#define LSM_ID_SNITCH 114 12 | 13 | /* 14 | * LSM_ATTR_XXX definitions identify different LSM attributes 15 | diff --git a/security/Kconfig b/security/Kconfig 16 | index 28e685f53..f55314838 100644 17 | --- a/security/Kconfig 18 | +++ b/security/Kconfig 19 | @@ -220,6 +220,7 @@ source "security/smack/Kconfig" 20 | source "security/tomoyo/Kconfig" 21 | source "security/apparmor/Kconfig" 22 | source "security/loadpin/Kconfig" 23 | +source "security/snitch/Kconfig" 24 | source "security/yama/Kconfig" 25 | source "security/safesetid/Kconfig" 26 | source "security/lockdown/Kconfig" 27 | @@ -281,4 +282,3 @@ config LSM 28 | source "security/Kconfig.hardening" 29 | 30 | endmenu 31 | - 32 | diff --git a/security/Makefile b/security/Makefile 33 | index cc0982214..3201771ea 100644 34 | --- a/security/Makefile 35 | +++ b/security/Makefile 36 | @@ -20,6 +20,7 @@ obj-$(CONFIG_SECURITY_TOMOYO) += tomoyo/ 37 | obj-$(CONFIG_SECURITY_APPARMOR) += apparmor/ 38 | obj-$(CONFIG_SECURITY_YAMA) += yama/ 39 | obj-$(CONFIG_SECURITY_LOADPIN) += loadpin/ 40 | +obj-$(CONFIG_SECURITY_SNITCH) += snitch/ 41 | obj-$(CONFIG_SECURITY_SAFESETID) += safesetid/ 42 | obj-$(CONFIG_SECURITY_LOCKDOWN_LSM) += lockdown/ 43 | obj-$(CONFIG_CGROUPS) += device_cgroup.o 44 | diff --git a/security/security.c b/security/security.c 45 | index c5981e558..c055cba66 100644 46 | --- a/security/security.c 47 | +++ b/security/security.c 48 | @@ -450,14 +450,14 @@ static void __init ordered_lsm_init(void) 49 | { 50 | struct lsm_info **lsm; 51 | 52 | - if (chosen_lsm_order) { 53 | - if (chosen_major_lsm) { 54 | - pr_warn("security=%s is ignored because it is superseded by lsm=%s\n", 55 | - chosen_major_lsm, chosen_lsm_order); 56 | - chosen_major_lsm = NULL; 57 | - } 58 | - ordered_lsm_parse(chosen_lsm_order, "cmdline"); 59 | - } else 60 | + /* if (chosen_lsm_order) { */ 61 | + /* if (chosen_major_lsm) { */ 62 | + /* pr_warn("security=%s is ignored because it is superseded by lsm=%s\n", */ 63 | + /* chosen_major_lsm, chosen_lsm_order); */ 64 | + /* chosen_major_lsm = NULL; */ 65 | + /* } */ 66 | + /* ordered_lsm_parse(chosen_lsm_order, "cmdline"); */ 67 | + /* } else */ 68 | ordered_lsm_parse(builtin_lsm_order, "builtin"); 69 | 70 | for (lsm = ordered_lsms; *lsm; lsm++) 71 | diff --git a/security/snitch/Kconfig b/security/snitch/Kconfig 72 | new file mode 100644 73 | index 000000000..7fbe23cf6 74 | --- /dev/null 75 | +++ b/security/snitch/Kconfig 76 | @@ -0,0 +1,10 @@ 77 | +config SECURITY_SNITCH 78 | + bool "SNITCH" 79 | + depends on SECURITY && NET 80 | + select SECURITY_PATH 81 | + select SECURITYFS 82 | + select SECURITY_NETWORK 83 | + default y 84 | + help 85 | + This selects SNITCH 86 | + If you are unsure how to answer this question, answer N. 87 | diff --git a/security/snitch/Makefile b/security/snitch/Makefile 88 | new file mode 100644 89 | index 000000000..9305bf5cb 90 | --- /dev/null 91 | +++ b/security/snitch/Makefile 92 | @@ -0,0 +1,3 @@ 93 | +obj-$(CONFIG_SECURITY_SNITCH) := snitch.o 94 | + 95 | +snitch-y := hashtable.o snitch.o 96 | diff --git a/security/snitch/hashtable.c b/security/snitch/hashtable.c 97 | new file mode 100644 98 | index 000000000..e4fa8522c 99 | --- /dev/null 100 | +++ b/security/snitch/hashtable.c 101 | @@ -0,0 +1,78 @@ 102 | +#include 103 | + 104 | +#include "hashtable.h" 105 | + 106 | +int hashtable_set(struct hashtable *hashtable, uint32_t key, uint64_t value) { 107 | + struct hashtable_node *node; 108 | + if (!hashtable) 109 | + return -1; 110 | + hash_for_each_possible(hashtable->table, node, hlist, key) { 111 | + if (node->key == key) { 112 | + node->value = value; 113 | + return 0; 114 | + } 115 | + } 116 | + node = kmalloc(sizeof(*node), GFP_ATOMIC); 117 | + if (node == NULL) { 118 | + return -ENOMEM; 119 | + } 120 | + node->key = key; 121 | + node->value = value; 122 | + hash_add(hashtable->table, &node->hlist, key); 123 | + return 0; 124 | +} 125 | + 126 | +int hashtable_delete(struct hashtable *hashtable, uint32_t key) { 127 | + struct hashtable_node *node; 128 | + if (!hashtable) 129 | + return -1; 130 | + hash_for_each_possible(hashtable->table, node, hlist, key) { 131 | + if (node->key == key) { 132 | + hash_del(&node->hlist); 133 | + kfree(node); 134 | + return 0; 135 | + } 136 | + } 137 | + return -1; 138 | +} 139 | + 140 | +struct hashtable_resp hashtable_get_locking(struct hashtable *hashtable, uint32_t key) { 141 | + spin_lock_bh(&hashtable->lock); 142 | + struct hashtable_resp resp = hashtable_get(hashtable, key); 143 | + spin_unlock_bh(&hashtable->lock); 144 | + return resp; 145 | +} 146 | + 147 | +struct hashtable_resp hashtable_get(struct hashtable *hashtable, uint32_t key) { 148 | + struct hashtable_resp resp = {0}; 149 | + struct hashtable_node *node; 150 | + if (!hashtable) { 151 | + resp.error = 1; 152 | + return resp; 153 | + } 154 | + hash_for_each_possible(hashtable->table, node, hlist, key) { 155 | + if (node->key == key) { 156 | + resp.value = node->value; 157 | + return resp; 158 | + } 159 | + } 160 | + resp.error = 2; 161 | + return resp; 162 | +} 163 | + 164 | +void hashtable_free(struct hashtable *hashtable) { 165 | + int i = 0; 166 | + struct hashtable_node *node; 167 | + struct hlist_node *tmp; 168 | + if (!hashtable) 169 | + return; 170 | + hash_for_each_safe(hashtable->table, i, tmp, node, hlist) { 171 | + hash_del(&node->hlist); 172 | + kfree(node); 173 | + } 174 | +} 175 | + 176 | +void hashtable_init(struct hashtable *hashtable) { 177 | + hash_init(hashtable->table); 178 | + spin_lock_init(&hashtable->lock); 179 | +} 180 | diff --git a/security/snitch/hashtable.h b/security/snitch/hashtable.h 181 | new file mode 100644 182 | index 000000000..f04f9d24c 183 | --- /dev/null 184 | +++ b/security/snitch/hashtable.h 185 | @@ -0,0 +1,37 @@ 186 | +#ifndef HASHTABLE_H 187 | +#define HASHTABLE_H 188 | + 189 | +#include 190 | +#include 191 | + 192 | +#define HASHTABLE_DEFAULT_SIZE 2048 193 | + 194 | +struct hashtable { 195 | + DECLARE_HASHTABLE(table, ilog2(HASHTABLE_DEFAULT_SIZE)); 196 | + spinlock_t lock __attribute__((aligned(64))); 197 | +}; 198 | + 199 | +struct hashtable_node { 200 | + uint64_t value; 201 | + uint32_t key; 202 | + struct hlist_node hlist; 203 | +}; 204 | + 205 | +struct hashtable_resp { 206 | + uint64_t value; 207 | + uint8_t error; 208 | +}; 209 | + 210 | +struct hashtable_resp hashtable_get_locking(struct hashtable *hashtable, uint32_t key); 211 | + 212 | +struct hashtable_resp hashtable_get(struct hashtable *hashtable, uint32_t key); 213 | + 214 | +int hashtable_delete(struct hashtable *hashtable, uint32_t key); 215 | + 216 | +int hashtable_set(struct hashtable *hashtable, uint32_t key, uint64_t value); 217 | + 218 | +void hashtable_free(struct hashtable *hashtable); 219 | + 220 | +void hashtable_init(struct hashtable *hashtable); 221 | + 222 | +#endif /** HASHTABLE_H */ 223 | diff --git a/security/snitch/snitch.c b/security/snitch/snitch.c 224 | new file mode 100644 225 | index 000000000..8a2ccffc4 226 | --- /dev/null 227 | +++ b/security/snitch/snitch.c 228 | @@ -0,0 +1,352 @@ 229 | +/* 230 | + * Copyright (C) 2019 Argus Cyber Security Ltd, Tel Aviv. 231 | + * Copyright (C) 2022-present Nathan Todd-Stone 232 | + * 233 | + * This program is free software: you can redistribute it and/or modify 234 | + * it under the terms of the GNU General Public License as published by 235 | + * the Free Software Foundation, either version 3 of the License, or 236 | + * (at your option) any later version. 237 | + * 238 | + * This program is distributed in the hope that it will be useful, 239 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of 240 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 241 | + * GNU General Public License for more details. 242 | + * 243 | + * You should have received a copy of the GNU General Public License 244 | + * along with this program. If not, see . 245 | + * 246 | + */ 247 | + 248 | +#include 249 | +#include 250 | +#include 251 | +#include 252 | +#include 253 | +#include 254 | +#include 255 | +#include 256 | +#include 257 | +#include 258 | +#include 259 | +#include 260 | +#include 261 | +#include 262 | +#include 263 | +#include 264 | +#include 265 | +#include 266 | +#include 267 | +#include 268 | + 269 | +#include "hashtable.h" 270 | + 271 | +MODULE_AUTHOR("nathants"); 272 | +MODULE_DESCRIPTION("might-snitch"); 273 | +MODULE_LICENSE("GPL"); 274 | +MODULE_VERSION("1.0"); 275 | + 276 | +int user_pid; 277 | + 278 | +struct sock *nl_sk; 279 | + 280 | +atomic_t counter = ATOMIC_INIT(0); 281 | + 282 | +struct hashtable hashtable_responses; 283 | + 284 | +DECLARE_WAIT_QUEUE_HEAD(wait_queue_responses); 285 | + 286 | +spinlock_t netlink_lock __attribute__((aligned(64))); 287 | + 288 | +#define NETLINK_USER 31 289 | + 290 | +#define ALLOW 0 291 | +#define DENY 1 292 | + 293 | +#define print(format, args...) \ 294 | + printk(KERN_INFO "snitch: " format "\n", ##args) 295 | + 296 | +#define NO_USERSPACE() \ 297 | + user_pid == 0 298 | + 299 | +struct file *get_exe_file(struct task_struct *task) { 300 | + struct file *exe_file = NULL; 301 | + struct mm_struct *mm; 302 | + task_lock(task); 303 | + mm = task->mm; 304 | + if (mm) { 305 | + if (!(task->flags & PF_KTHREAD)) { 306 | + exe_file = get_mm_exe_file(mm); 307 | + } 308 | + } 309 | + task_unlock(task); 310 | + return exe_file; 311 | +} 312 | + 313 | +void netlink_recv(struct sk_buff *skb) { 314 | + spin_lock_bh(&netlink_lock); 315 | + struct nlmsghdr *nlh = (struct nlmsghdr*)skb->data; 316 | + int size = nlh->nlmsg_len - NLMSG_HDRLEN; 317 | + if (size < sizeof(int) * 2) { 318 | + print("bad netlink message size: %d", size); 319 | + spin_unlock_bh(&netlink_lock); 320 | + return; 321 | + } 322 | + int id = *(int*)nlmsg_data(nlh); 323 | + int response = *(int*)(nlmsg_data(nlh) + sizeof(int)); 324 | + int pid = nlh->nlmsg_pid; 325 | + if (NO_USERSPACE() && pid != 0) { 326 | + print("user started %d", pid); 327 | + user_pid = pid; 328 | + } else { 329 | + spin_lock_bh(&hashtable_responses.lock); 330 | + int res = hashtable_set(&hashtable_responses, id, response); 331 | + spin_unlock_bh(&hashtable_responses.lock); 332 | + if (res == 0) { 333 | + wake_up(&wait_queue_responses); 334 | + } else { 335 | + print("err on hashtable set: %d", res); 336 | + } 337 | + } 338 | + spin_unlock_bh(&netlink_lock); 339 | +} 340 | + 341 | +int netlink_send(const char *msg, int msg_size) { 342 | + spin_lock_bh(&netlink_lock); 343 | + struct sk_buff *skb_out = nlmsg_new(msg_size, 0); 344 | + if (!skb_out) { 345 | + spin_unlock_bh(&netlink_lock); 346 | + return -1; 347 | + } 348 | + struct nlmsghdr *nlh = nlmsg_put(skb_out, 0, 0, NLMSG_DONE, msg_size, 0); 349 | + NETLINK_CB(skb_out).dst_group = 0; 350 | + memcpy(nlmsg_data(nlh), msg, msg_size); 351 | + int res = nlmsg_unicast(nl_sk, skb_out, user_pid); 352 | + if (res < 0) { 353 | + spin_unlock_bh(&netlink_lock); 354 | + return -1; 355 | + } 356 | + spin_unlock_bh(&netlink_lock); 357 | + return 0; 358 | +} 359 | + 360 | +int __init netlink_init(void) { 361 | + struct netlink_kernel_cfg cfg = { .input = netlink_recv }; 362 | + nl_sk = netlink_kernel_create(&init_net, NETLINK_USER, &cfg); 363 | + if (!nl_sk) 364 | + return -1; 365 | + return 0; 366 | +} 367 | + 368 | +#define SNITCH_INIT(name) \ 369 | + int pid = current->pid; \ 370 | + int tgid = current->tgid; \ 371 | + int id = atomic_fetch_inc(&counter); \ 372 | + int size = 0; \ 373 | + char type = 0; \ 374 | + char namebuf[24] = {0}; \ 375 | + snprintf(namebuf, sizeof(namebuf), name); \ 376 | + char tempbuf[240] = {0}; \ 377 | + char *temp = NULL; \ 378 | + char exebuf[240] = {0}; \ 379 | + char cmdlinebuf[240] = {0}; \ 380 | + char databuf[240] = {0}; \ 381 | + char *head = NULL; 382 | + 383 | +#define SEND_RECV() \ 384 | + char message[sizeof(id) + \ 385 | + sizeof(tgid) + /* tgid is userspace pid */ \ 386 | + sizeof(type) + \ 387 | + sizeof(namebuf) + \ 388 | + sizeof(exebuf) + \ 389 | + sizeof(cmdlinebuf) + \ 390 | + sizeof(databuf)] = {0}; \ 391 | + head = message; \ 392 | + size = sizeof(id); memcpy(head, &id, size); head += size; \ 393 | + size = sizeof(tgid); memcpy(head, &tgid, size); head += size; \ 394 | + size = sizeof(type); memcpy(head, &type, size); head += size; \ 395 | + size = sizeof(namebuf); memcpy(head, namebuf, size); head += size; \ 396 | + size = sizeof(exebuf); memcpy(head, exebuf, size); head += size; \ 397 | + size = sizeof(cmdlinebuf); memcpy(head, cmdlinebuf, size); head += size; \ 398 | + size = sizeof(databuf); memcpy(head, databuf, size); head += size; \ 399 | + int i = 0; \ 400 | + while (1) { \ 401 | + i++; \ 402 | + if (NO_USERSPACE()) { \ 403 | + return DENY; \ 404 | + } \ 405 | + int send_res = netlink_send(message, sizeof(message)); \ 406 | + if (send_res != 0) { \ 407 | + print("send-failed id: %d, attempt: %d, name: %s, exe: %s, cmdline: %s, send_res: %d", id, i, namebuf, exebuf, cmdlinebuf, send_res); \ 408 | + usleep_range(500, 1000); \ 409 | + continue; \ 410 | + } \ 411 | + if (wait_event_timeout(wait_queue_responses, hashtable_get_locking(&hashtable_responses, id).error == 0, 1 * HZ) != 0) { \ 412 | + spin_lock_bh(&hashtable_responses.lock); \ 413 | + int ret = hashtable_get(&hashtable_responses, id).value; \ 414 | + hashtable_delete(&hashtable_responses, id); \ 415 | + spin_unlock_bh(&hashtable_responses.lock); \ 416 | + return ret; \ 417 | + } else { \ 418 | + /* don't log failure here because a recv failure is expected when waiting for user interaction at the ui prompt */ \ 419 | + usleep_range(500, 1000); \ 420 | + continue; \ 421 | + } \ 422 | + } 423 | + 424 | +#define READ_CMDLINE(task, buf) \ 425 | + if (get_cmdline(task, buf, sizeof(buf) - 1) == 0) \ 426 | + strcpy(buf, ""); 427 | + 428 | +#define READ_EXE(task, buf) \ 429 | + struct file *exe_file = get_exe_file(task); \ 430 | + if (exe_file) { \ 431 | + memset(tempbuf, 0, sizeof(tempbuf)); \ 432 | + temp = d_absolute_path(&exe_file->f_path, tempbuf, sizeof(tempbuf) - 1); \ 433 | + if (!temp) { \ 434 | + strcpy(buf, ""); \ 435 | + } else { \ 436 | + head = tempbuf; \ 437 | + size = sizeof(tempbuf) - 1; \ 438 | + while (size > 0) { \ 439 | + if (head[0] != 0) \ 440 | + break; \ 441 | + size--; \ 442 | + head++; \ 443 | + } \ 444 | + strncpy(buf, head, size); \ 445 | + } \ 446 | + } else { \ 447 | + strcpy(buf, ""); \ 448 | + } 449 | + 450 | +void snitch_task_free(struct task_struct *task) { 451 | + if (user_pid == task->tgid && user_pid != 0) { 452 | + print("user exited %d", task->tgid); 453 | + user_pid = 0; 454 | + } 455 | +} 456 | + 457 | +int snitch_socket_sendmsg(struct socket *sock, struct msghdr *msg, int _msgsize) { 458 | + SNITCH_INIT("socket_sendmsg"); 459 | + READ_CMDLINE(current, cmdlinebuf); 460 | + READ_EXE(current, exebuf); 461 | + if (msg && msg->msg_namelen > 0) { 462 | + memcpy(databuf, msg->msg_name, msg->msg_namelen); 463 | + } else { 464 | + struct sockaddr_storage remote = {0}; 465 | + int res = sock->ops->getname(sock, (struct sockaddr*)&remote, 2); 466 | + if (res < 0) { 467 | + if (strcmp("/usr/bin/dhcpcd", exebuf) == 0) 468 | + return ALLOW; // why does arch need this? 469 | + print("exe=%s cmdline=[%s] sendmsg get remote addr failure", exebuf, cmdlinebuf); 470 | + return DENY; 471 | + } 472 | + memcpy(databuf, &remote, sizeof(remote)); 473 | + } 474 | + if (sock) { 475 | + type = (char)sock->type; 476 | + } 477 | + struct sockaddr *sa = (struct sockaddr*)databuf; 478 | + if (sa->sa_family == AF_INET6) { 479 | + // deny ipv6 480 | + return DENY; 481 | + } else if (sa->sa_family == AF_INET) { 482 | + // userspace decides ipv4 483 | + SEND_RECV(); 484 | + } else { 485 | + // allow everything else 486 | + return ALLOW; 487 | + } 488 | +} 489 | + 490 | +int snitch_socket_recvmsg(struct socket *sock, struct msghdr *msg, int _size, int _flags) { 491 | + SNITCH_INIT("socket_recvmsg"); 492 | + READ_CMDLINE(current, cmdlinebuf); 493 | + READ_EXE(current, exebuf); 494 | + if (msg && msg->msg_namelen > 0) { 495 | + memcpy(databuf, msg->msg_name, msg->msg_namelen); 496 | + } else { 497 | + struct sockaddr_storage local = {0}; 498 | + if (sock->ops->getname(sock, (struct sockaddr*)&local, 0) < 0) { 499 | + print("exe=%s cmdline=[%s] recvmsg get local addr failure", exebuf, cmdlinebuf); 500 | + return DENY; 501 | + } 502 | + memcpy(databuf, &local, sizeof(local)); 503 | + } 504 | + if (sock) { 505 | + type = (char)sock->type; 506 | + } 507 | + struct sockaddr *sa = (struct sockaddr*)databuf; 508 | + if (sa->sa_family == AF_INET6) { 509 | + // deny ipv6 510 | + return DENY; 511 | + } else if (sa->sa_family == AF_INET) { 512 | + // userspace decides ipv4 513 | + SEND_RECV(); 514 | + } else { 515 | + // allow everything else 516 | + return ALLOW; 517 | + } 518 | +} 519 | + 520 | +int snitch_uring_override_creds(const struct cred *new) { 521 | + return DENY; 522 | +} 523 | + 524 | +int snitch_uring_sqpoll(void) { 525 | + return DENY; 526 | +} 527 | + 528 | +int snitch_uring_cmd(struct io_uring_cmd *ioucmd) { 529 | + return DENY; 530 | +} 531 | + 532 | +static struct security_hook_list snitch_ops[] __ro_after_init = { 533 | + 534 | + // task cleanup 535 | + LSM_HOOK_INIT(task_free, snitch_task_free), 536 | + 537 | + // network filtering 538 | + LSM_HOOK_INIT(socket_recvmsg, snitch_socket_recvmsg), 539 | + LSM_HOOK_INIT(socket_sendmsg, snitch_socket_sendmsg), 540 | + 541 | + // disable io_uring since it circumvents security 542 | + LSM_HOOK_INIT(uring_override_creds, snitch_uring_override_creds), 543 | + LSM_HOOK_INIT(uring_sqpoll, snitch_uring_sqpoll), 544 | + LSM_HOOK_INIT(uring_cmd, snitch_uring_cmd), 545 | + 546 | +}; 547 | + 548 | +static const struct lsm_id snitch_lsmid = { 549 | + .name = "snitch", 550 | + .id = LSM_ID_SNITCH, 551 | +}; 552 | + 553 | +static int __init snitch_security_init(void) { 554 | + print("security_initcall start"); 555 | + user_pid = 0; 556 | + spin_lock_init(&netlink_lock); 557 | + hashtable_init(&hashtable_responses); 558 | + security_add_hooks(snitch_ops, ARRAY_SIZE(snitch_ops), &snitch_lsmid); 559 | + print("security_initcall finished successfully"); 560 | + return 0; 561 | +} 562 | + 563 | +static int __init snitch_late_initcall(void) { 564 | + int res = netlink_init(); 565 | + if (res) 566 | + print("late_initcall failed %d", res); 567 | + print("late_initcall finished successfully"); 568 | + return 0; 569 | +} 570 | + 571 | +int snitch_enabled __ro_after_init = 1; 572 | + 573 | +DEFINE_LSM(snitch) = { 574 | + .name = "snitch", 575 | + .init = snitch_security_init, 576 | + .flags = LSM_FLAG_EXCLUSIVE, 577 | + .enabled = &snitch_enabled, 578 | +}; 579 | + 580 | +late_initcall(snitch_late_initcall); 581 | -------------------------------------------------------------------------------- /kernel/arch/PKGBUILD: -------------------------------------------------------------------------------- 1 | pkgbase=linux 2 | ver=6.14.6 3 | pkgver=$ver.arch1 4 | _srcname=linux-$ver 5 | pkgrel=1 6 | pkgdesc='Linux' 7 | _srctag=v${pkgver%.*}-${pkgver##*.} 8 | arch=(x86_64) 9 | license=(GPL-2.0-only) 10 | depends=( 11 | libnetfilter_queue python-blessed linux-headers nftables 12 | ) 13 | makedepends=( 14 | bc libelf pahole cpio perl tar xz python 15 | xmlto python-sphinx python-yaml graphviz imagemagick texlive-latexextra 16 | git 17 | rust rust-bindgen rust-src 18 | ) 19 | options=( 20 | '!debug' 21 | '!strip' 22 | ) 23 | source=( 24 | "$_srcname.tar::https://cdn.kernel.org/pub/linux/kernel/v6.x/$_srcname.tar.xz" 25 | config 26 | 0001-snitch.patch 27 | ) 28 | b2sums=('dedcadc0b7506f620da3ac849446539e83d694f0955d5417e063b6680d53ef8993eeef40562ae8dae9249a21bea9746093f8873a360dd74f6b139fbafdd7b9ac' 29 | '78583b6b6b0a2a52279d3f073e0d717744b84b5486401994d78b39d98e5af91ef48c4e3a2d73bf90f188929e1d916fb260b5875bde7d3128acc9be80cab4a3de' 30 | 'a91c4c5ed1524354ce66d42a1a451c0a04e51ca43e4622263217aadc71e8bb7a7b915257878af5b47e74563f6a058fda1512f91839ef12f3433f186026a737c2') 31 | 32 | export KBUILD_BUILD_HOST=archlinux 33 | export KBUILD_BUILD_USER=$pkgbase 34 | export KBUILD_BUILD_TIMESTAMP="$(date -Ru${SOURCE_DATE_EPOCH:+d @$SOURCE_DATE_EPOCH})" 35 | 36 | prepare() { 37 | cd $_srcname 38 | 39 | echo "Setting version..." 40 | echo "-$pkgrel" > localversion.10-pkgrel 41 | echo "${pkgbase#linux}" > localversion.20-pkgname 42 | 43 | local src 44 | for src in "${source[@]}"; do 45 | src="${src%%::*}" 46 | src="${src##*/}" 47 | src="${src%.zst}" 48 | [[ $src = *.patch ]] || continue 49 | echo "Applying patch $src..." 50 | patch -Np1 < "../$src" 51 | done 52 | 53 | echo "Setting config..." 54 | cp ../config .config 55 | make olddefconfig 56 | diff -u ../config .config || : 57 | 58 | make -s kernelrelease > version 59 | echo "Prepared $pkgbase version $(/dev/null; then 4 | curl --fail --no-progress-meter https://raw.githubusercontent.com/nathants/bootstraps/master/set_opt.sh | /usr/bin/sudo tee /usr/bin/set-opt >/dev/null 5 | /usr/bin/sudo chmod +x /usr/bin/set-opt 6 | fi 7 | 8 | grep CONFIG_SECURITY_NETWORK=y config 9 | grep CONFIG_NETFILTER_NETLINK_QUEUE=m config 10 | grep CONFIG_NFT_QUEUE=m config 11 | 12 | sed -i -r 's/^CONFIG_LSM="([^"]+)"/CONFIG_SNITCH=y\nCONFIG_LSM="snitch,\1"/' config 13 | sed -i -r 's/^(CONFIG_IO_URING)=.$/# \1 is not set/' config 14 | sed -i -r 's/^(CONFIG_.*IPV6.*)=.$/# \1 is not set/' config 15 | -------------------------------------------------------------------------------- /kernel/arch/readme.md: -------------------------------------------------------------------------------- 1 | upstream source: https://gitlab.archlinux.org/archlinux/packaging/packages/linux 2 | 3 | when updating kernel configs, take upstream, and then run: 4 | 5 | ``` 6 | bash config.sh 7 | ``` 8 | -------------------------------------------------------------------------------- /kernel/debian/todo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nathants/mighty-snitch/5cf7d3cf010d58d3c4334b7f0dbdb5cd50f9f4ab/kernel/debian/todo -------------------------------------------------------------------------------- /license.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | 3 | Version 3, 29 June 2007 4 | 5 | Copyright (C) 2007 Free Software Foundation, Inc. 6 | 7 | Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for software and other kinds of works. 11 | 12 | The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. 13 | 14 | When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. 15 | 16 | To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. 17 | 18 | For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. 19 | 20 | Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. 21 | 22 | For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. 23 | 24 | Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. 25 | 26 | Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. 27 | 28 | The precise terms and conditions for copying, distribution and modification follow. 29 | TERMS AND CONDITIONS 30 | 0. Definitions. 31 | 32 | ?This License? refers to version 3 of the GNU General Public License. 33 | 34 | ?Copyright? also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. 35 | 36 | ?The Program? refers to any copyrightable work licensed under this License. Each licensee is addressed as ?you?. ?Licensees? and ?recipients? may be individuals or organizations. 37 | 38 | To ?modify? a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a ?modified version? of the earlier work or a work ?based on? the earlier work. 39 | 40 | A ?covered work? means either the unmodified Program or a work based on the Program. 41 | 42 | To ?propagate? a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. 43 | 44 | To ?convey? a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. 45 | 46 | An interactive user interface displays ?Appropriate Legal Notices? to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 47 | 1. Source Code. 48 | 49 | The ?source code? for a work means the preferred form of the work for making modifications to it. ?Object code? means any non-source form of a work. 50 | 51 | A ?Standard Interface? means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. 52 | 53 | The ?System Libraries? of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A ?Major Component?, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. 54 | 55 | The ?Corresponding Source? for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. 56 | 57 | The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. 58 | 59 | The Corresponding Source for a work in source code form is that same work. 60 | 2. Basic Permissions. 61 | 62 | All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. 63 | 64 | You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. 65 | 66 | Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 67 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 68 | 69 | No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. 70 | 71 | When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 72 | 4. Conveying Verbatim Copies. 73 | 74 | You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. 75 | 76 | You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 77 | 5. Conveying Modified Source Versions. 78 | 79 | You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: 80 | 81 | * a) The work must carry prominent notices stating that you modified it, and giving a relevant date. 82 | * b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to ?keep intact all notices?. 83 | * c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. 84 | * d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. 85 | 86 | A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an ?aggregate? if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 87 | 6. Conveying Non-Source Forms. 88 | 89 | You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: 90 | 91 | * a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. 92 | * b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. 93 | * c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. 94 | * d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. 95 | * e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. 96 | 97 | A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. 98 | 99 | A ?User Product? is either (1) a ?consumer product?, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, ?normally used? refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. 100 | 101 | ?Installation Information? for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. 102 | 103 | If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). 104 | 105 | The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. 106 | 107 | Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 108 | 7. Additional Terms. 109 | 110 | ?Additional permissions? are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. 111 | 112 | When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. 113 | 114 | Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: 115 | 116 | * a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or 117 | * b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or 118 | * c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or 119 | * d) Limiting the use for publicity purposes of names of licensors or authors of the material; or 120 | * e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or 121 | * f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. 122 | 123 | All other non-permissive additional terms are considered ?further restrictions? within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. 124 | 125 | If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. 126 | 127 | Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 128 | 8. Termination. 129 | 130 | You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). 131 | 132 | However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. 133 | 134 | Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. 135 | 136 | Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 137 | 9. Acceptance Not Required for Having Copies. 138 | 139 | You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 140 | 10. Automatic Licensing of Downstream Recipients. 141 | 142 | Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. 143 | 144 | An ?entity transaction? is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. 145 | 146 | You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 147 | 11. Patents. 148 | 149 | A ?contributor? is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's ?contributor version?. 150 | 151 | A contributor's ?essential patent claims? are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, ?control? includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. 152 | 153 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. 154 | 155 | In the following three paragraphs, a ?patent license? is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To ?grant? such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. 156 | 157 | If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. ?Knowingly relying? means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. 158 | 159 | If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. 160 | 161 | A patent license is ?discriminatory? if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. 162 | 163 | Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 164 | 12. No Surrender of Others' Freedom. 165 | 166 | If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 167 | 13. Use with the GNU Affero General Public License. 168 | 169 | Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 170 | 14. Revised Versions of this License. 171 | 172 | The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 173 | 174 | Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License ?or any later version? applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. 175 | 176 | If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. 177 | 178 | Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 179 | 15. Disclaimer of Warranty. 180 | 181 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM ?AS IS? WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 182 | 16. Limitation of Liability. 183 | 184 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 185 | 17. Interpretation of Sections 15 and 16. 186 | 187 | If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. 188 | 189 | END OF TERMS AND CONDITIONS 190 | How to Apply These Terms to Your New Programs 191 | 192 | If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. 193 | 194 | To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the ?copyright? line and a pointer to where the full notice is found. 195 | 196 | 197 | Copyright (C) 198 | 199 | This program is free software: you can redistribute it and/or modify 200 | it under the terms of the GNU General Public License as published by 201 | the Free Software Foundation, either version 3 of the License, or 202 | (at your option) any later version. 203 | 204 | This program is distributed in the hope that it will be useful, 205 | but WITHOUT ANY WARRANTY; without even the implied warranty of 206 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 207 | GNU General Public License for more details. 208 | 209 | You should have received a copy of the GNU General Public License 210 | along with this program. If not, see . 211 | 212 | Also add information on how to contact you by electronic and paper mail. 213 | 214 | If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: 215 | 216 | Copyright (C) 217 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 218 | This is free software, and you are welcome to redistribute it 219 | under certain conditions; type `show c' for details. 220 | 221 | The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an ?about box?. 222 | 223 | You should also get your employer (if you work as a programmer) or school, if any, to sign a ?copyright disclaimer? for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . 224 | 225 | The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . 226 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # mighty-snitch 2 | 3 | ## why 4 | 5 | noticing and preventing network requests should be easy. 6 | 7 | ## how 8 | 9 | interactively filter network requests with rules and visual prompts. 10 | 11 | ## what 12 | 13 | a [linux security module](https://www.kernel.org/doc/html/latest/security/lsm.html) communicates via [netlink](https://man7.org/linux/man-pages/man7/netlink.7.html) with the userspace [snitch](https://github.com/nathants/mighty-snitch/blob/master/snitch/snitch.c) on each [sendmsg](https://man7.org/linux/man-pages/man3/sendmsg.3p.html)/[recvmsg](https://man7.org/linux/man-pages/man3/recvmsg.3p.html). 14 | 15 | snitch decides whether to allow or deny the network request. 16 | 17 | rules are checked. if no rule exists, a visual prompt is displayed to the user. 18 | 19 | finally snitch responds to the kernel and the request is allowed or denied. 20 | 21 | ## demo 22 | 23 | ![](https://github.com/nathants/mighty-snitch/raw/master/demo.gif) 24 | 25 | ## hardware 26 | 27 | the primary test environments is [arch](https://archlinux.org/) 28 | 29 | the primary test devices are [thinkpad x1](https://www.lenovo.com/us/en/c/laptops/thinkpad/thinkpadx1) and [rog x670e-i](https://rog.asus.com/motherboards/rog-strix/rog-strix-x670e-i-gaming-wifi-model/) 30 | 31 | ## prior art 32 | 33 | [little-snitch](https://www.obdev.at/products/littlesnitch/index.html) which introduced me to this concept. 34 | 35 | [open-snitch](https://github.com/evilsocket/opensnitch) which introduced me to [nfq](https://www.netfilter.org/projects/libnetfilter_queue/). 36 | 37 | [tiny-snitch](https://github.com/nathants/tiny-snitch) which helped me understand what is possible with [nfq](https://www.netfilter.org/projects/libnetfilter_queue/) and [bpftrace](https://github.com/iovisor/bpftrace). 38 | 39 | [uslm](https://github.com/argussecurity/ulsm) which helped me understand what is possible with [lsm](https://www.kernel.org/doc/html/latest/security/lsm.html). 40 | 41 | ## design 42 | 43 | mighty-snitch uses [lsm](https://www.kernel.org/doc/html/latest/security/lsm.html) instead of [nfq](https://www.netfilter.org/projects/libnetfilter_queue/) to filter network requests. 44 | 45 | the primary advantage is that it has direct access to the pid, executable, and commandline of the process making the request. 46 | 47 | the primary disadvantage is that it requires a custom kernel. 48 | 49 | the visual prompt is a terminal [application](https://github.com/nathants/mighty-snitch/blob/master/snitch-prompt/snitch-prompt) which responds to keyboard input. a new terminal is launched for each prompt and exits after y/n are pressed. [st](https://st.suckless.org/) is used on x86_64, though any terminal should work. 50 | 51 | the system fails closed. when snitch isn't running, network requests are not possible. 52 | 53 | dns packets received on udp 53 are read via [nfq](https://www.netfilter.org/projects/libnetfilter_queue/) so that rules can specify domains in addition to ipv4 addresses. 54 | 55 | ## constraints 56 | 57 | the following are simplifying constraints. other configurations should be possible. 58 | 59 | - ipv6 is disabled. 60 | 61 | - io_uring is disabled. 62 | 63 | - nftables rules are replaced when snitch starts. 64 | 65 | - iptables rules should be empty. 66 | 67 | - all other lsm are disabled. 68 | 69 | - kernel commandline parameters for lsm are ignored. 70 | 71 | ## rules 72 | 73 | snitch creates a rules file: `~/.snitch.rules` 74 | 75 | when this file is edited, snitch reloads the rules. 76 | 77 | typically rules are created by choosing the `forever` duration in the visual prompt, but can also be directly added to the rules file. 78 | 79 | address can be a wildcard up to three subdomains. 80 | 81 | commandline can be a wildcard. 82 | 83 | here are the rules for firefox to deny all the unprompted connections it makes: 84 | 85 | ``` 86 | send deny /usr/lib/firefox/firefox content-signature-2.cdn.mozilla.net 443 tcp /usr/lib/firefox/firefox 87 | send deny /usr/lib/firefox/firefox content-signature-2.cdn.mozilla.net 80 tcp /usr/lib/firefox/firefox 88 | send deny /usr/lib/firefox/firefox contile.services.mozilla.com 443 tcp /usr/lib/firefox/firefox 89 | send deny /usr/lib/firefox/firefox firefox.settings.services.mozilla.com 443 tcp /usr/lib/firefox/firefox 90 | send deny /usr/lib/firefox/firefox firefox.settings.services.mozilla.com 443 udp /usr/lib/firefox/firefox 91 | send deny /usr/lib/firefox/firefox getpocket.cdn.mozilla.net 443 tcp /usr/lib/firefox/firefox 92 | send deny /usr/lib/firefox/firefox location.services.mozilla.com 443 tcp /usr/lib/firefox/firefox 93 | send deny /usr/lib/firefox/firefox mozilla.cloudflare-dns.com 443 tcp /usr/lib/firefox/firefox 94 | send deny /usr/lib/firefox/firefox normandy.cdn.mozilla.net 443 tcp /usr/lib/firefox/firefox 95 | send deny /usr/lib/firefox/firefox push.services.mozilla.com 443 tcp /usr/lib/firefox/firefox 96 | send deny /usr/lib/firefox/firefox shavar.services.mozilla.com 443 tcp /usr/lib/firefox/firefox 97 | ``` 98 | 99 | ## build arch and install 100 | 101 | ```bash 102 | cd ~ 103 | git clone https://github.com/nathants/mighty-snitch 104 | 105 | cd ~/mighty-snitch/kernel/arch 106 | makepkg -sCf 107 | sudo pacman -U *.zst 108 | 109 | cd ~/mighty-snitch/snitch-prompt 110 | sudo pip install . 111 | 112 | cd ~/mighty-snitch/snitch 113 | bash snitch.sh 114 | ``` 115 | -------------------------------------------------------------------------------- /snitch-prompt/color: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | colorize parts of lines to arbitrary colors 4 | 5 | usage: echo a b c | color 0:green 1:red 2:blue 6 | 7 | usage: echo a b c | color a:green c:red 8 | 9 | usage: echo /a/b/c | sep=/ color a:green c:red 10 | 11 | usage: echo /a123/b/c | sep=/ sub=y color a:green c:red 12 | 13 | usage: echo /a123/b/c | sep=/ sub=y ljust=10 color a:green c:red 14 | """ 15 | import functools 16 | import sys 17 | import os 18 | import sys 19 | 20 | # make colors 21 | _colors = ['red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'] 22 | _pairs = zip(_colors, range(31, 38)) 23 | def _make_color(code, text): 24 | return "\033[{}m{}\033[0m".format(code, text) 25 | for _color, _num in _pairs: 26 | globals()[_color] = functools.partial(_make_color, _num) 27 | 28 | # print help 29 | if '-h' in sys.argv or '--help' in sys.argv: 30 | print('colors:', ' | '.join(_colors)) 31 | print(__doc__) 32 | sys.exit(1) 33 | 34 | # create map of token => color function 35 | colors = {token: globals()[color] 36 | for arg in sys.argv[1:] 37 | for token, color in [arg.split(':')]} 38 | 39 | # default ljust is 0 40 | ljust = int(os.environ.get('ljust', '0')) 41 | 42 | # default sep is whitespace 43 | sep = os.environ.get('sep') 44 | 45 | # default to exact match, use SUB=y for substring match 46 | sub = 'sub' in os.environ 47 | 48 | for line in sys.stdin: 49 | # if line contains any token 50 | if any(token in line for token in colors) or any(token.isdigit() for token in colors): 51 | # for each part of the line 52 | parts = [] 53 | for i, part in enumerate(line.rstrip().split(sep)): 54 | # colorize part by first matching substring 55 | if sub: 56 | for t in colors: 57 | if t in part: 58 | part = colors[t](part) 59 | if ljust: 60 | part = part.ljust(ljust + 9) 61 | break 62 | # colorize part by exact match 63 | else: 64 | if part in colors: 65 | part = colors[part](part) 66 | if ljust: 67 | part = part.ljust(ljust + 9) 68 | elif str(i) in colors: 69 | part = colors[str(i)](part) 70 | if ljust: 71 | part = part.ljust(ljust + 9) 72 | 73 | parts.append(part) 74 | sys.stdout.write((sep or ' ').join(parts) + '\n') 75 | else: 76 | sys.stdout.write(line) 77 | sys.stdout.flush() 78 | -------------------------------------------------------------------------------- /snitch-prompt/count-last: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import blessed 3 | import sys 4 | term = blessed.Terminal() 5 | last = None 6 | count = 1 7 | for line in sys.stdin: 8 | line = line.rstrip() 9 | if line == last: 10 | count += 1 11 | print(term.move_up(2) + term.move_x(0)) 12 | else: 13 | last = line 14 | count = 1 15 | if count > 1: 16 | print(line, f'[{count}]', flush=True) 17 | else: 18 | print(line, flush=True) 19 | -------------------------------------------------------------------------------- /snitch-prompt/setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | setuptools.setup( 4 | version="0.0.1", 5 | name="snitch-prompt", 6 | install_requires=[ 7 | 'blessed', 8 | ], 9 | scripts=[ 10 | 'snitch-prompt', 11 | 'color', 12 | 'count-last', 13 | ], 14 | description='snitch-prompt', 15 | ) 16 | -------------------------------------------------------------------------------- /snitch-prompt/snitch-prompt: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # type: ignore 3 | import os 4 | import time 5 | import blessed 6 | import sys 7 | import termios 8 | import tty 9 | import contextlib 10 | import threading 11 | import queue 12 | import re 13 | import tempfile 14 | 15 | _rm_color = re.compile(r'\x1b[^m]*m') 16 | 17 | def rm_color(text): 18 | return _rm_color.sub('', text) 19 | 20 | def _make_color(code, text): 21 | return "\033[{}m{}\033[0m".format(code, text) 22 | 23 | black = lambda text: _make_color(30, text) 24 | red = lambda text: _make_color(31, text) 25 | green = lambda text: _make_color(32, text) 26 | yellow = lambda text: _make_color(33, text) 27 | blue = lambda text: _make_color(34, text) 28 | magenta = lambda text: _make_color(35, text) 29 | cyan = lambda text: _make_color(36, text) 30 | white = lambda text: _make_color(37, text) 31 | clear = lambda text: _make_color(38, text) 32 | 33 | def getch(q): 34 | while True: 35 | val = sys.stdin.read(1).lower() 36 | if val == '\x03': 37 | sys.exit(1) 38 | else: 39 | q.put(val) 40 | 41 | @contextlib.contextmanager 42 | def raw(): 43 | fd = sys.stdin.fileno() 44 | old = termios.tcgetattr(fd) 45 | try: 46 | tty.setraw(fd) 47 | yield 48 | except KeyboardInterrupt: 49 | sys.exit(1) 50 | finally: 51 | termios.tcsetattr(fd, termios.TCSADRAIN, old) 52 | 53 | delay = .35 54 | 55 | def paths(path): 56 | res = [path] 57 | parts = path.split('/') 58 | for i in range(len(parts)): 59 | val = '/'.join(parts[:-i]) 60 | if val: 61 | res.append(val + '/') 62 | return res 63 | 64 | def addrs(addr): 65 | vals = [] 66 | parts = addr.split('.') 67 | for i in range(1, len(parts)): 68 | if i > 4: 69 | break 70 | if i > 1: 71 | vals.append('*.' + '.'.join(parts[-i:])) 72 | vals.append('*') 73 | vals.append(addr) 74 | return vals 75 | 76 | def main(): 77 | msg, outfile = sys.argv[1:] 78 | interval = float(os.environ.get('SNITCH_PROMPT_INTERVAL', '0.01')) 79 | with raw(): 80 | q = queue.Queue() 81 | t = threading.Thread(target=getch, args=[q]) 82 | t.daemon = True 83 | t.start() 84 | 85 | t = blessed.Terminal() 86 | 87 | with t.fullscreen(), t.hidden_cursor(): 88 | 89 | start = time.monotonic() 90 | duration = '1-minute' 91 | 92 | txt = msg 93 | txt = txt.replace('\\n', '\n') 94 | kind, rest = txt.split('\n', 1) 95 | if kind == 'send': 96 | exe, target, cmdline = rest.strip().splitlines() 97 | cmdline_orig = cmdline 98 | addr, port, proto = target.split('\t') 99 | addr_orig = addr 100 | if port.strip().isdigit() and int(port) > 32_000: 101 | port = 'ephemeral' 102 | elif kind == 'recv': 103 | exe, target, cmdline = rest.strip().splitlines() 104 | cmdline_orig = cmdline 105 | port, proto = target.split('\t') 106 | port = port 107 | if port.strip().isdigit() and int(port) > 32_000: 108 | port = 'ephemeral' 109 | elif kind in ['read', 'write', 'exec', 'unknown']: 110 | exe, path, cmdline = rest.strip().splitlines() 111 | path_orig = path 112 | cmdline_orig = cmdline 113 | else: 114 | assert False, f'unknown kind: {kind}' 115 | 116 | while True: 117 | 118 | if kind == 'send': 119 | if proto in ['tcp', 'udp']: 120 | txt = f'{white("send")}\n{white("d")}uration={cyan(duration)}\nexe={red(exe)}\n{white("a")}ddr={green(addr)}\nport={blue(port)}\nproto={yellow(proto)}\n{white("c")}mdline={magenta(cmdline)}' 121 | elif proto == 'unix': 122 | txt = f'{white("send")}\n{white("d")}uration={cyan(duration)}\nexe={red(exe)}\nport={blue(port)}\nproto={yellow(proto)}\n{white("c")}mdline={magenta(cmdline)}' 123 | else: 124 | txt = f'{white("send")}\n{white("d")}uration={cyan(duration)}\nexe={red(exe)}\nproto={yellow(proto)}\n{white("c")}mdline={magenta(cmdline)}' 125 | elif kind == 'recv': 126 | if proto in ['tcp', 'udp', 'unix']: 127 | txt = f'{white("recv")}\n{white("d")}uration={cyan(duration)}\nexe={red(exe)}\nport={blue(port)}\nproto={yellow(proto)}\n{white("c")}mdline={magenta(cmdline)}' 128 | else: 129 | txt = f'{white("recv")}\n{white("d")}uration={cyan(duration)}\nexe={red(exe)}\nproto={yellow(proto)}\n{white("c")}mdline={magenta(cmdline)}' 130 | elif kind in ['read', 'write', 'exec', 'unknown']: 131 | txt = f'{white(kind)}\n{white("d")}uration={cyan(duration)}\nexe={red(exe)}\n{white("p")}ath={blue(path)}\n{white("c")}mdline={magenta(cmdline)}' 132 | else: 133 | assert False, f'unknown kind: {kind}' 134 | 135 | txt += f'\n{white("y")} / {white("n")} ?' 136 | txt = txt.replace('\t', ' ') 137 | txt = txt.replace('\n', '\n\n') 138 | 139 | print(t.move_xy(0, 0), file=sys.stderr) 140 | print(t.clear, file=sys.stderr) 141 | y = (t.height - len(txt.splitlines())) // 2 142 | for i, line in enumerate(txt.splitlines()): 143 | print(t.move_xy(t.width // 2 - len(rm_color(line)) // 2, y) + line, file=sys.stderr) 144 | y += 1 145 | elapsed = time.monotonic() - start 146 | 147 | y += 1 148 | remaining = int(30 - elapsed) 149 | timeout_txt = f'{remaining}s' 150 | print(t.move_xy(t.width // 2 - len(timeout_txt) // 2, y) + timeout_txt) 151 | 152 | if delay != 0 and elapsed < delay: 153 | progress = 1 - (min(elapsed, delay) / delay) 154 | ptxt = '=' * int(progress * 40) 155 | y += 1 156 | print(t.move_xy(t.width // 2 - len(rm_color(ptxt)) // 2, y) + ptxt, file=sys.stderr) 157 | time.sleep(interval) 158 | while True: 159 | try: 160 | q.get_nowait() # drain input queue while delayed 161 | except queue.Empty: 162 | break 163 | 164 | else: 165 | try: 166 | if remaining <= 0: 167 | char = 'n' 168 | else: 169 | char = q.get_nowait() 170 | except queue.Empty: 171 | time.sleep(interval) 172 | else: 173 | if char in ['y', 'n']: 174 | temp = tempfile.mktemp() 175 | if char == 'y': 176 | response = 'allow' 177 | elif char == 'n': 178 | response = 'deny' 179 | if kind == 'send': 180 | with open(temp, 'w') as f: 181 | f.write(f'send\x00{response}\x00{duration}\x00{exe}\x00{addr}\x00{port}\x00{proto}\x00{cmdline}') 182 | elif kind == 'recv': 183 | with open(temp, 'w') as f: 184 | f.write(f'recv\x00{response}\x00{duration}\x00{exe}\x00{port}\x00{proto}\x00{cmdline}') 185 | elif kind in ['read', 'write', 'exec', 'unknown']: 186 | with open(temp, 'w') as f: 187 | f.write(f'{kind}\x00{response}\x00{duration}\x00{exe}\x00{path}\x00{cmdline}') 188 | else: 189 | assert False, f'unknown kind {kind}' 190 | os.rename(temp, outfile) 191 | sys.exit(0) 192 | elif char == 'd': 193 | if duration == '1-minute': 194 | duration = '24-hour' 195 | elif duration == '24-hour': 196 | duration = 'forever' 197 | elif duration == 'forever': 198 | duration = '1-minute' 199 | elif char == 'a': 200 | if kind == 'send': 201 | vals = addrs(addr_orig) 202 | i = vals.index(addr.strip()) 203 | i += 1 204 | i %= len(vals) 205 | addr = vals[i] 206 | elif char == 'c': 207 | if cmdline.strip() == cmdline_orig: 208 | cmdline = '*' 209 | else: 210 | cmdline = cmdline_orig 211 | elif char == 'p' and kind in ['read', 'write', 'exec', 'unknown']: 212 | vals = paths(path_orig) 213 | i = vals.index(path.strip()) 214 | i += 1 215 | i %= len(vals) 216 | path = vals[i] 217 | 218 | if __name__ == '__main__': 219 | try: 220 | main() 221 | except SystemExit: 222 | raise 223 | except: 224 | import traceback 225 | import time 226 | print(traceback.format_exc(), file=sys.stderr) 227 | print(sys.argv) 228 | input() 229 | -------------------------------------------------------------------------------- /snitch/build.sh: -------------------------------------------------------------------------------- 1 | gcc \ 2 | -Ivendor/ \ 3 | -Iutil/ \ 4 | -O3 \ 5 | -Wall \ 6 | -flto \ 7 | -o snitch \ 8 | snitch.c \ 9 | $(pkg-config libnetfilter_queue --cflags --libs) 10 | -------------------------------------------------------------------------------- /snitch/snitch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include "util.h" 13 | #include "nl.h" 14 | #include "nft.h" 15 | #include "queue.h" 16 | #include "map.h" 17 | #include "array.h" 18 | 19 | #define EPHEMERAL_PORT_START 1<<15 20 | 21 | int foot_terminal = 0; 22 | char home[1024] = {0}; 23 | char rules_file[1024] = {0}; 24 | 25 | typedef struct result_s { 26 | i32 id; 27 | i32 response; 28 | } result_t; 29 | 30 | typedef struct event_s { 31 | i32 id; 32 | i32 pid; 33 | char type; 34 | char namebuf[24]; 35 | char exe[240]; 36 | char cmdline[240]; 37 | char databuf[240]; 38 | char net_remote_domain[240]; 39 | } event_t; 40 | 41 | pthread_mutex_t dns_lock; 42 | MAP_INIT(dns, char*, 1<<16); 43 | 44 | typedef struct rule_s { 45 | 46 | // shared fields 47 | char kind[8]; // send | recv 48 | char response[6]; // allow | deny 49 | char duration[16]; // 1-minute | 24-hour | forever 50 | char exe[240]; 51 | char cmdline[240]; 52 | 53 | // fields for: send | recv 54 | char port[240]; // %d | ephemeral 55 | char proto[16]; // udp | tcp | raw | socktype=%d 56 | 57 | // fields for: send 58 | char addr[240]; 59 | 60 | // internal fields 61 | u8 meta; // mark existing rules for deletion check 62 | u32 creation; // epoch seconds 63 | 64 | } rule_t; 65 | 66 | pthread_mutex_t rules_file_lock; 67 | 68 | pthread_mutex_t rules_lock; 69 | i64 rules_file_mtime = 0; 70 | i32 rules_file_needs_write = 0; 71 | MAP_INIT(rules, rule_t*, 1<<16); 72 | 73 | i32 rule_equal(rule_t *a, rule_t *b) { 74 | return \ 75 | strncmp(a->kind, b->kind, sizeof(a->kind)) == 0 && 76 | strncmp(a->response, b->response, sizeof(a->response)) == 0 && 77 | strncmp(a->exe, b->exe, sizeof(a->exe)) == 0 && 78 | strncmp(a->cmdline, b->cmdline, sizeof(a->cmdline)) == 0 && 79 | strncmp(a->port, b->port, sizeof(a->port)) == 0 && 80 | strncmp(a->proto, b->proto, sizeof(a->proto)) == 0 && 81 | strncmp(a->addr, b->addr, sizeof(a->addr)) == 0; 82 | } 83 | 84 | rule_t *rule_parse(char *buf, i32 size) { 85 | i32 offset; 86 | rule_t *r; 87 | MALLOC(r, sizeof(*r)); 88 | memset(r, 0, sizeof(*r)); 89 | strcpy(r->duration, "forever"); 90 | if (size < 6) { 91 | LOG("rule parse buf too small: %d\n", size); 92 | free(r); 93 | return NULL; 94 | } 95 | if (strncmp(buf, "send\t", 5) == 0) { 96 | // parse kind 97 | strcpy(r->kind, "send"); 98 | buf += 5; size -= 5; 99 | // parse response 100 | if (size < 6) { 101 | LOG("rule parse buf too small\n"); 102 | free(r); 103 | return NULL; 104 | } 105 | if (strncmp(buf, "allow\t", 6) == 0) { 106 | strcpy(r->response, "allow"); 107 | buf += 6; size -= 6; 108 | } else if (strncmp(buf, "deny\t", 5) == 0) { 109 | strcpy(r->response, "deny"); 110 | buf += 5; size -= 5; 111 | } else { 112 | LOG("rule parse bad response: %.*s\n", size, buf); 113 | free(r); 114 | return NULL; 115 | } 116 | // parse exe 117 | offset = 0; 118 | for (i32 i = 0; i < size; i++) { 119 | offset = i; 120 | if (buf[i] == '\t') 121 | break; 122 | } 123 | if (offset >= size) { 124 | LOG("rule parse overflow\n"); 125 | free(r); 126 | return NULL; 127 | } 128 | strncpy(r->exe, buf, offset); 129 | offset += 1; buf += offset; size -= offset; 130 | // parse addr 131 | offset = 0; 132 | for (i32 i = 0; i < size; i++) { 133 | offset = i; 134 | if (buf[i] == '\t') 135 | break; 136 | } 137 | if (offset >= size) { 138 | LOG("rule parse overflow\n"); 139 | free(r); 140 | return NULL; 141 | } 142 | strncpy(r->addr, buf, offset); 143 | offset += 1; buf += offset; size -= offset; 144 | // parse port 145 | offset = 0; 146 | for (i32 i = 0; i < size; i++) { 147 | offset = i; 148 | if (buf[i] == '\t') 149 | break; 150 | } 151 | if (offset >= size) { 152 | LOG("rule parse overflow\n"); 153 | free(r); 154 | return NULL; 155 | } 156 | strncpy(r->port, buf, offset); 157 | offset += 1; buf += offset; size -= offset; 158 | // parse proto 159 | offset = 0; 160 | for (i32 i = 0; i < size; i++) { 161 | offset = i; 162 | if (buf[i] == '\t') 163 | break; 164 | } 165 | if (offset >= size) { 166 | LOG("rule parse overflow\n"); 167 | free(r); 168 | return NULL; 169 | } 170 | strncpy(r->proto, buf, offset); 171 | offset += 1; buf += offset; size -= offset; 172 | // parse cmdline 173 | strncpy(r->cmdline, buf, size); 174 | } else if (strncmp(buf, "recv\t", 5) == 0) { 175 | // parse kind 176 | strcpy(r->kind, "recv"); 177 | buf += 5; size -= 5; 178 | // parse response 179 | if (size < 6) { 180 | LOG("rule parse buf too small\n"); 181 | free(r); 182 | return NULL; 183 | } 184 | if (strncmp(buf, "allow\t", 6) == 0) { 185 | strcpy(r->response, "allow"); 186 | buf += 6; size -= 6; 187 | } else if (strncmp(buf, "deny\t", 5) == 0) { 188 | strcpy(r->response, "deny"); 189 | buf += 5; size -= 5; 190 | } else { 191 | LOG("rule parse bad response: %.*s\n", size, buf); 192 | free(r); 193 | return NULL; 194 | } 195 | // parse exe 196 | offset = 0; 197 | for (i32 i = 0;; i++) { 198 | offset = i; 199 | if (buf[i] == '\t') 200 | break; 201 | } 202 | if (offset >= size) { 203 | LOG("rule parse overflow\n"); 204 | free(r); 205 | return NULL; 206 | } 207 | strncpy(r->exe, buf, offset); 208 | offset += 1; buf += offset; size -= offset; 209 | // parse port 210 | offset = 0; 211 | for (i32 i = 0; i < size; i++) { 212 | offset = i; 213 | if (buf[i] == '\t') 214 | break; 215 | } 216 | if (offset >= size) { 217 | LOG("rule parse overflow\n"); 218 | free(r); 219 | return NULL; 220 | } 221 | strncpy(r->port, buf, offset); 222 | offset += 1; buf += offset; size -= offset; 223 | // parse proto 224 | offset = 0; 225 | for (i32 i = 0; i < size; i++) { 226 | offset = i; 227 | if (buf[i] == '\t') 228 | break; 229 | } 230 | if (offset >= size) { 231 | LOG("rule parse overflow\n"); 232 | free(r); 233 | return NULL; 234 | } 235 | strncpy(r->proto, buf, offset); 236 | offset += 1; buf += offset; size -= offset; 237 | // parse cmdline 238 | strncpy(r->cmdline, buf, size); 239 | } else { 240 | LOG("rule parse unknown kind [%s]\n", r->kind); 241 | free(r); 242 | return NULL; 243 | } 244 | return r; 245 | } 246 | 247 | i32 rule_format(rule_t *r, char *buf, i32 size) { 248 | if (strcmp(r->kind, "send") == 0) { 249 | return snprintf(buf, size - 1, "%s\t%s\t%s\t%s\t%s\t%s\t%s", r->kind, r->response, r->exe, r->addr, r->port, r->proto, r->cmdline); 250 | } else if (strcmp(r->kind, "recv") == 0) { 251 | return snprintf(buf, size - 1, "%s\t%s\t%s\t%s\t%s\t%s", r->kind, r->response, r->exe, r->port, r->proto, r->cmdline); 252 | } else { 253 | ASSERT(0, "rule format unknown kind [%s]\n", r->kind); 254 | } 255 | } 256 | 257 | i32 rule_key(rule_t *r, char *buf, i32 size) { 258 | if (strcmp(r->kind, "send") == 0) { 259 | return snprintf(buf, size - 1, "send\t%s\t%s\t%s\t%s\t%s", r->exe, r->addr, r->port, r->proto, r->cmdline); 260 | } else if (strcmp(r->kind, "recv") == 0) { 261 | return snprintf(buf, size - 1, "recv\t%s\t%s\t%s\t%s", r->exe, r->port, r->proto, r->cmdline); 262 | } else { 263 | ASSERT(0, "unknown kind [%s]\n", r->kind); 264 | } 265 | } 266 | 267 | static int sortcmp(const void *p1, const void *p2) { 268 | return strcmp(*(const char**)p1, *(const char**)p2); 269 | } 270 | 271 | i32 add_rule(char *buf, i32 size) { 272 | rule_t *r; 273 | MALLOC(r, sizeof(*r)); 274 | memset(r, 0, sizeof(*r)); 275 | r->creation = unix_seconds(); 276 | char keybuf[sizeof(*r)] = {0}; 277 | i32 keysize; 278 | if (strcmp(buf, "send") == 0) { 279 | strncpy(r->kind, buf, sizeof(r->kind) - 1); buf += strlen(buf) + 1; 280 | strncpy(r->response, buf, sizeof(r->response) - 1); buf += strlen(buf) + 1; 281 | strncpy(r->duration, buf, sizeof(r->duration) - 1); buf += strlen(buf) + 1; 282 | strncpy(r->exe, buf, sizeof(r->exe) - 1); buf += strlen(buf) + 1; 283 | strncpy(r->addr, buf, sizeof(r->addr) - 1); buf += strlen(buf) + 1; 284 | strncpy(r->port, buf, sizeof(r->port) - 1); buf += strlen(buf) + 1; 285 | strncpy(r->proto, buf, sizeof(r->proto) - 1); buf += strlen(buf) + 1; 286 | strncpy(r->cmdline, buf, sizeof(r->cmdline) - 1); buf += strlen(buf) + 1; 287 | keysize = rule_key(r, keybuf, sizeof(keybuf)); 288 | } 289 | else if (strcmp(buf, "recv") == 0) { 290 | strncpy(r->kind, buf, sizeof(r->kind) - 1); buf += strlen(buf) + 1; 291 | strncpy(r->response, buf, sizeof(r->response) - 1); buf += strlen(buf) + 1; 292 | strncpy(r->duration, buf, sizeof(r->duration) - 1); buf += strlen(buf) + 1; 293 | strncpy(r->exe, buf, sizeof(r->exe) - 1); buf += strlen(buf) + 1; 294 | strncpy(r->port, buf, sizeof(r->port) - 1); buf += strlen(buf) + 1; 295 | strncpy(r->proto, buf, sizeof(r->proto) - 1); buf += strlen(buf) + 1; 296 | strncpy(r->cmdline, buf, sizeof(r->cmdline) - 1); buf += strlen(buf) + 1; 297 | keysize = rule_key(r, keybuf, sizeof(keybuf)); 298 | } 299 | else { 300 | LOG("error: unknown add-rule format: %s\n", buf); 301 | return DENY; 302 | } 303 | i32 response; 304 | if (strncmp(r->response, "allow", sizeof(r->response)) == 0) { 305 | response = ALLOW; 306 | } else if (strncmp(r->response, "deny", sizeof(r->response)) == 0) { 307 | response = DENY; 308 | } else { 309 | LOG("error: unknown response [%s]\n", r->response); 310 | return DENY; 311 | } 312 | 313 | if (strncmp(r->duration, "24-hour", sizeof(r->duration)) != 0 && 314 | strncmp(r->duration, "forever", sizeof(r->duration)) != 0 && 315 | strncmp(r->duration, "1-minute", sizeof(r->duration)) != 0) 316 | { 317 | LOG("error: unknown duration [%s]\n", r->duration); 318 | return DENY; 319 | } 320 | 321 | pthread_mutex_lock(&rules_lock); { 322 | MAP_FIND_INDEX(rules, keybuf, keysize); 323 | if (!MAP_KEY(rules)) { 324 | char *key; 325 | MALLOC(key, keysize + 1); 326 | memset(key, 0, keysize + 1); 327 | strncpy(key, keybuf, keysize); 328 | MAP_SET_INDEX(rules, (u8*)key, keysize, rule_t*); 329 | } 330 | if (MAP_VALUE(rules)) { 331 | free(MAP_VALUE(rules)); 332 | } 333 | MAP_VALUE(rules) = r; 334 | if (strncmp(r->duration, "forever", sizeof(r->duration)) == 0) { 335 | rules_file_needs_write = 1; 336 | } 337 | }; pthread_mutex_unlock(&rules_lock); 338 | LOG("add-rule %s %s %s\n", r->response, r->duration, keybuf); 339 | 340 | return response; 341 | } 342 | 343 | char *sub_addr(char *addr, int size, int n) { 344 | int stop = 0; 345 | for (int i = 0; i < size; i++) { 346 | if (addr[i] == 0) 347 | break; 348 | stop++; 349 | } 350 | int count = -2; 351 | for (int i = stop - 1; i >= 0; i--) { 352 | if (addr[i] == '.') 353 | count ++; 354 | if (count > 2) 355 | break; 356 | if (count == n) 357 | return addr + i + 1; 358 | } 359 | return addr; 360 | } 361 | 362 | rule_t *match_rule(event_t *e) { 363 | rule_t r = {0}; 364 | 365 | strncpy(r.exe, e->exe, sizeof(r.exe) - 1); 366 | strncpy(r.cmdline, e->cmdline, sizeof(r.cmdline) - 1); 367 | 368 | if (strcmp(e->namebuf, "socket_sendmsg") == 0) { 369 | snprintf(r.kind, sizeof(r.kind), "send"); 370 | struct sockaddr_in *sin = (struct sockaddr_in*)e->databuf; 371 | if (e->net_remote_domain[0] != 0) { 372 | strncpy(r.addr, e->net_remote_domain, sizeof(r.addr)); 373 | } else { 374 | ntoa(sin->sin_addr, r.addr, sizeof(r.addr)); 375 | } 376 | if (e->type == SOCK_DGRAM) { 377 | strcpy(r.proto, "udp"); 378 | } else if (e->type == SOCK_STREAM) { 379 | strcpy(r.proto, "tcp"); 380 | } else if (e->type == SOCK_RAW) { 381 | strcpy(r.proto, "raw"); 382 | } else { 383 | snprintf(r.proto, sizeof(r.proto) - 1, "socktype=%d", e->type); 384 | } 385 | snprintf(r.port, sizeof(r.port) - 1, "%d", ntohs(sin->sin_port)); 386 | } 387 | 388 | else if (strcmp(e->namebuf, "socket_recvmsg") == 0) { 389 | snprintf(r.kind, sizeof(r.kind), "recv"); 390 | struct sockaddr_in *sin = (struct sockaddr_in*)e->databuf; 391 | snprintf(r.port, sizeof(r.port) - 1, "%d", ntohs(sin->sin_port)); 392 | if (e->type == SOCK_DGRAM) { 393 | strcpy(r.proto, "udp"); 394 | } else if (e->type == SOCK_STREAM) { 395 | strcpy(r.proto, "tcp"); 396 | } else if (e->type == SOCK_RAW) { 397 | strcpy(r.proto, "raw"); 398 | } else { 399 | snprintf(r.proto, sizeof(r.proto) - 1, "socktype=%d", e->type); 400 | } 401 | } 402 | 403 | else { 404 | ASSERT(0, "unknown name [%s]\n", e->namebuf); 405 | } 406 | 407 | i32 nrs = 32; 408 | rule_t rs[nrs]; 409 | memset(rs, 0, sizeof(rs)); 410 | i32 i; 411 | 412 | if (strcmp(r.kind, "send") == 0) { 413 | if (strcmp(r.proto, "tcp") == 0 || strcmp(r.proto, "udp") == 0) { 414 | i = 0; rs[i] = r; 415 | i++; rs[i] = r; sprintf(rs[i].addr, "*"); 416 | i++; rs[i] = r; sprintf(rs[i].cmdline, "*"); 417 | i++; rs[i] = r; sprintf(rs[i].cmdline, "*"); sprintf(rs[i].addr, "*"); 418 | i++; rs[i] = r; sprintf(rs[i].cmdline, "*"); sprintf(rs[i].port, "ephemeral"); sprintf(rs[i].addr, "*"); 419 | i++; rs[i] = r; sprintf(rs[i].cmdline, "*"); sprintf(rs[i].port, "ephemeral"); 420 | i++; rs[i] = r; sprintf(rs[i].port, "ephemeral"); sprintf(rs[i].addr, "*"); 421 | i++; rs[i] = r; sprintf(rs[i].port, "ephemeral"); 422 | for (int j = 0; ; j++) { 423 | char *addr = sub_addr(r.addr, sizeof(r.addr) - 1, j); 424 | if (strncmp(addr, r.addr, sizeof(r.addr)) == 0) { 425 | i++; rs[i] = r; sprintf(rs[i].addr, "*"); 426 | i++; rs[i] = r; sprintf(rs[i].cmdline, "*"); sprintf(rs[i].addr, "*"); 427 | i++; rs[i] = r; sprintf(rs[i].cmdline, "*"); memcpy(rs[i].addr, r.addr, sizeof(r.addr)); 428 | i++; rs[i] = r; memcpy(rs[i].addr, r.addr, sizeof(r.addr)); 429 | break; 430 | } else { 431 | i++; rs[i] = r; sprintf(rs[i].addr, "*.%s", addr); 432 | i++; rs[i] = r; sprintf(rs[i].cmdline, "*"); sprintf(rs[i].addr, "*.%s", addr); 433 | } 434 | } 435 | } else { 436 | i = 0; rs[i] = r; 437 | i++; rs[i] = r; sprintf(rs[i].cmdline, "*"); 438 | } 439 | } 440 | 441 | else if (strcmp(r.kind, "recv") == 0) { 442 | if (strcmp(r.proto, "tcp") == 0 || strcmp(r.proto, "udp") == 0) { 443 | i = 0; rs[i] = r; 444 | i++; rs[i] = r; sprintf(rs[i].cmdline, "*"); 445 | i++; rs[i] = r; sprintf(rs[i].cmdline, "*"); sprintf(rs[i].port, "ephemeral"); 446 | i++; rs[i] = r; sprintf(rs[i].port, "ephemeral"); 447 | } else { 448 | i = 0; rs[i] = r; 449 | i++; rs[i] = r; sprintf(rs[i].cmdline, "*"); 450 | } 451 | } 452 | 453 | else { 454 | ASSERT(0, "unknown kind2 [%s]\n", r.kind); 455 | } 456 | 457 | for (i32 i = 0; i < nrs; i++) { 458 | if (rs[i].kind[0] == 0) { 459 | break; 460 | } 461 | rule_t *match = NULL; 462 | char keybuf[sizeof(r)] = {0}; 463 | i32 keysize = rule_key(&rs[i], keybuf, sizeof(keybuf)); 464 | ASSERT(keysize > 0, "bad key: %d %s\n", keysize, keybuf); 465 | pthread_mutex_lock(&rules_lock); { 466 | MAP_FIND_INDEX(rules, keybuf, keysize); 467 | if (MAP_KEY(rules)) { 468 | match = MAP_VALUE(rules); 469 | } 470 | }; pthread_mutex_unlock(&rules_lock); 471 | if (match) { 472 | return match; 473 | } 474 | } 475 | return NULL; 476 | } 477 | 478 | pthread_mutex_t prompt_lock; 479 | queue_t *prompt_q; 480 | MAP_INIT(prompt, event_t*, 1<<16); 481 | 482 | pthread_mutex_t nl_send_lock; 483 | 484 | void log_decision(event_t *e, i32 response) { 485 | for (i32 i = 0; i < sizeof(e->cmdline); i++) { 486 | if (e->cmdline[i] == '\t') { 487 | e->cmdline[i] = ' '; 488 | } 489 | } 490 | 491 | char response_name[6] = {0}; 492 | if (response == ALLOW) sprintf(response_name, "allow"); 493 | else sprintf(response_name, "deny"); 494 | 495 | char proto[32] = {0}; 496 | if (e->type == SOCK_DGRAM) strcpy(proto, "udp"); 497 | else if (e->type == SOCK_STREAM) strcpy(proto, "tcp"); 498 | else if (e->type == SOCK_RAW) strcpy(proto, "raw"); 499 | else snprintf(proto, sizeof(proto) - 1, "socktype=%d", e->type); 500 | 501 | if (0 == strcmp(e->namebuf, "socket_recvmsg")) { 502 | struct sockaddr *sa = (struct sockaddr*)e->databuf; 503 | if (sa->sa_family == AF_INET) { 504 | struct sockaddr_in *sin_local = (struct sockaddr_in*)e->databuf; 505 | char port[10] = {0}; 506 | sprintf(port, "ephemeral"); 507 | if (ntohs(sin_local->sin_port) < EPHEMERAL_PORT_START) { 508 | sprintf(port, "%d", ntohs(sin_local->sin_port)); 509 | } 510 | LOG("%s %s %d %s %s %s %s\n", response_name, "recv", e->pid, e->exe, port, proto, e->cmdline); 511 | } else { 512 | ASSERT(0, "these are always allowed in kernel\n"); 513 | } 514 | } else if (0 == strcmp(e->namebuf, "socket_sendmsg")) { 515 | struct sockaddr *sa = (struct sockaddr*)e->databuf; 516 | if (sa->sa_family == AF_INET) { 517 | struct sockaddr_in *sin_remote = (struct sockaddr_in*)e->databuf; 518 | char addr_remote[18] = {0}; 519 | ntoa(sin_remote->sin_addr, addr_remote, sizeof(addr_remote)); 520 | if (!e->net_remote_domain[0]) { 521 | LOG("%s %s %d %s %s %d %s %s\n", response_name, "send", e->pid, e->exe, addr_remote, ntohs(sin_remote->sin_port), proto, e->cmdline); 522 | } else { 523 | LOG("%s %s %d %s %s %d %s %s\n", response_name, "send", e->pid, e->exe, e->net_remote_domain, ntohs(sin_remote->sin_port), proto, e->cmdline); 524 | } 525 | } else { 526 | ASSERT(0, "these are always allowed in kernel\n"); 527 | } 528 | } else { 529 | ASSERT(0, "log decision unknown: %s\n", e->namebuf); 530 | } 531 | } 532 | 533 | static int dns_parse_callback(unsigned char *qname, int rr, const void *data, int len, const void *packet) { // based on musl @ 4100279825c17807bdabf1c128ba4e49a1dea406 534 | switch (rr) { 535 | case RR_A: 536 | if (len != 4) 537 | return -1; 538 | char *tmp; 539 | char addr[18] = {0}; 540 | ntoa(*(struct in_addr*)data, addr, sizeof(addr)); 541 | i32 size = sizeof(addr); 542 | pthread_mutex_lock(&dns_lock); { 543 | MAP_FIND_INDEX(dns, addr, size); 544 | if (!MAP_KEY(dns)) { 545 | MALLOC(tmp, size); 546 | memset(tmp, 0, size); 547 | strcpy(tmp, addr); 548 | MAP_SET_INDEX(dns, (u8*)tmp, size, char*); 549 | } 550 | if (MAP_VALUE(dns)) { 551 | free(MAP_VALUE(dns)); 552 | } 553 | size = strlen((char*)qname) + 1; 554 | MALLOC(tmp, size); 555 | memset(tmp, 0, size); 556 | strcpy(tmp, (char*)qname); 557 | MAP_VALUE(dns) = tmp; 558 | LOG("dns %s %s\n", qname, addr); 559 | }; pthread_mutex_unlock(&dns_lock); 560 | return 0; 561 | default: 562 | return 0; 563 | } 564 | } 565 | 566 | void resolve_dns(event_t *e) { 567 | if (strcmp(e->namebuf, "socket_sendmsg") != 0) 568 | return; 569 | struct sockaddr *sa = (struct sockaddr*)e->databuf; 570 | if (sa->sa_family == AF_INET) { 571 | struct sockaddr_in *sin_remote = (struct sockaddr_in*)e->databuf; 572 | char addr[18] = {0}; 573 | ntoa(sin_remote->sin_addr, addr, sizeof(addr)); 574 | pthread_mutex_lock(&dns_lock); { 575 | MAP_FIND_INDEX(dns, addr, sizeof(addr)); 576 | if (MAP_KEY(dns)) { 577 | ASSERT(MAP_VALUE(dns), "missing dns value\n"); 578 | strncpy(e->net_remote_domain, MAP_VALUE(dns), sizeof(e->net_remote_domain)); 579 | } 580 | }; pthread_mutex_unlock(&dns_lock); 581 | } 582 | } 583 | 584 | int sock_fd = 0; 585 | struct sockaddr_nl src_addr = {0}; 586 | struct sockaddr_nl dest_addr = {0}; 587 | 588 | struct nlmsghdr *nlh_send; 589 | struct msghdr msg_send = {0}; 590 | struct iovec iov_send = {0}; 591 | char msgbuf_send[NL_MAX_PAYLOAD] = {0}; 592 | 593 | struct nlmsghdr *nlh_recv; 594 | struct msghdr msg_recv = {0}; 595 | struct iovec iov_recv = {0}; 596 | char msgbuf_recv[NL_MAX_PAYLOAD] = {0}; 597 | 598 | void *loop_netlink(void *vargp) { 599 | int res = 0; 600 | 601 | NL_INIT(); 602 | 603 | // sent init message 604 | memset(msgbuf_send, 0, sizeof(msgbuf_send)); 605 | NL_PREPARE_SEND(msgbuf_send); 606 | ASSERT(sendmsg(sock_fd, &msg_send, 0) >= 0, "failed to send init %d\n", errno); 607 | 608 | // vars 609 | i32 response; 610 | i32 size; 611 | char *head; 612 | 613 | // struct 614 | event_t *e; 615 | MALLOC(e, sizeof(*e)); 616 | 617 | while (1) { 618 | 619 | // reset struct 620 | memset(e, 0, sizeof(*e)); 621 | 622 | // recv and unpack message 623 | NL_PREPARE_RECV(); 624 | res = recvmsg(sock_fd, &msg_recv, 0); 625 | if (res < 0) { 626 | if (errno != 11) // 11 is timeout 627 | LOG("error: recv %d\n", errno); 628 | continue; 629 | } 630 | head = NLMSG_DATA(nlh_recv); 631 | size = sizeof(e->id); memcpy(&e->id, head, size); head += size; 632 | size = sizeof(e->pid); memcpy(&e->pid, head, size); head += size; 633 | size = sizeof(e->type); memcpy(&e->type, head, size); head += size; 634 | size = sizeof(e->namebuf); memcpy(e->namebuf, head, size); head += size; 635 | size = sizeof(e->exe); memcpy(e->exe, head, size); head += size; 636 | size = sizeof(e->cmdline); memcpy(e->cmdline, head, size); head += size; 637 | size = sizeof(e->databuf); memcpy(e->databuf, head, size); head += size; 638 | 639 | // we use tabs as a field separator, so sanitize all tabs 640 | TABS_TO_SPACES(e->exe); 641 | TABS_TO_SPACES(e->cmdline); 642 | 643 | // cmdline use nullbyte to separate argv[] elements, so sanitize all nullbytes 644 | ZEROS_TO_TABS(e->cmdline); 645 | 646 | // we use newlines as a field separator, so sanitize all newlines 647 | NEWLINES_TO_SPACES(e->cmdline); 648 | 649 | // sanitize cmdline since it will be a shell argument 650 | for (int i = 0; i < sizeof(e->cmdline); i++) { 651 | if (e->cmdline[i] == '\'' || 652 | e->cmdline[i] == '"' || 653 | e->cmdline[i] == ';' || 654 | e->cmdline[i] == '|' || 655 | e->cmdline[i] == '&' || 656 | e->cmdline[i] == '>' || 657 | e->cmdline[i] == '<' || 658 | e->cmdline[i] == '(' || 659 | e->cmdline[i] == ')' || 660 | e->cmdline[i] == '{' || 661 | e->cmdline[i] == '}' || 662 | e->cmdline[i] == '$') 663 | { 664 | e->cmdline[i] = '_'; 665 | } 666 | } 667 | 668 | // resolve dns 669 | resolve_dns(e); 670 | 671 | // try to match a rule to the event 672 | rule_t *r = match_rule(e); 673 | 674 | // on hit, apply rule 675 | if (r) { 676 | 677 | // send response to kernel 678 | pthread_mutex_lock(&nl_send_lock); { 679 | if (strcmp(r->response, "allow") == 0) { 680 | response = ALLOW; 681 | } else if (strcmp(r->response, "deny") == 0) { 682 | response = DENY; 683 | } else { 684 | ASSERT(0, "unknown response2 [%s]\n", r->response); 685 | } 686 | memset(msgbuf_send, 0, sizeof(msgbuf_send)); 687 | head = msgbuf_send; 688 | size = sizeof(e->id); memcpy(head, &e->id, size); head += size; 689 | size = sizeof(response); memcpy(head, &response, size); head += size; 690 | NL_PREPARE_SEND(msgbuf_send); 691 | res = sendmsg(sock_fd, &msg_send, 0); 692 | log_decision(e, response); 693 | }; pthread_mutex_unlock(&nl_send_lock); 694 | if (res < 0) { 695 | LOG("error: send %d\n", errno); 696 | } 697 | 698 | } 699 | 700 | // on miss, enqueue for user prompt. 701 | else { 702 | i32 res; 703 | pthread_mutex_lock(&prompt_lock); { 704 | MAP_FIND_INDEX(prompt, &e->id, sizeof(e->id)); 705 | // if id is already in known, skip. recv is idempotent to prompt queue. 706 | if (MAP_KEY(prompt)) { 707 | pthread_mutex_unlock(&prompt_lock); 708 | continue; 709 | } 710 | // malloc and copy event 711 | event_t *prompt_event; 712 | MALLOC(prompt_event, sizeof(*prompt_event)); 713 | memcpy(prompt_event, e, sizeof(*e)); 714 | // set event in prompt map by id 715 | i32 *key; 716 | MALLOC(key, sizeof(*key)); 717 | *key = e->id; 718 | MAP_SET_INDEX(prompt, (u8*)key, sizeof(*key), event_t*); 719 | MAP_VALUE(prompt) = prompt_event; 720 | // enqueue id 721 | u8 *val; 722 | MALLOC(val, sizeof(e->id)); 723 | memcpy(val, &e->id, sizeof(e->id)); 724 | res = queue_put(prompt_q, val); 725 | }; pthread_mutex_unlock(&prompt_lock); 726 | 727 | // send DENY to kernel when prompt queue is full 728 | if (res != 0) { 729 | i32 res; 730 | pthread_mutex_lock(&nl_send_lock); { 731 | memset(msgbuf_send, 0, sizeof(msgbuf_send)); 732 | char *head = msgbuf_send; 733 | i32 size; 734 | i32 response = DENY; 735 | size = sizeof(e->id); memcpy(head, &e->id, size); head += size; 736 | size = sizeof(i32); memcpy(head, &response, size); head += size; 737 | NL_PREPARE_SEND(msgbuf_send); 738 | res = sendmsg(sock_fd, &msg_send, 0); 739 | fprintf(stdout, "prompt queue full: "); 740 | log_decision(e, response); 741 | }; pthread_mutex_unlock(&nl_send_lock); 742 | if (res < 0) { 743 | LOG("error: send %d\n", errno); 744 | } 745 | } 746 | 747 | } 748 | } 749 | } 750 | 751 | i32 prompt(event_t *e, char *payload, i32 size) { 752 | char outfile [64] = {0}; 753 | sprintf(outfile, "/tmp/snitch_%d", e->id); 754 | char inbuf[4096] = {0}; 755 | i32 n = sprintf(inbuf, "DISPLAY=:0 st snitch-prompt '%.*s' %s 2>/dev/null", size, payload, outfile); 756 | ASSERT(n < sizeof(inbuf), "prompt inbuf overflow\n"); 757 | FILE *f = popen(inbuf, "r"); 758 | if (!f) { 759 | LOG("prompt failure1: deny\n"); 760 | return DENY; 761 | } 762 | char buf[1] = {0}; 763 | while (fread(buf, 1, sizeof(buf), f)) {} 764 | pclose(f); 765 | char outbuf[4096] = {0}; 766 | f = fopen(outfile, "r"); 767 | if (!f) { 768 | LOG("prompt failure3: deny\n"); 769 | return DENY; 770 | } 771 | n = fread(outbuf, 1, sizeof(outbuf), f); 772 | ASSERT(n < sizeof(outbuf), "bad outfile read from prompt: %d\n", n); 773 | ASSERT(unlink(outfile) == 0, "failed to rm: %s\n", outfile); 774 | return add_rule(outbuf, sizeof(outbuf)); 775 | } 776 | 777 | void do_prompt(result_t *result, event_t *e) { 778 | char payload1[4096] = {0}; 779 | if (0 == strcmp(e->namebuf, "socket_recvmsg")) { 780 | struct sockaddr_in *sin_local = (struct sockaddr_in*)e->databuf; 781 | char proto[5] = {0}; 782 | if (e->type == SOCK_DGRAM) { 783 | strcpy(proto, "udp"); 784 | } else if (e->type == SOCK_STREAM) { 785 | strcpy(proto, "tcp"); 786 | } else if (e->type == SOCK_RAW) { 787 | strcpy(proto, "raw"); 788 | } else { 789 | snprintf(proto, sizeof(proto) - 1, "socktype=%d", e->type); 790 | } 791 | ASSERT(snprintf(payload1, sizeof(payload1) - 1, "recv\n%s\n%d\t%s\n%s", e->exe, ntohs(sin_local->sin_port), proto, e->cmdline) < sizeof(payload1), "payload1 overflow\n"); 792 | result->response = prompt(e, payload1, sizeof(payload1));; 793 | } 794 | else if (0 == strcmp(e->namebuf, "socket_sendmsg")) { 795 | struct sockaddr_in *sin_remote = (struct sockaddr_in*)e->databuf; 796 | char addr_remote[18] = {0}; 797 | ntoa(sin_remote->sin_addr, addr_remote, sizeof(addr_remote)); 798 | char *addr = addr_remote; 799 | if (e->net_remote_domain[0] != 0) { 800 | addr = e->net_remote_domain; 801 | } 802 | char port[6] = {0}; 803 | snprintf(port, sizeof(port), "%d", ntohs(sin_remote->sin_port)); 804 | char proto[5] = {0}; 805 | if (e->type == SOCK_DGRAM) { 806 | strcpy(proto, "udp"); 807 | } else if (e->type == SOCK_STREAM) { 808 | strcpy(proto, "tcp"); 809 | } else if (e->type == SOCK_RAW) { 810 | strcpy(proto, "raw"); 811 | } else { 812 | snprintf(proto, sizeof(proto) - 1, "socktype=%d", e->type); 813 | } 814 | ASSERT(snprintf(payload1, sizeof(payload1) - 1, "send\n%s\n%s\t%s\t%s\n%s", e->exe, addr, port, proto, e->cmdline) < sizeof(payload1), "payload1 overflow\n"); 815 | result->response = prompt(e, payload1, sizeof(payload1)); 816 | } 817 | else { 818 | ASSERT(0, "bad name: %s\n", e->namebuf); 819 | } 820 | } 821 | 822 | void *loop_rules_writer(void *vargp) { 823 | while (1) { 824 | 825 | usleep(1000 * 1000); 826 | 827 | pthread_mutex_lock(&rules_lock); { 828 | if (!rules_file_needs_write) { 829 | pthread_mutex_unlock(&rules_lock); 830 | continue; 831 | } 832 | }; pthread_mutex_unlock(&rules_lock); 833 | 834 | ARRAY_INIT(rule_lines, char*); 835 | 836 | pthread_mutex_lock(&rules_lock); { 837 | for (i32 i = 0; i < MAP_SIZE(rules); i++) { 838 | if (MAP_VALUES(rules)[i] != NULL && strncmp(MAP_VALUES(rules)[i]->duration, "forever", 7) == 0) { 839 | char buf[2048] = {0}; 840 | i32 size = rule_format(MAP_VALUES(rules)[i], buf, sizeof(buf)); 841 | char *line; 842 | MALLOC(line, size + 1); 843 | memset(line, 0, size + 1); 844 | strncpy(line, buf, size); 845 | ARRAY_APPEND(rule_lines, line, char*); 846 | } 847 | } 848 | }; pthread_mutex_unlock(&rules_lock); 849 | 850 | qsort(rule_lines, ARRAY_SIZE(rule_lines), sizeof(char*), sortcmp); 851 | 852 | pthread_mutex_lock(&rules_file_lock); { 853 | FILE *f = fopen(rules_file, "w"); 854 | ASSERT(f, "failed to open rules_file: %s\n", rules_file); 855 | for (i32 i = 0; i < ARRAY_SIZE(rule_lines); i++) { 856 | i32 size = strlen(rule_lines[i]); 857 | ASSERT(fwrite(rule_lines[i], 1, size, f) == size, "short write on rules file\n"); 858 | ASSERT(fwrite("\n", 1, 1, f) == 1, "short write on rules file newline\n"); 859 | } 860 | ASSERT(fclose(f) == 0, "failed to close rules file on write\n"); 861 | rules_file_needs_write = 0; 862 | }; pthread_mutex_unlock(&rules_file_lock); 863 | 864 | LOG("write rules file\n"); 865 | 866 | free(rule_lines); 867 | 868 | } 869 | } 870 | 871 | void *loop_rules_expirer(void *vargp) { 872 | while (1) { 873 | 874 | usleep(1000 * 1000); 875 | 876 | pthread_mutex_lock(&rules_lock); { 877 | 878 | for (i32 i = 0; i < MAP_SIZE(rules); i++) { 879 | rule_t *r = MAP_VALUES(rules)[i]; 880 | char *key = (char*)MAP_KEYS(rules)[i]; 881 | if (r && key) { 882 | if ((strncmp(r->duration, "1-minute", sizeof(r->duration)) == 0 && unix_seconds() - r->creation > 60) || 883 | (strncmp(r->duration, "24-hour", sizeof(r->duration)) == 0 && unix_seconds() - r->creation > 60 * 60 * 24)) 884 | { 885 | LOG("expire-rule %s\n", key); 886 | MAP_UNSET_INDEX(rules, key, MAP_SIZES(rules)[i]); 887 | free(MAP_VALUES(rules)[i]); 888 | MAP_VALUES(rules)[i] = NULL; 889 | } 890 | } 891 | } 892 | 893 | }; pthread_mutex_unlock(&rules_lock); 894 | 895 | } 896 | } 897 | 898 | void *loop_rules_reader(void *vargp) { 899 | while (1) { 900 | struct stat st; 901 | 902 | pthread_mutex_lock(&rules_file_lock); { 903 | 904 | if (stat(rules_file, &st) == 0) { 905 | i64 mtime = st.st_mtim.tv_sec * (i64)1000000 + st.st_mtim.tv_nsec; 906 | if (rules_file_mtime == mtime) { 907 | pthread_mutex_unlock(&rules_file_lock); 908 | usleep(1000 * 1000); 909 | continue; 910 | } 911 | rules_file_mtime = mtime; 912 | 913 | pthread_mutex_lock(&rules_lock); { 914 | 915 | for (i32 i = 0; i < MAP_SIZE(rules); i++) { 916 | rule_t *r = MAP_VALUES(rules)[i]; 917 | if (r) { 918 | r->meta = 1; 919 | } 920 | } 921 | 922 | char buf[2048] = {0}; 923 | char *head = buf; 924 | FILE *f = fopen(rules_file, "r"); 925 | ASSERT(f, "failed to open rules files: %s\n", rules_file); 926 | i32 stop = 0; 927 | while (!stop) { 928 | if (!fread(head, 1, 1, f)) { 929 | stop = 1; 930 | fclose(f); 931 | } 932 | i32 size = head - buf; 933 | ASSERT(size < sizeof(buf) - 1, "rule line too long"); 934 | if (size && (stop || *head == '\n')) { 935 | *head = 0; 936 | rule_t *r = rule_parse(buf, size); 937 | if (r) { 938 | char keybuf[sizeof(*r)] = {0}; 939 | i32 keysize = rule_key(r, keybuf, sizeof(keybuf)); 940 | MAP_FIND_INDEX(rules, keybuf, keysize); 941 | if (!MAP_KEY(rules)) { 942 | char *key; 943 | MALLOC(key, keysize + 1); 944 | memset(key, 0, keysize + 1); 945 | strncpy(key, keybuf, keysize); 946 | MAP_SET_INDEX(rules, (u8*)key, keysize, rule_t*); 947 | LOG("load-rule %s\n", buf); 948 | } 949 | if (MAP_VALUE(rules)) { 950 | u8 meta = MAP_VALUE(rules)->meta; 951 | MAP_VALUE(rules)->meta = 0; 952 | if (!rule_equal(r, MAP_VALUE(rules))) { 953 | LOG("update-rule %s\n", buf); 954 | } 955 | MAP_VALUE(rules)->meta = meta; 956 | free(MAP_VALUE(rules)); 957 | } 958 | MAP_VALUE(rules) = r; 959 | } 960 | memset(buf, 0, sizeof(buf)); 961 | head = buf; 962 | } else { 963 | head++; 964 | } 965 | } 966 | 967 | for (i32 i = 0; i < MAP_SIZE(rules); i++) { 968 | rule_t *r = MAP_VALUES(rules)[i]; 969 | char *key = (char*)MAP_KEYS(rules)[i]; 970 | if (r && r->meta == 1 && key && strncmp(r->duration, "forever", sizeof(r->duration)) == 0) { 971 | LOG("delete-rule %s\n", key); 972 | MAP_UNSET_INDEX(rules, key, MAP_SIZES(rules)[i]); 973 | free(MAP_VALUES(rules)[i]); 974 | MAP_VALUES(rules)[i] = NULL; 975 | } 976 | } 977 | 978 | }; pthread_mutex_unlock(&rules_lock); 979 | 980 | } 981 | }; pthread_mutex_unlock(&rules_file_lock); 982 | } 983 | } 984 | 985 | void *loop_prompt(void *vargp) { 986 | while (1) { 987 | i32 id; 988 | event_t *e; 989 | 990 | // dequeue prompt id and lookup value in prompt map 991 | pthread_mutex_lock(&prompt_lock); { 992 | u8 *val = queue_get(prompt_q); 993 | if (!val) { 994 | pthread_mutex_unlock(&prompt_lock); 995 | usleep(1000); 996 | continue; 997 | } 998 | id = *(i32*)val; 999 | free(val); 1000 | MAP_FIND_INDEX(prompt, &id, sizeof(id)); 1001 | ASSERT(MAP_KEY(prompt), "no key in map\n"); 1002 | e = MAP_VALUE(prompt); 1003 | }; pthread_mutex_unlock(&prompt_lock); 1004 | 1005 | result_t rs = {0}; 1006 | result_t *result = &rs; 1007 | result->response = -1; 1008 | result->id = id; 1009 | 1010 | // check rule again since rules can change while enqueued 1011 | rule_t *rule = match_rule(e); 1012 | 1013 | if (rule) { 1014 | if (strcmp(rule->response, "allow") == 0) { 1015 | result->response = ALLOW; 1016 | } else if (strcmp(rule->response, "deny") == 0) { 1017 | result->response = DENY; 1018 | } else { 1019 | ASSERT(0, "bad rule response [%s]\n", rule->response); 1020 | } 1021 | } 1022 | 1023 | else { 1024 | do_prompt(result, e); 1025 | } 1026 | 1027 | // send response to kernel 1028 | i32 res; 1029 | pthread_mutex_lock(&nl_send_lock); { 1030 | memset(msgbuf_send, 0, sizeof(msgbuf_send)); 1031 | char *head = msgbuf_send; 1032 | int size; 1033 | size = sizeof(id); memcpy(head, &id, size); head += size; 1034 | size = sizeof(result->response); memcpy(head, &result->response, size); head += size; 1035 | NL_PREPARE_SEND(msgbuf_send); 1036 | res = sendmsg(sock_fd, &msg_send, 0); 1037 | log_decision(e, result->response); 1038 | }; pthread_mutex_unlock(&nl_send_lock); 1039 | 1040 | // free value from prompt map 1041 | pthread_mutex_lock(&prompt_lock); { 1042 | MAP_UNSET_INDEX(prompt, &id, sizeof(id)); 1043 | free(MAP_VALUE(prompt)); 1044 | MAP_VALUE(prompt) = NULL; 1045 | }; pthread_mutex_unlock(&prompt_lock); 1046 | 1047 | if (res < 0) { 1048 | LOG("error: send %d\n", errno); 1049 | continue; 1050 | } 1051 | } 1052 | } 1053 | 1054 | static int nf_callback(struct nfq_q_handle *qh, struct nfgenmsg *nfmsg, struct nfq_data *nfad, void *data) { 1055 | unsigned char *buffer = NULL; 1056 | struct nfqnl_msg_packet_hdr *ph = nfq_get_msg_packet_hdr(nfad); 1057 | unsigned int id = ntohl(ph->packet_id); 1058 | int size = nfq_get_payload(nfad, &buffer); 1059 | if (size > 0) { 1060 | packet_t p = {0}; 1061 | if (0 == parse_ipv4(buffer, size, &p)) { 1062 | if (p.sport == 53) { 1063 | dns_parse(buffer + p.offset, p.size, dns_parse_callback); 1064 | } 1065 | } 1066 | } 1067 | nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL); 1068 | return 0; 1069 | } 1070 | 1071 | void *loop_nfq(void *vargp) { 1072 | nftables_init(); 1073 | struct nfq_handle *h = nfq_open(); 1074 | ASSERT(h != NULL, "failed to open nfq\n"); 1075 | ASSERT(nfq_unbind_pf(h, AF_INET) >= 0, "failed to unbind inet %d\n", errno); 1076 | ASSERT(nfq_bind_pf(h, AF_INET) >= 0, "failed to bind inet %d\n", errno); 1077 | struct nfq_q_handle *qh = nfq_create_queue(h, NFQ_QUEUE, &nf_callback, (void*)((uintptr_t)unix_nano())); 1078 | ASSERT(qh != NULL, "failed to create queue\n"); 1079 | ASSERT(nfq_set_queue_maxlen(qh, NFQ_QUEUE_SIZE) >= 0, "failed to set queue len\n"); 1080 | ASSERT(nfq_set_mode(qh, NFQNL_COPY_PACKET, NFQ_PACKET_SIZE) >= 0, "failed to set mode\n"); 1081 | int fd = nfq_fd(h); 1082 | ASSERT(nfnl_rcvbufsiz(nfq_nfnlh(h), NFQ_TOTAL_SIZE) >= 0, "failed to set rcvbuf size\n"); 1083 | char buf[4096] __attribute__ ((aligned)); 1084 | int rcvd, opt = 1; 1085 | setsockopt(fd, SOL_NETLINK, NETLINK_NO_ENOBUFS, &opt, sizeof(int)); 1086 | while (1) { 1087 | memset(buf, 0, sizeof(buf)); 1088 | rcvd = recv(fd, buf, sizeof(buf), 0); 1089 | ASSERT(rcvd >= 0, "nfq failed: errno: %d\n", errno); 1090 | nfq_handle_packet(h, buf, rcvd); 1091 | } 1092 | return NULL; 1093 | } 1094 | 1095 | void thread(void *(*func)(void *)) { 1096 | pthread_t t; 1097 | pthread_create(&t, NULL, func, NULL); 1098 | } 1099 | 1100 | void which_terminal() { 1101 | FILE *f = popen("which foot", "r"); 1102 | ASSERT(f, "failed to which foot\n"); 1103 | char buf[1] = {0}; 1104 | while (fread(buf, 1, sizeof(buf), f)) {} 1105 | foot_terminal = pclose(f) == 0; 1106 | if (foot_terminal) { 1107 | setenv("SNITCH_PROMPT_INTERVAL", "0.05", 1); 1108 | } 1109 | } 1110 | 1111 | int main(int argc, char **argv) { 1112 | 1113 | which_terminal(); 1114 | 1115 | strcpy(home, getenv("HOME")); 1116 | ASSERT(sprintf(rules_file, "%s/.snitch.rules", home) > 0, "failed to sprintf rules_file\n"); 1117 | LOG("rules_file: %s\n", rules_file); 1118 | 1119 | i32 size = 1<<16; 1120 | prompt_q = queue_init(size); 1121 | 1122 | MAP_ALLOC(dns, char*); 1123 | MAP_ALLOC(rules, rule_t*); 1124 | MAP_ALLOC(prompt, event_t*); 1125 | 1126 | thread(loop_nfq); 1127 | thread(loop_prompt); 1128 | thread(loop_rules_writer); 1129 | thread(loop_rules_reader); 1130 | thread(loop_rules_expirer); 1131 | thread(loop_netlink); 1132 | 1133 | // block main thread 1134 | while (1) 1135 | usleep(1000*1000); 1136 | 1137 | } 1138 | -------------------------------------------------------------------------------- /snitch/snitch.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -xeou pipefail 3 | 4 | cd $(dirname $0) 5 | 6 | rm -f snitch 7 | 8 | bash build.sh 9 | 10 | echo start snitch 11 | 12 | sudo kill $(ps -ef | grep '\./snitch' | awk '{print $2}') || true 13 | sleep 1 14 | 15 | # wayland postmarketos needs to do this to allow root gui access 16 | if which foot &>/dev/null; then 17 | xhost +si:localuser:root 18 | fi 19 | 20 | if [ "${COLOR:-y}" = n ]; then 21 | sudo -E stdbuf -o0 ./snitch 22 | else 23 | sudo -E stdbuf -o0 ./snitch 2>&1\ 24 | | tee ${SNITCH_LOG:-/tmp/snitch.log} \ 25 | | color \ 26 | allow:green \ 27 | deny:red \ 28 | dns:white \ 29 | add-rule:white \ 30 | delete-rule:white \ 31 | update-rule:white \ 32 | expire-rule:white \ 33 | load-rule:white \ 34 | 1:cyan \ 35 | 2:magenta \ 36 | 3:yellow \ 37 | 4:blue \ 38 | 5:white \ 39 | | count-last 40 | fi 41 | -------------------------------------------------------------------------------- /snitch/util/array.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "util.h" 4 | 5 | #define ARRAY_EXPAND_CAPACITY 1024 * 512 6 | 7 | #define ARRAY_INIT(array, type) \ 8 | u64 array##_size = 0; \ 9 | u64 array##_capacity = ARRAY_EXPAND_CAPACITY; \ 10 | type *array; \ 11 | MALLOC(array, sizeof(type) * array##_capacity); 12 | 13 | #define ARRAY_ADD(array, size, type) \ 14 | do { \ 15 | if (array##_size + size > array##_capacity) { \ 16 | array##_capacity += ARRAY_EXPAND_CAPACITY; \ 17 | REALLOC(array, sizeof(type) * array##_capacity); \ 18 | } \ 19 | array##_size += size; \ 20 | } while(0) 21 | 22 | #define ARRAY_APPEND(array, val, type) \ 23 | do { \ 24 | if (array##_size == array##_capacity) { \ 25 | array##_capacity += ARRAY_EXPAND_CAPACITY; \ 26 | REALLOC(array, sizeof(type) * array##_capacity); \ 27 | } \ 28 | array[array##_size++] = val; \ 29 | } while(0) 30 | 31 | #define ARRAY_POP(array, dst) \ 32 | do { \ 33 | if (array##_size) { \ 34 | dst = array[--array##_size]; \ 35 | } else { \ 36 | dst = NULL; \ 37 | } \ 38 | } while(0) 39 | 40 | #define ARRAY_RESET(array) \ 41 | do { \ 42 | array##_size = 0; \ 43 | } while(0) 44 | 45 | #define ARRAY_SIZE(array) \ 46 | array##_size 47 | -------------------------------------------------------------------------------- /snitch/util/map.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "xxh3.h" 3 | #include "util.h" 4 | #include 5 | 6 | #define MAP_USAGE_FACTOR 0.5 7 | 8 | #define MAP_INDEX(map) map##_index 9 | #define MAP_KEYS(map) map##_keys 10 | #define MAP_SIZES(map) map##_sizes 11 | #define MAP_SIZE(map) map##_size 12 | #define MAP_VALUES(map) map##_values 13 | #define MAP_USED(map) map##_used 14 | #define MAP_KEY(map) map##_keys[map##_index] 15 | #define MAP_VALUE(map) map##_values[map##_index] 16 | 17 | #define MAP_INIT(map, type, initial_size) \ 18 | u64 map##_index = 0; \ 19 | u16 *map##_sizes; \ 20 | type *map##_values; \ 21 | u8 **map##_keys_tmp; \ 22 | u16 *map##_sizes_tmp; \ 23 | type *map##_values_tmp; \ 24 | u64 map##_used = 0; \ 25 | u64 map##_size = initial_size; \ 26 | u8 **map##_keys; \ 27 | 28 | #define MAP_ALLOC(map, type) \ 29 | MALLOC(map##_keys, sizeof(u8*) * map##_size); \ 30 | for (u64 i = 0; i < map##_size; i++) \ 31 | map##_keys[i] = NULL; \ 32 | MALLOC(map##_sizes, sizeof(u16) * map##_size); \ 33 | memset(map##_sizes, 0, sizeof(u16) * map##_size); \ 34 | MALLOC(map##_values, sizeof(type) * map##_size); \ 35 | memset(map##_values, 0, sizeof(type) * map##_size); 36 | 37 | #define MAP_FIND_INDEX(map, key, size) \ 38 | do { \ 39 | map##_index = XXH3_64bits(key, size) % map##_size; \ 40 | while (1) { \ 41 | if (map##_keys[map##_index] == NULL) \ 42 | break; \ 43 | if (map##_sizes[map##_index] == size && \ 44 | memcmp(map##_keys[map##_index], key, size) == 0) \ 45 | break; \ 46 | map##_index = (map##_index + 1) % map##_size; \ 47 | } \ 48 | } while (0) 49 | 50 | #define MAP_SET_INDEX(map, key, size, type) \ 51 | do { \ 52 | MAP_FIND_INDEX(map, key, size); \ 53 | if (map##_keys[map##_index] == NULL) { \ 54 | map##_keys[map##_index] = key; \ 55 | map##_sizes[map##_index] = size; \ 56 | map##_used++; \ 57 | if (map##_used > map##_size * MAP_USAGE_FACTOR) { \ 58 | MAP_GROW(map, type); \ 59 | MAP_FIND_INDEX(map, key, size); \ 60 | } \ 61 | } \ 62 | } while (0) 63 | 64 | #define MAP_UNSET_INDEX(map, key, size) \ 65 | do { \ 66 | MAP_FIND_INDEX(map, key, size); \ 67 | if (map##_keys[map##_index] != NULL) { \ 68 | free(map##_keys[map##_index]); \ 69 | map##_keys[map##_index] = NULL; \ 70 | map##_used--; \ 71 | } \ 72 | } while (0) 73 | 74 | #define MAP_GROW(map, type) \ 75 | do { \ 76 | map##_keys_tmp = map##_keys; \ 77 | map##_sizes_tmp = map##_sizes; \ 78 | map##_values_tmp = map##_values; \ 79 | map##_size *= 2; \ 80 | map##_used = 0; \ 81 | MALLOC(map##_keys, sizeof(u8 *) * map##_size); \ 82 | for (u64 i = 0; i < map##_size; i++) \ 83 | map##_keys[i] = NULL; \ 84 | MALLOC(map##_sizes, sizeof(i32) * map##_size); \ 85 | memset(map##_sizes, 0, sizeof(i32) * map##_size); \ 86 | MALLOC(map##_values, sizeof(type) * map##_size); \ 87 | memset(map##_values, 0, sizeof(type) * map##_size); \ 88 | for (u64 i = 0; i < map##_size / 2; i++) { \ 89 | if (map##_keys_tmp[i] == NULL) \ 90 | continue; \ 91 | MAP_FIND_INDEX(map, map##_keys_tmp[i], map##_sizes_tmp[i]); \ 92 | map##_keys[map##_index] = map##_keys_tmp[i]; \ 93 | map##_sizes[map##_index] = map##_sizes_tmp[i]; \ 94 | map##_values[map##_index] = map##_values_tmp[i]; \ 95 | map##_used++; \ 96 | } \ 97 | free(map##_keys_tmp); \ 98 | free(map##_sizes_tmp); \ 99 | free(map##_values_tmp); \ 100 | } while (0) 101 | -------------------------------------------------------------------------------- /snitch/util/nft.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include "util.h" 14 | 15 | #define NFQ_SIZEOF_OUTPUT 1024 * 1024 16 | #define NFQ_LINKTYPE_IPV4 12 17 | #define NFQ_QUEUE 0 18 | #define NFQ_QUEUE_SIZE 4096 19 | #define NFQ_PACKET_SIZE 4096 20 | #define NFQ_TOTAL_SIZE 4096 * 4096 21 | 22 | #define RR_A 1 23 | #define RR_CNAME 5 24 | 25 | int dns_parse(unsigned char *r, int rlen, int (*callback)(unsigned char *, int, const void *, int, const void *)) { // based on musl @ 4100279825c17807bdabf1c128ba4e49a1dea406 26 | int qdcount, ancount; 27 | unsigned char *p; 28 | unsigned char *qname; 29 | int len; 30 | if (rlen<12) return -1; 31 | if ((r[3]&15)) return 0; 32 | p = r+12; 33 | qdcount = r[4]*256 + r[5]; 34 | ancount = r[6]*256 + r[7]; 35 | if (qdcount+ancount > 64) return -1; 36 | while (qdcount--) { 37 | int qoffset = 0; // start change to musl code. keep a pointer to the qname and pass it to the callback. 38 | while (1) { 39 | if (qoffset > rlen - (p-r)) return -1; 40 | if (p[qoffset] == 0) break; 41 | int size = p[qoffset]; 42 | p[qoffset] = '.'; 43 | qoffset += size + 1; 44 | } 45 | qname = p + 1; // end change to musl code. 46 | while (p-r < rlen && *p-1U < 127) p++; 47 | if (*p>193 || (*p==193 && p[1]>254) || p>r+rlen-6) 48 | return -1; 49 | p += 5 + !!*p; 50 | } 51 | while (ancount--) { 52 | while (p-r < rlen && *p-1U < 127) p++; 53 | if (*p>193 || (*p==193 && p[1]>254) || p>r+rlen-6) 54 | return -1; 55 | p += 1 + !!*p; 56 | len = p[8]*256 + p[9]; 57 | if (p+len > r+rlen) return -1; 58 | if (callback(qname, p[1], p+10, len, r) < 0) return -1; 59 | p += 10 + len; 60 | } 61 | return 0; 62 | } 63 | 64 | typedef struct packet_s { 65 | char proto[5]; 66 | char saddr[18]; 67 | char daddr[18]; 68 | int sport; 69 | int dport; 70 | int offset; 71 | int size; 72 | } packet_t; 73 | 74 | int parse_ipv4(unsigned char *buf, int size, packet_t *p) { 75 | p->offset = 0; 76 | struct iphdr *ip = (struct iphdr*)buf; 77 | p->offset += sizeof(*ip); 78 | if (p->offset > size) 79 | return -1; 80 | if (ip->version != 4) 81 | return -1; 82 | ntoa(*(struct in_addr*)&ip->saddr, p->saddr, sizeof(p->saddr)); 83 | ntoa(*(struct in_addr*)&ip->daddr, p->daddr, sizeof(p->daddr)); 84 | switch (ip->protocol) { 85 | case IPPROTO_ICMP: 86 | sprintf(p->proto, "icmp"); 87 | return 0; 88 | case IPPROTO_TCP: 89 | sprintf(p->proto, "tcp"); 90 | struct tcphdr *tcp = (struct tcphdr*)(buf + p->offset); 91 | p->offset += sizeof(*tcp); 92 | if (p->offset > size) 93 | return -1; 94 | p->sport = ntohs(tcp->th_sport); 95 | p->dport = ntohs(tcp->th_dport); 96 | return 0; 97 | case IPPROTO_UDP: 98 | sprintf(p->proto, "udp"); 99 | struct udphdr *udp = (struct udphdr*)(buf + p->offset); 100 | p->offset += sizeof(*udp); 101 | if (p->offset > size) 102 | return -1; 103 | p->sport = ntohs(udp->uh_sport); 104 | p->dport = ntohs(udp->uh_dport); 105 | p->size = ntohs(ip->tot_len) - p->offset; 106 | return 0; 107 | default: 108 | sprintf(p->proto, "%d", ip->protocol); 109 | return 0; 110 | } 111 | } 112 | 113 | char *conf_content = 114 | "flush ruleset\n" 115 | "table ip snitch {\n" 116 | " chain inbound {\n" 117 | " type filter hook input priority filter; policy accept;\n" 118 | " udp sport 53 counter queue num 0 bypass\n" 119 | " }\n" 120 | "}\n"; 121 | 122 | #define CONF_FILE "/tmp/nftables.conf" 123 | 124 | void nftables_init() { 125 | FILE *f = fopen(CONF_FILE, "w"); 126 | ASSERT(strlen(conf_content) == fwrite(conf_content, 1, strlen(conf_content), f), "failed to write nftables conf to /tmp\n"); 127 | ASSERT(0 == fclose(f), "failed to close nftables conf file\n"); 128 | ASSERT(0 == pclose(popen("nft -f " CONF_FILE, "r")), "failed to load nft ruleset\n"); 129 | } 130 | -------------------------------------------------------------------------------- /snitch/util/nl.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #define NL_MAX_PAYLOAD 2048 4 | 5 | #define NL_USER 31 6 | 7 | #define NL_INIT() \ 8 | nlh_send = malloc(NLMSG_SPACE(NL_MAX_PAYLOAD)); \ 9 | nlh_recv = malloc(NLMSG_SPACE(NL_MAX_PAYLOAD)); \ 10 | /* */ \ 11 | sock_fd = socket(PF_NETLINK, SOCK_RAW, NL_USER); \ 12 | ASSERT(sock_fd > 0, "failed to get nl socket %d\n", sock_fd); \ 13 | /* */ \ 14 | memset(&src_addr, 0, sizeof(src_addr)); \ 15 | src_addr.nl_family = AF_NETLINK; \ 16 | src_addr.nl_pid = getpid(); \ 17 | src_addr.nl_groups = 0; \ 18 | ASSERT(0 == bind(sock_fd, (struct sockaddr*)&src_addr, sizeof(src_addr)), "failed to bind %d\n", errno); \ 19 | /* */ \ 20 | memset(&dest_addr, 0, sizeof(dest_addr)); \ 21 | dest_addr.nl_family = AF_NETLINK; \ 22 | dest_addr.nl_pid = 0; \ 23 | dest_addr.nl_groups = 0; 24 | 25 | #define NL_PREPARE_RECV() \ 26 | memset(nlh_recv, 0, NLMSG_SPACE(NL_MAX_PAYLOAD)); \ 27 | nlh_recv->nlmsg_len = NLMSG_SPACE(NL_MAX_PAYLOAD); \ 28 | nlh_recv->nlmsg_pid = getpid(); \ 29 | nlh_recv->nlmsg_flags = 0; \ 30 | memcpy(NLMSG_DATA(nlh_recv), msgbuf_recv, sizeof(msgbuf_recv)); \ 31 | memset(&iov_recv, 0, sizeof(iov_recv)); \ 32 | iov_recv.iov_base = (void *)nlh_recv; \ 33 | iov_recv.iov_len = nlh_recv->nlmsg_len; \ 34 | memset(&msg_recv, 0, sizeof(msg_recv)); \ 35 | msg_recv.msg_name = (void *)&dest_addr; \ 36 | msg_recv.msg_namelen = sizeof(dest_addr); \ 37 | msg_recv.msg_iov = &iov_recv; \ 38 | msg_recv.msg_iovlen = 1; 39 | 40 | #define NL_PREPARE_SEND(msgbuf) \ 41 | memset(nlh_send, 0, NLMSG_SPACE(NL_MAX_PAYLOAD)); \ 42 | nlh_send->nlmsg_len = NLMSG_SPACE(NL_MAX_PAYLOAD); \ 43 | nlh_send->nlmsg_pid = getpid(); \ 44 | nlh_send->nlmsg_flags = 0; \ 45 | memcpy(NLMSG_DATA(nlh_send), msgbuf, sizeof(msgbuf)); \ 46 | memset(&iov_send, 0, sizeof(iov_send)); \ 47 | iov_send.iov_base = (void *)nlh_send; \ 48 | iov_send.iov_len = nlh_send->nlmsg_len; \ 49 | memset(&msg_send, 0, sizeof(msg_send)); \ 50 | msg_send.msg_name = (void *)&dest_addr; \ 51 | msg_send.msg_namelen = sizeof(dest_addr); \ 52 | msg_send.msg_iov = &iov_send; \ 53 | msg_send.msg_iovlen = 1; 54 | -------------------------------------------------------------------------------- /snitch/util/queue.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "util.h" 4 | 5 | typedef struct node_s node_t; 6 | 7 | struct node_s { 8 | u8 *val; 9 | node_t *next; 10 | }; 11 | 12 | typedef struct queue_s { 13 | i32 size; 14 | i32 capacity; 15 | node_t *head; 16 | node_t *tail; 17 | } queue_t; 18 | 19 | queue_t *queue_init(i32 capacity) { 20 | queue_t *q; 21 | MALLOC(q, sizeof(*q)); 22 | q->size = 0; 23 | q->capacity = capacity; 24 | q->head = NULL; 25 | q->tail = NULL; 26 | return q; 27 | } 28 | 29 | i32 queue_put(queue_t *q, u8 *val) { 30 | if (q->size == q->capacity) 31 | return 1; 32 | node_t *n; 33 | MALLOC(n, sizeof(*n)); 34 | n->val = val; 35 | n->next = NULL; 36 | if (!q->head) { 37 | q->head = n; 38 | q->tail = n; 39 | q->size = 1; 40 | return 0; 41 | } 42 | q->tail->next = n; 43 | q->tail = n; 44 | q->size++; 45 | return 0; 46 | } 47 | 48 | u8 *queue_get(queue_t *q) { 49 | if (!q->size) 50 | return NULL; 51 | node_t *n = q->head; 52 | u8 *val = n->val; 53 | q->head = n->next; 54 | free(n); 55 | q->size--; 56 | return val; 57 | } 58 | -------------------------------------------------------------------------------- /snitch/util/util.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | typedef int8_t i8; 12 | typedef int16_t i16; 13 | typedef int32_t i32; 14 | typedef int64_t i64; 15 | typedef uint8_t u8; 16 | typedef uint16_t u16; 17 | typedef uint32_t u32; 18 | typedef uint64_t u64; 19 | typedef float f32; 20 | typedef double f64; 21 | 22 | u32 unix_seconds() { 23 | struct timeval current_time; 24 | gettimeofday(¤t_time, NULL); 25 | return current_time.tv_sec; 26 | } 27 | 28 | i64 unix_nano() { 29 | struct timeval current_time; 30 | gettimeofday(¤t_time, NULL); 31 | return current_time.tv_sec * (i64)1000000 + current_time.tv_usec; 32 | } 33 | 34 | int to_hex(const unsigned char *buf, int size, char *dstbuf, int dstbufsize) { 35 | if (dstbufsize != size * 2 + 1) 36 | return -1; 37 | for (int i = 0; i < size; i++) 38 | sprintf(dstbuf + i*2, "%02x", buf[i]); 39 | return 0; 40 | } 41 | 42 | #define ALLOW 0 43 | #define DENY 1 44 | 45 | #define NEWLINES_TO_SPACES(buf) \ 46 | for (int i = 0; i < sizeof(buf); i++) { \ 47 | if (buf[i] == '\n') { \ 48 | buf[i] = ' '; \ 49 | } \ 50 | } 51 | 52 | #define TABS_TO_SPACES(buf) \ 53 | for (int i = 0; i < sizeof(buf); i++) { \ 54 | if (buf[i] == '\t') { \ 55 | buf[i] = ' '; \ 56 | } \ 57 | } 58 | 59 | #define ZEROS_TO_TABS(buf) \ 60 | for (int i = 0; i < sizeof(buf); i++) { \ 61 | if (buf[i] == 0) { \ 62 | if (i > 0 && buf[i - 1] == '\t') { \ 63 | buf[i - 1] = 0; \ 64 | break; \ 65 | } else { \ 66 | buf[i] = '\t'; \ 67 | } \ 68 | } \ 69 | } 70 | 71 | #define LOG(args...) fprintf(stdout, ##args); 72 | 73 | #define DEBUG(args...) fprintf(stderr, ##args) 74 | 75 | #define ASSERT(cond, ...) \ 76 | do { \ 77 | if (!(cond)) { \ 78 | fprintf(stderr, ##__VA_ARGS__); \ 79 | exit(1); \ 80 | } \ 81 | } while(0) 82 | 83 | #define MALLOC(dst, size) \ 84 | do { \ 85 | dst = malloc(size); \ 86 | ASSERT(dst != NULL, "fatal: failed to allocate memory\n"); \ 87 | } while(0) 88 | 89 | #define REALLOC(dst, size) \ 90 | do { \ 91 | dst = realloc(dst, size); \ 92 | ASSERT(dst != NULL, "fatal: failed to reallocate memory\n"); \ 93 | } while(0) 94 | 95 | void ntoa(struct in_addr in, char *buf, int size) { 96 | ASSERT(size >= 18, "bad size: %d\n", size); 97 | unsigned char *bytes = (unsigned char *) ∈ 98 | snprintf(buf, 18, "%d.%d.%d.%d", bytes[0], bytes[1], bytes[2], bytes[3]); 99 | } 100 | -------------------------------------------------------------------------------- /snitch/vendor/xxh3.h: -------------------------------------------------------------------------------- 1 | /* source: https://github.com/Cyan4973/xxHash/blob/a9054f397d7f41bc505638df3853b270eb9e7493/xxh3.h */ 2 | /* 3 | * xxHash - Extremely Fast Hash algorithm 4 | * Development source file for `xxh3` 5 | * Copyright (C) 2019-2020 Yann Collet 6 | * 7 | * BSD 2-Clause License (https://www.opensource.org/licenses/bsd-license.php) 8 | * 9 | * Redistribution and use in source and binary forms, with or without 10 | * modification, are permitted provided that the following conditions are 11 | * met: 12 | * 13 | * * Redistributions of source code must retain the above copyright 14 | * notice, this list of conditions and the following disclaimer. 15 | * * Redistributions in binary form must reproduce the above 16 | * copyright notice, this list of conditions and the following disclaimer 17 | * in the documentation and/or other materials provided with the 18 | * distribution. 19 | * 20 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 23 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | * 32 | * You can contact the author at: 33 | * - xxHash homepage: https://www.xxhash.com 34 | * - xxHash source repository: https://github.com/Cyan4973/xxHash 35 | */ 36 | 37 | /* 38 | * Note: This file used to host the source code of XXH3_* variants. 39 | * during the development period. 40 | * The source code is now properly integrated within xxhash.h. 41 | * 42 | * xxh3.h is no longer useful, 43 | * but it is still provided for compatibility with source code 44 | * which used to include it directly. 45 | * 46 | * Programs are now highly discouraged to include xxh3.h. 47 | * Include `xxhash.h` instead, which is the officially supported interface. 48 | * 49 | * In the future, xxh3.h will start to generate warnings, then errors, 50 | * then it will be removed from source package and from include directory. 51 | */ 52 | 53 | /* Simulate the same impact as including the old xxh3.h source file */ 54 | 55 | #define XXH_INLINE_ALL 56 | #include "xxhash.h" 57 | --------------------------------------------------------------------------------