├── src ├── .gitignore ├── rust_santa_daemon │ ├── .gitignore │ ├── testrules.json │ ├── src │ │ ├── libsanta │ │ │ ├── consts.rs │ │ │ ├── commands.rs │ │ │ ├── lib.rs │ │ │ ├── uxpc.rs │ │ │ ├── engine_types.rs │ │ │ └── rules.rs │ │ ├── santa-daemon │ │ │ ├── tracer.rs │ │ │ ├── engine.rs │ │ │ ├── cache.rs │ │ │ ├── daemon.rs │ │ │ ├── netlink.rs │ │ │ └── main.rs │ │ └── santactl │ │ │ └── main.rs │ └── Cargo.toml ├── testbins │ ├── allowme │ ├── blockme │ ├── testbin │ ├── allowme.c │ ├── blockme.c │ └── testbin.c └── santa_kmod │ ├── Makefile │ ├── santa_clone.h │ └── santa_clone.c ├── ext-tree ├── .gitignore ├── external.desc ├── overlay │ ├── etc │ │ ├── init.d │ │ │ ├── S90modules │ │ │ └── S99santa_daemon │ │ └── inittab │ ├── allowme │ ├── blockme │ ├── testbin │ └── opt │ │ └── santa │ │ └── rules.json ├── external.mk ├── Config.in ├── package │ ├── santa_kmod │ │ ├── Config.in │ │ └── santa_kmod.mk │ └── rust_santa_daemon │ │ ├── Config.in │ │ └── rust_santa_daemon.mk └── configs │ ├── rust-santa-clone-qemu_x86_64_defconfig │ ├── santa-clone-qemu_x86_64_defconfig │ └── linux.config ├── br-output └── .gitignore ├── .gitignore ├── docker ├── init.sh ├── container.sh └── Dockerfile ├── local-build.sh ├── runbuild.sh ├── qemu-run.sh ├── README.md └── LICENSE /src/.gitignore: -------------------------------------------------------------------------------- 1 | **/.vscode/ 2 | -------------------------------------------------------------------------------- /ext-tree/.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | Makefile 3 | -------------------------------------------------------------------------------- /br-output/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | */ 3 | !.gitignore -------------------------------------------------------------------------------- /ext-tree/external.desc: -------------------------------------------------------------------------------- 1 | name: SANTA_CLONE 2 | -------------------------------------------------------------------------------- /ext-tree/overlay/etc/init.d/S90modules: -------------------------------------------------------------------------------- 1 | modprobe santa_clone 2 | -------------------------------------------------------------------------------- /src/rust_santa_daemon/.gitignore: -------------------------------------------------------------------------------- 1 | debug/ 2 | target/ 3 | 4 | Cargo.lock 5 | **/*.rs.bk 6 | -------------------------------------------------------------------------------- /ext-tree/external.mk: -------------------------------------------------------------------------------- 1 | include $(sort $(wildcard $(BR2_EXTERNAL_SANTA_CLONE_PATH)/package/*/*.mk)) 2 | -------------------------------------------------------------------------------- /src/testbins/allowme: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mellow-hype/santa-linux/HEAD/src/testbins/allowme -------------------------------------------------------------------------------- /src/testbins/blockme: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mellow-hype/santa-linux/HEAD/src/testbins/blockme -------------------------------------------------------------------------------- /src/testbins/testbin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mellow-hype/santa-linux/HEAD/src/testbins/testbin -------------------------------------------------------------------------------- /ext-tree/overlay/allowme: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mellow-hype/santa-linux/HEAD/ext-tree/overlay/allowme -------------------------------------------------------------------------------- /ext-tree/overlay/blockme: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mellow-hype/santa-linux/HEAD/ext-tree/overlay/blockme -------------------------------------------------------------------------------- /ext-tree/overlay/testbin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mellow-hype/santa-linux/HEAD/ext-tree/overlay/testbin -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | image/ 2 | br22-out/ 3 | buildroot-2022.08/ 4 | 5 | # Object files 6 | **/*.o 7 | **/*.ko 8 | **/*.obj 9 | **/*.elf 10 | -------------------------------------------------------------------------------- /docker/init.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | CONTAINER="santa-clone-builder" 3 | 4 | sudo docker build -t $CONTAINER . 5 | echo "Container name is: $CONTAINER" 6 | 7 | -------------------------------------------------------------------------------- /src/testbins/allowme.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | int pid = getpid(); 6 | printf("i should be ALLOWED - my PID is %d\n", pid); 7 | return 0; 8 | } 9 | -------------------------------------------------------------------------------- /src/testbins/blockme.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | int pid = getpid(); 6 | printf("i should be BLOCKED - my PID is %d\n", pid); 7 | return 0; 8 | } 9 | -------------------------------------------------------------------------------- /ext-tree/Config.in: -------------------------------------------------------------------------------- 1 | menu "Santa Clone" 2 | source "$BR2_EXTERNAL_SANTA_CLONE_PATH/package/santa_kmod/Config.in" 3 | source "$BR2_EXTERNAL_SANTA_CLONE_PATH/package/rust_santa_daemon/Config.in" 4 | endmenu 5 | -------------------------------------------------------------------------------- /ext-tree/package/santa_kmod/Config.in: -------------------------------------------------------------------------------- 1 | config BR2_PACKAGE_SANTA_KMOD 2 | bool "santa_kmod" 3 | depends on BR2_LINUX_KERNEL 4 | help 5 | Santa clone kernel module component. 6 | -------------------------------------------------------------------------------- /src/rust_santa_daemon/testrules.json: -------------------------------------------------------------------------------- 1 | { 2 | "a92d9b7533984599bb263f703b5968db9a07f49aa6bb416faa535cd781debcbb": "Block", 3 | "f5d5379e0ec9b97813f546bd12029657b7c51135fcd8439bca9333ab1dfdf557": "Allow" 4 | } 5 | -------------------------------------------------------------------------------- /ext-tree/overlay/opt/santa/rules.json: -------------------------------------------------------------------------------- 1 | { 2 | "a92d9b7533984599bb263f703b5968db9a07f49aa6bb416faa535cd781debcbb": "Block", 3 | "f5d5379e0ec9b97813f546bd12029657b7c51135fcd8439bca9333ab1dfdf557": "Allow" 4 | } 5 | -------------------------------------------------------------------------------- /docker/container.sh: -------------------------------------------------------------------------------- 1 | #/usr/bin/env bash 2 | 3 | # drop into a shell in the container 4 | sudo docker run \ 5 | --cpus=12 \ 6 | --rm \ 7 | -it \ 8 | -v "$PWD:/home/builder/santa" \ 9 | santa-clone-builder $1 10 | -------------------------------------------------------------------------------- /ext-tree/package/santa_kmod/santa_kmod.mk: -------------------------------------------------------------------------------- 1 | SANTA_KMOD_VERSION = 1.0 2 | SANTA_KMOD_SITE = "$(BR2_EXTERNAL_SANTA_CLONE_PATH)/../src/santa_kmod" 3 | SANTA_KMOD_SITE_METHOD = local 4 | $(eval $(kernel-module)) 5 | $(eval $(generic-package)) 6 | -------------------------------------------------------------------------------- /src/testbins/testbin.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() { 7 | int pid = getpid(); 8 | printf("- my PID is %d\n", pid); 9 | return 0; 10 | } 11 | -------------------------------------------------------------------------------- /ext-tree/package/rust_santa_daemon/Config.in: -------------------------------------------------------------------------------- 1 | config BR2_PACKAGE_RUST_SANTA_DAEMON 2 | bool "rust_santa_daemon" 3 | depends on BR2_PACKAGE_HOST_RUSTC_ARCH_SUPPORTS 4 | select BR2_PACKAGE_HOST_RUSTC 5 | select BR2_PACKAGE_HOST_CARGO 6 | help 7 | rust version of the Santa daemon package. 8 | -------------------------------------------------------------------------------- /src/santa_kmod/Makefile: -------------------------------------------------------------------------------- 1 | obj-m += $(addsuffix .o, $(notdir $(basename $(wildcard $(PWD)/santa_clone.c)))) 2 | ccflags-y := -DDEBUG -g -std=gnu99 -Wno-declaration-after-statement 3 | 4 | .PHONY: all clean 5 | 6 | all: 7 | $(MAKE) -C '$(LINUX_DIR)' M='$(PWD)' modules 8 | 9 | clean: 10 | $(MAKE) -C '$(LINUX_DIR)' M='$(PWD)' clean 11 | -------------------------------------------------------------------------------- /ext-tree/overlay/etc/inittab: -------------------------------------------------------------------------------- 1 | ::sysinit:/bin/mount -t proc proc /proc 2 | ::sysinit:/bin/mount -o remount,rw / 3 | ::sysinit:/bin/mkdir -p /dev/pts 4 | ::sysinit:/bin/mkdir -p /dev/shm 5 | ::sysinit:/bin/mount -a 6 | ::sysinit:/bin/hostname -F /etc/hostname 7 | ::sysinit:/etc/init.d/rcS 8 | ::respawn:-/bin/sh 9 | ::shutdown:/etc/init.d/rcK 10 | ::shutdown:/sbin/swapoff -a 11 | ::shutdown:/bin/umount -a -r 12 | 13 | -------------------------------------------------------------------------------- /ext-tree/package/rust_santa_daemon/rust_santa_daemon.mk: -------------------------------------------------------------------------------- 1 | RUST_SANTA_DAEMON_VERSION = 1.0 2 | RUST_SANTA_DAEMON_SITE = "$(BR2_EXTERNAL_SANTA_CLONE_PATH)/../src/rust_santa_daemon" 3 | RUST_SANTA_DAEMON_SITE_METHOD = local 4 | 5 | define RUST_SANTA_DAEMON_BUILD_CMDS 6 | cd $(@D) && $(TARGET_CONFIGURE_OPTS) $(PKG_CARGO_ENV) cargo build --release --manifest-path Cargo.toml --locked 7 | endef 8 | 9 | $(eval $(cargo-package)) 10 | -------------------------------------------------------------------------------- /local-build.sh: -------------------------------------------------------------------------------- 1 | #/usr/bin/env bash 2 | BREXT="$PWD/ext-tree" 3 | BRBASE="$PWD/buildroot-2022.08" 4 | BROUT="$PWD/br-output" 5 | 6 | if [ ! -d "$BROUT" ]; then 7 | mkdir $BROUT 8 | fi 9 | 10 | cd $BRBASE 11 | make O="$BROUT" BR2_EXTERNAL="$BREXT" rust-santa-clone-qemu_x86_64_defconfig 12 | cd $BROUT 13 | make -j12 santa_kmod-rebuild 14 | make -j12 all 15 | 16 | echo -E "\n\nDone -- images are under 'br-output/images/'" 17 | -------------------------------------------------------------------------------- /src/rust_santa_daemon/src/libsanta/consts.rs: -------------------------------------------------------------------------------- 1 | // Constants 2 | pub const SANTAD_NAME: &str = "[santa-DAEMON]"; 3 | pub const SANTACTL_NAME: &str = "[santactl]"; 4 | pub const SANTA_BASE_PATH: &str = "/opt/santa"; 5 | pub const RULES_DB_PATH: &str = "/opt/santa/rules.json"; 6 | pub const XPC_SOCKET_PATH: &str = "/opt/santa/santa.xpc"; 7 | pub const XPC_CLIENT_PATH: &str = "/opt/santa/santactl.xpc"; 8 | pub const XPC_SERVER_PATH: &str = "/opt/santa/santad.xpc"; 9 | -------------------------------------------------------------------------------- /src/rust_santa_daemon/src/santa-daemon/tracer.rs: -------------------------------------------------------------------------------- 1 | use nix::sys::ptrace; 2 | use nix::unistd::Pid; 3 | 4 | pub fn attacher(pid: Pid) -> Result { 5 | if let Err(_) = ptrace::attach(pid) { 6 | return Err(format!("Error attaching to process {pid}").to_string()) 7 | } 8 | return Ok(pid) 9 | } 10 | 11 | pub fn detacher(pid: Pid) -> Result<(), String> { 12 | if let Err(_) = ptrace::detach(pid, None) { 13 | return Err(format!("Error detaching from process {pid}").to_string()) 14 | } 15 | return Ok(()) 16 | } -------------------------------------------------------------------------------- /runbuild.sh: -------------------------------------------------------------------------------- 1 | #/usr/bin/env bash 2 | 3 | if [ "$#" != 2 ]; then 4 | echo "usage: $0 " 5 | exit 1 6 | fi 7 | 8 | BUILDLOC="$1" 9 | TARGET="$2" 10 | CORES=$(( $(nproc)-1 )) 11 | 12 | if [ $CORES -gt 12 ]; then 13 | THREADS=$(( $CORES-4 )) 14 | elif [ $CORES -gt 8 && $CORES -lt 12 ]; then 15 | THREADS=$(( $CORES-2 )) 16 | elif [ $CORES -lt 8 ]; then 17 | THREADS=$(( $CORES-1 )) 18 | fi 19 | 20 | cd $BUILDLOC 21 | make -j${THREADS} ${TARGET} 22 | make -j${THREADS} all 23 | 24 | ../qemu-run.sh images 25 | -------------------------------------------------------------------------------- /src/rust_santa_daemon/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "santa-daemon" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [lib] 7 | name = "libsanta" 8 | path = "src/libsanta/lib.rs" 9 | 10 | [[bin]] 11 | name = "santa-daemon" 12 | path = "src/santa-daemon/main.rs" 13 | 14 | [[bin]] 15 | name = "santactl" 16 | path = "src/santactl/main.rs" 17 | 18 | [dependencies] 19 | nix = "0.25.0" 20 | rustc-hash = "1.1.0" 21 | serde_json = "1.0.87" 22 | neli = "0.6.3" 23 | sha2 = "0.10.6" 24 | daemonize = "0.4.1" 25 | serde = { version = "1.0", features = ["derive", "std"] } 26 | clap = { version = "4.0", features = ["derive"] } 27 | -------------------------------------------------------------------------------- /src/santa_kmod/santa_clone.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | // custom define for our protocol 7 | #define NLPOC 30 8 | 9 | // maxlen for symbol targets for probing 10 | #define MAX_SYMBOL_LEN 64 11 | #define MAX_PAYLOAD 1024 12 | 13 | // helper function for printing registers from the probe 14 | static void print_regs(struct pt_regs *regs) 15 | { 16 | // print out registers 17 | pr_info("REGISTERS:\n\t " 18 | "rax: 0x%08lx\n\t rbx: 0x%08lx\n\t rcx: 0x%08lx\n\t rdx: 0x%08lx\n\t " 19 | "rsi: 0x%08lx\n\t rdi: 0x%08lx\n\t r8: %08lx\n\t r9: %08lx\n\n", 20 | regs->ax, regs->bx, regs->cx, regs->dx, 21 | regs->si, regs->di, regs->r8, regs->r9); 22 | } 23 | 24 | -------------------------------------------------------------------------------- /ext-tree/overlay/etc/init.d/S99santa_daemon: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | DAEMON="santa-daemon" 3 | 4 | # and use "-m" to instruct start-stop-daemon to create one. 5 | start() { 6 | printf 'Starting %s: ' "$DAEMON" 7 | export RUST_BACKTRACE=1 8 | /usr/bin/"$DAEMON" -d 9 | status=$? 10 | if [ "$status" -eq 0 ]; then 11 | echo "OK" 12 | else 13 | echo "FAIL" 14 | fi 15 | return "$status" 16 | } 17 | 18 | stop() { 19 | printf 'Stopping %s: ' "$DAEMON" 20 | killall $DAEMON 21 | status=$? 22 | if [ "$status" -eq 0 ]; then 23 | echo "OK" 24 | else 25 | echo "FAIL" 26 | fi 27 | return "$status" 28 | } 29 | 30 | restart() { 31 | stop 32 | sleep 1 33 | start 34 | } 35 | 36 | case "$1" in 37 | start|stop|restart) 38 | "$1";; 39 | reload) 40 | # Restart, since there is no true "reload" feature. 41 | restart;; 42 | *) 43 | echo "Usage: $0 {start|stop|restart|reload}" 44 | exit 1 45 | esac 46 | 47 | -------------------------------------------------------------------------------- /qemu-run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | if [ "$#" != 1 ]; then 4 | echo "usage: $0 " 5 | exit 1 6 | fi 7 | 8 | IMAGE_DIR="$1" 9 | 10 | qemu-system-x86_64 \ 11 | -m 1G \ 12 | -M pc \ 13 | -cpu qemu64 \ 14 | -kernel ${IMAGE_DIR}/bzImage \ 15 | -drive file="${IMAGE_DIR}"/rootfs.ext2,if=virtio,format=raw \ 16 | -append "rw nokaslr panic=1 root=/dev/vda console=tty1 console=ttyS0" \ 17 | -no-reboot \ 18 | -nographic \ 19 | -serial mon:stdio \ 20 | -s \ 21 | -net nic,model=virtio -net user 22 | 23 | -------------------------------------------------------------------------------- /src/rust_santa_daemon/src/libsanta/commands.rs: -------------------------------------------------------------------------------- 1 | use crate::rules::RuleTypes; 2 | use crate::Jsonify; 3 | use std::path::PathBuf; 4 | use serde::{Deserialize, Serialize}; 5 | use clap::Subcommand; 6 | 7 | #[derive(Serialize, Deserialize, Debug, Clone)] 8 | pub enum CommandTypes { 9 | Status, 10 | FileInfo, 11 | Rule, 12 | } 13 | 14 | #[derive(Subcommand, Serialize, Deserialize, Debug, Clone, Copy)] 15 | pub enum RuleAction { 16 | Insert, 17 | Remove, 18 | Show, 19 | } 20 | 21 | #[derive(Serialize, Deserialize, Debug, Clone)] 22 | pub enum RuleCommandInputType { 23 | Path(PathBuf), 24 | Hash(String) 25 | } 26 | 27 | #[derive(Serialize, Deserialize, Debug, Clone)] 28 | pub struct RuleCommand { 29 | pub action: RuleAction, 30 | pub target: RuleCommandInputType, 31 | pub policy: RuleTypes, 32 | } 33 | impl Jsonify for RuleCommand {} 34 | 35 | #[derive(Serialize, Deserialize, Debug, Clone)] 36 | pub struct StatusCommand {} 37 | impl Jsonify for StatusCommand {} 38 | 39 | #[derive(Serialize, Deserialize, Debug, Clone)] 40 | pub struct FileInfoCommand { pub path: PathBuf } 41 | impl Jsonify for FileInfoCommand {} 42 | 43 | #[derive(Serialize, Deserialize, Debug, Clone)] 44 | pub struct SantaCtlCommand { 45 | pub ctype: CommandTypes, 46 | pub command: String, 47 | } 48 | impl Jsonify for SantaCtlCommand {} -------------------------------------------------------------------------------- /ext-tree/configs/rust-santa-clone-qemu_x86_64_defconfig: -------------------------------------------------------------------------------- 1 | BR2_x86_64=y 2 | BR2_TOOLCHAIN_BUILDROOT_GLIBC=y 3 | BR2_PACKAGE_HOST_LINUX_HEADERS_CUSTOM_5_4=y 4 | BR2_PACKAGE_GLIBC_UTILS=y 5 | BR2_TOOLCHAIN_BUILDROOT_CXX=y 6 | BR2_CCACHE=y 7 | # BR2_STRIP_strip is not set 8 | BR2_OPTIMIZE_1=y 9 | BR2_SSP_REGULAR=y 10 | BR2_RELRO_PARTIAL=y 11 | BR2_SYSTEM_BIN_SH_BASH=y 12 | BR2_SYSTEM_DHCP="eth0" 13 | BR2_ROOTFS_OVERLAY="../ext-tree/overlay" 14 | BR2_ROOTFS_POST_BUILD_SCRIPT="board/qemu/x86_64/post-build.sh" 15 | BR2_ROOTFS_POST_IMAGE_SCRIPT="board/qemu/post-image.sh" 16 | BR2_ROOTFS_POST_SCRIPT_ARGS="$(BR2_DEFCONFIG)" 17 | BR2_LINUX_KERNEL=y 18 | BR2_LINUX_KERNEL_CUSTOM_VERSION=y 19 | BR2_LINUX_KERNEL_CUSTOM_VERSION_VALUE="5.4.58" 20 | BR2_LINUX_KERNEL_USE_CUSTOM_CONFIG=y 21 | BR2_LINUX_KERNEL_CUSTOM_CONFIG_FILE="../ext-tree/configs/linux.config" 22 | BR2_LINUX_KERNEL_NEEDS_HOST_OPENSSL=y 23 | BR2_LINUX_KERNEL_NEEDS_HOST_LIBELF=y 24 | BR2_PACKAGE_BUSYBOX_SHOW_OTHERS=y 25 | BR2_PACKAGE_LTRACE=y 26 | BR2_PACKAGE_STRACE=y 27 | BR2_PACKAGE_BINUTILS=y 28 | BR2_PACKAGE_BINUTILS_TARGET=y 29 | BR2_PACKAGE_MAKE=y 30 | BR2_PACKAGE_SED=y 31 | BR2_PACKAGE_GNUTLS=y 32 | BR2_PACKAGE_GNUTLS_OPENSSL=y 33 | BR2_PACKAGE_GNUTLS_TOOLS=y 34 | BR2_PACKAGE_OPENSSL=y 35 | BR2_PACKAGE_LIBEVENT=y 36 | BR2_PACKAGE_BASH_COMPLETION=y 37 | BR2_PACKAGE_FILE=y 38 | BR2_PACKAGE_COREUTILS=y 39 | BR2_PACKAGE_UTIL_LINUX=y 40 | BR2_PACKAGE_VIM=y 41 | BR2_TARGET_ROOTFS_EXT2=y 42 | BR2_TARGET_ROOTFS_EXT2_SIZE="1200M" 43 | # BR2_TARGET_ROOTFS_TAR is not set 44 | BR2_PACKAGE_HOST_QEMU=y 45 | BR2_PACKAGE_HOST_QEMU_SYSTEM_MODE=y 46 | BR2_PACKAGE_SANTA_KMOD=y 47 | BR2_PACKAGE_RUST_SANTA_DAEMON=y 48 | -------------------------------------------------------------------------------- /ext-tree/configs/santa-clone-qemu_x86_64_defconfig: -------------------------------------------------------------------------------- 1 | BR2_x86_64=y 2 | BR2_CCACHE=y 3 | # BR2_STRIP_strip is not set 4 | BR2_OPTIMIZE_1=y 5 | BR2_PIC_PIE=y 6 | BR2_SSP_REGULAR=y 7 | BR2_RELRO_PARTIAL=y 8 | BR2_TOOLCHAIN_BUILDROOT_GLIBC=y 9 | BR2_PACKAGE_HOST_LINUX_HEADERS_CUSTOM_5_4=y 10 | BR2_PACKAGE_GLIBC_UTILS=y 11 | BR2_TOOLCHAIN_BUILDROOT_CXX=y 12 | BR2_SYSTEM_BIN_SH_BASH=y 13 | BR2_SYSTEM_DHCP="eth0" 14 | BR2_ROOTFS_OVERLAY="../ext-tree/overlay" 15 | BR2_ROOTFS_POST_BUILD_SCRIPT="board/qemu/x86_64/post-build.sh" 16 | BR2_ROOTFS_POST_IMAGE_SCRIPT="board/qemu/post-image.sh" 17 | BR2_ROOTFS_POST_SCRIPT_ARGS="$(BR2_DEFCONFIG)" 18 | BR2_LINUX_KERNEL=y 19 | BR2_LINUX_KERNEL_CUSTOM_VERSION=y 20 | BR2_LINUX_KERNEL_CUSTOM_VERSION_VALUE="5.4.58" 21 | BR2_LINUX_KERNEL_USE_CUSTOM_CONFIG=y 22 | BR2_LINUX_KERNEL_CUSTOM_CONFIG_FILE="../ext-tree/configs/linux.config" 23 | BR2_LINUX_KERNEL_NEEDS_HOST_OPENSSL=y 24 | BR2_LINUX_KERNEL_NEEDS_HOST_LIBELF=y 25 | BR2_PACKAGE_BUSYBOX_SHOW_OTHERS=y 26 | BR2_PACKAGE_LTRACE=y 27 | BR2_PACKAGE_STRACE=y 28 | BR2_PACKAGE_BINUTILS=y 29 | BR2_PACKAGE_BINUTILS_TARGET=y 30 | BR2_PACKAGE_MAKE=y 31 | BR2_PACKAGE_SED=y 32 | BR2_PACKAGE_GNUTLS=y 33 | BR2_PACKAGE_GNUTLS_OPENSSL=y 34 | BR2_PACKAGE_GNUTLS_TOOLS=y 35 | BR2_PACKAGE_LIBNFNETLINK=y 36 | BR2_PACKAGE_BASH_COMPLETION=y 37 | BR2_PACKAGE_FILE=y 38 | BR2_PACKAGE_TMUX=y 39 | BR2_PACKAGE_COREUTILS=y 40 | BR2_PACKAGE_UTIL_LINUX=y 41 | BR2_PACKAGE_VIM=y 42 | BR2_TARGET_ROOTFS_EXT2=y 43 | BR2_TARGET_ROOTFS_EXT2_SIZE="1200M" 44 | # BR2_TARGET_ROOTFS_TAR is not set 45 | BR2_PACKAGE_HOST_QEMU=y 46 | BR2_PACKAGE_HOST_QEMU_SYSTEM_MODE=y 47 | BR2_PACKAGE_SANTA_DAEMON=y 48 | BR2_PACKAGE_SANTA_KMOD=y 49 | -------------------------------------------------------------------------------- /docker/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:20.04 2 | ENV TZ=America/Los_Angeles 3 | RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone 4 | 5 | # install dependencies 6 | RUN apt-get update && apt-get install -y --no-install-recommends \ 7 | build-essential \ 8 | bzip2 \ 9 | default-jdk \ 10 | git-core \ 11 | gzip \ 12 | liblzma-dev \ 13 | liblzo2-dev \ 14 | liblzo2-dev \ 15 | ocaml-nox gawk \ 16 | lzop \ 17 | p7zip-full \ 18 | python3 \ 19 | python3-lzo \ 20 | python3-pip \ 21 | squashfs-tools \ 22 | srecord \ 23 | tar \ 24 | unzip \ 25 | perl \ 26 | rsync \ 27 | fakeroot \ 28 | ccache ecj fastjar \ 29 | gettext git java-propose-classpath libelf-dev libncurses5-dev \ 30 | libncursesw5-dev libssl-dev python python2.7-dev \ 31 | python3-setuptools python3-dev rsync subversion \ 32 | gcc-multilib \ 33 | pkg-config \ 34 | wget \ 35 | sudo \ 36 | cpio \ 37 | bc \ 38 | vim \ 39 | tmux \ 40 | zlib1g-dev && \ 41 | apt-get clean && \ 42 | rm -rf /var/lib/apt/lists/* 43 | 44 | # add non-root user required for buildroot 45 | ENV HOME "/home/builder" 46 | RUN useradd -m builder &&\ 47 | echo 'builder ALL=NOPASSWD: ALL' > /etc/sudoers.d/builder 48 | USER builder 49 | 50 | # a place to mount the src code for the module 51 | RUN mkdir -p $HOME/src 52 | 53 | # download buildroot 54 | WORKDIR $HOME 55 | RUN wget -c https://buildroot.org/downloads/buildroot-2022.08.tar.gz -O - | tar -xz 56 | 57 | # this is where images produced by buildroot will be copied for export to the host 58 | # allow to mount an external ext tree here 59 | VOLUME [ "/home/builder/src" ] 60 | 61 | # change to the ext-tree 62 | WORKDIR $HOME/src 63 | ENTRYPOINT [ "/bin/bash" ] 64 | -------------------------------------------------------------------------------- /ext-tree/configs/linux.config: -------------------------------------------------------------------------------- 1 | CONFIG_SYSVIPC=y 2 | CONFIG_CGROUPS=y 3 | CONFIG_NAMESPACES=y 4 | CONFIG_EXPERT=y 5 | # CONFIG_FHANDLE is not set 6 | # CONFIG_BUG is not set 7 | # CONFIG_PCSPKR_PLATFORM is not set 8 | # CONFIG_SHMEM is not set 9 | # CONFIG_AIO is not set 10 | # CONFIG_ADVISE_SYSCALLS is not set 11 | CONFIG_KALLSYMS_ALL=y 12 | CONFIG_BPF_SYSCALL=y 13 | CONFIG_SMP=y 14 | CONFIG_HYPERVISOR_GUEST=y 15 | CONFIG_PARAVIRT=y 16 | CONFIG_KPROBES=y 17 | CONFIG_MODULES=y 18 | CONFIG_MODULE_UNLOAD=y 19 | CONFIG_NET=y 20 | CONFIG_PACKET=y 21 | CONFIG_UNIX=y 22 | CONFIG_INET=y 23 | # CONFIG_WIRELESS is not set 24 | CONFIG_PCI=y 25 | CONFIG_DEVTMPFS=y 26 | CONFIG_DEVTMPFS_MOUNT=y 27 | CONFIG_VIRTIO_BLK=y 28 | CONFIG_BLK_DEV_SD=y 29 | CONFIG_SCSI_VIRTIO=y 30 | CONFIG_ATA=y 31 | CONFIG_ATA_PIIX=y 32 | CONFIG_NETDEVICES=y 33 | CONFIG_VIRTIO_NET=y 34 | CONFIG_NE2K_PCI=y 35 | CONFIG_8139CP=y 36 | # CONFIG_WLAN is not set 37 | CONFIG_INPUT_EVDEV=y 38 | CONFIG_SERIAL_8250=y 39 | CONFIG_SERIAL_8250_CONSOLE=y 40 | CONFIG_VIRTIO_CONSOLE=y 41 | CONFIG_HW_RANDOM_VIRTIO=m 42 | CONFIG_DRM=y 43 | CONFIG_DRM_QXL=y 44 | CONFIG_DRM_BOCHS=y 45 | CONFIG_DRM_VIRTIO_GPU=y 46 | CONFIG_FRAMEBUFFER_CONSOLE=y 47 | CONFIG_SOUND=y 48 | CONFIG_SND=y 49 | CONFIG_SND_HDA_INTEL=y 50 | CONFIG_SND_HDA_GENERIC=y 51 | CONFIG_HID_A4TECH=y 52 | CONFIG_HID_APPLE=y 53 | CONFIG_HID_BELKIN=y 54 | CONFIG_HID_CHERRY=y 55 | CONFIG_HID_CHICONY=y 56 | CONFIG_HID_CYPRESS=y 57 | CONFIG_HID_EZKEY=y 58 | CONFIG_HID_ITE=y 59 | CONFIG_HID_KENSINGTON=y 60 | CONFIG_HID_LOGITECH=y 61 | CONFIG_HID_REDRAGON=y 62 | CONFIG_HID_MICROSOFT=y 63 | CONFIG_HID_MONTEREY=y 64 | CONFIG_USB=y 65 | CONFIG_USB_XHCI_HCD=y 66 | CONFIG_USB_EHCI_HCD=y 67 | CONFIG_USB_UHCI_HCD=y 68 | CONFIG_USB_STORAGE=y 69 | CONFIG_VIRTIO_PCI=y 70 | CONFIG_VIRTIO_BALLOON=y 71 | CONFIG_VIRTIO_INPUT=y 72 | CONFIG_VIRTIO_MMIO=y 73 | CONFIG_VIRTIO_MMIO_CMDLINE_DEVICES=y 74 | CONFIG_EXT4_FS=y 75 | CONFIG_AUTOFS4_FS=y 76 | CONFIG_FUNCTION_TRACER=y 77 | CONFIG_PREEMPTIRQ_EVENTS=y 78 | CONFIG_FTRACE_SYSCALLS=y 79 | CONFIG_BPF_KPROBE_OVERRIDE=y 80 | CONFIG_UNWINDER_FRAME_POINTER=y 81 | -------------------------------------------------------------------------------- /src/rust_santa_daemon/src/libsanta/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod uxpc; 2 | pub mod commands; 3 | pub mod consts; 4 | pub mod engine_types; 5 | pub mod rules; 6 | 7 | use std::fmt; 8 | use serde::Serialize; 9 | use serde_json::json; 10 | use consts::{SANTACTL_NAME, SANTAD_NAME}; 11 | use sha2::{Sha256, Digest}; 12 | use std::{fs, io}; 13 | use std::path::PathBuf; 14 | 15 | 16 | /// SantaMode Enum 17 | #[derive(Clone, Copy)] 18 | pub enum SantaMode { 19 | Lockdown, 20 | Monitor, 21 | } 22 | 23 | impl fmt::Display for SantaMode { 24 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 25 | match self { 26 | SantaMode::Lockdown => write!(f, "Lockdown"), 27 | SantaMode::Monitor => write!(f, "Monitor"), 28 | } 29 | } 30 | } 31 | 32 | /// Trait for types that support being json-ified to simplify doing so. 33 | pub trait Jsonify: Serialize { 34 | fn jsonify(&self) -> String { 35 | let js = json!(self); 36 | js.to_string() 37 | } 38 | 39 | fn jsonify_pretty(&self) -> String { 40 | serde_json::to_string_pretty(self) 41 | .unwrap_or(self.jsonify()) 42 | } 43 | } 44 | 45 | pub trait Loggable { 46 | fn log(&self, src: LoggerSource); 47 | } 48 | 49 | pub enum LoggerSource { 50 | SantaDaemon, 51 | SantaCtl, 52 | } 53 | impl ToString for LoggerSource { 54 | fn to_string(&self) -> String { 55 | match self { 56 | LoggerSource::SantaCtl => String::from(SANTACTL_NAME), 57 | LoggerSource::SantaDaemon => String::from(SANTAD_NAME), 58 | } 59 | } 60 | } 61 | 62 | 63 | /// Calculate the SHA256 hash of the file given in `target` 64 | pub fn hash_file_at_path(target: &PathBuf) -> Option { 65 | // sanity check to make sure file exists 66 | if !target.exists() { return None } 67 | // open the file 68 | let mut file = match fs::File::open(&target) { 69 | Ok(f) => f, 70 | Err(_) => return None, 71 | }; 72 | 73 | // hash file via Read object, avoid reading the entire file into memory 74 | let mut hasher = Sha256::new(); 75 | if let Err(_) = io::copy(&mut file, &mut hasher) { 76 | return None 77 | } 78 | // finalize the calculation (consumes the hasher instance) 79 | let hash_bytes = hasher.finalize(); 80 | // we're done 81 | Some(String::from(format!("{:x}", hash_bytes))) 82 | } -------------------------------------------------------------------------------- /src/rust_santa_daemon/src/libsanta/uxpc.rs: -------------------------------------------------------------------------------- 1 | use std::os::unix::net::UnixStream; 2 | use std::os::unix::net::UnixListener; 3 | use std::io::prelude::*; 4 | use std::io::{Error, ErrorKind}; 5 | use std::path::Path; 6 | 7 | /// A server-side Unix socket 8 | pub struct SantaXpcServer { 9 | rx: UnixListener, 10 | } 11 | impl SantaXpcServer { 12 | pub fn new(path: &str, nonblocking: bool) -> SantaXpcServer { 13 | // set up the socket for receiving commands 14 | let rx_sockpath = Path::new(&path); 15 | // delete old socket if it exists 16 | if rx_sockpath.exists() { 17 | std::fs::remove_file(rx_sockpath).expect("should be able to delete file"); 18 | } 19 | // bind the rx socket 20 | let rx = match UnixListener::bind(rx_sockpath) { 21 | Err(_) => panic!("failed to bind santactl xpc listener socket: {path}"), 22 | Ok(socket) => socket, 23 | }; 24 | // set the socket to non-blocking 25 | rx.set_nonblocking(nonblocking).expect("Couldn't set xpc socket to non-blocking"); 26 | 27 | SantaXpcServer {rx} 28 | } 29 | 30 | // the socket should be non-blocking so we'll either get a connection 31 | // or move on and try again on the next iteration 32 | pub fn recv(&self) -> Option { 33 | if let Ok((mut client, _)) = self.rx.accept() { 34 | let mut data = String::new(); 35 | match client.read_to_string(&mut data) { 36 | Ok(_) => return Some(data), 37 | Err(_) => { 38 | eprintln!("failed to parse message to string"); 39 | return None 40 | } 41 | } 42 | } else { 43 | None 44 | } 45 | } 46 | } 47 | 48 | /// A client-side Unix socket 49 | pub struct SantaXpcClient { 50 | tx: UnixStream, // where we send messages 51 | } 52 | 53 | impl SantaXpcClient { 54 | pub fn new(path: &str) -> SantaXpcClient { 55 | // set up the socket connection for sending responses? 56 | let sockpath = std::path::Path::new(&path); 57 | // connect the socket 58 | let tx = match UnixStream::connect(sockpath) { 59 | Ok(asdf) => {asdf}, 60 | Err(_) => panic!("couldn't connect to daemon socket, is it running?"), 61 | }; 62 | // set the socket to non-blocking 63 | tx.set_nonblocking(true).expect("Couldn't set xpc socket to non-blocking"); 64 | 65 | // return sock 66 | SantaXpcClient {tx} 67 | } 68 | 69 | pub fn send(&mut self, msg: &[u8]) -> std::io::Result<()> { 70 | if msg.len() > 1023 { 71 | let err = Error::new(ErrorKind::InvalidInput, 72 | "Message too long, not sending (limit is 1024 bytes)"); 73 | return Err(err) 74 | } 75 | 76 | // send the message 77 | self.tx.write_all(msg).unwrap(); 78 | Ok(()) 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/rust_santa_daemon/src/santa-daemon/engine.rs: -------------------------------------------------------------------------------- 1 | // std imports 2 | 3 | use nix::sys::signal; 4 | use nix::unistd::Pid; 5 | 6 | // local imports 7 | use crate::SantaMode; 8 | use libsanta::rules::RulesDb; 9 | use libsanta::engine_types::{ 10 | HashState, 11 | PolicyDecision, 12 | PolicyDecisionReason, 13 | PolicyEngineResult, 14 | }; 15 | 16 | /// PolicyEngine struct 17 | pub struct SantaEngine { 18 | pub mode: SantaMode, 19 | pub rules: RulesDb, 20 | } 21 | // impl Jsonify for HashMap {} 22 | 23 | /// PolicyEngine implementation 24 | impl SantaEngine { 25 | pub fn new(mode: SantaMode) -> SantaEngine { 26 | SantaEngine{ 27 | mode, 28 | rules: RulesDb::new(), 29 | } 30 | } 31 | 32 | /// Sync the daemon's ruleset back to the rules db file 33 | #[allow(dead_code)] 34 | fn sync_rules(&self) { 35 | // write_json_to_file(&self.rules, RULES_DB_PATH) 36 | } 37 | 38 | /// Check the rules database for the given hash and return a PolicyDecision based on the 39 | /// result. 40 | fn decision_from_hash_state(&self, state: &HashState) -> PolicyDecision { 41 | match state { 42 | HashState::HashOk => PolicyDecision::Allow, 43 | HashState::HashBlock => PolicyDecision::Block, 44 | HashState::HashUnknown => { 45 | PolicyDecision::from(self.mode) 46 | }, 47 | } 48 | } 49 | 50 | /// Determine a state for the given hash based on whether its on the allowlist, blocklist, or 51 | /// unknown. 52 | #[allow(dead_code)] 53 | fn hash_state(&self, hash: &str) -> HashState { 54 | match self.rules.0.get(hash).copied() { 55 | // A rule exists, return a decision based on the rule 56 | Some(rule) => return HashState::from(rule), 57 | // No rule found, decide based on the current mode 58 | None => return HashState::HashUnknown, 59 | }; 60 | } 61 | 62 | pub fn decide(&self, hash: &str) -> PolicyEngineResult { 63 | match self.rules.0.get(hash).copied() { 64 | // A rule exists, return a decision based on the rule 65 | Some(rule) => { 66 | let state = HashState::from(rule); 67 | let dec = self.decision_from_hash_state(&state); 68 | let reason = PolicyDecisionReason::from(state); 69 | return PolicyEngineResult {filepath: "".to_string(), hash: hash.to_string(), decision: dec, reason} 70 | } 71 | // No rule found, decide based on the current mode 72 | None => { 73 | let state = HashState::HashUnknown; 74 | let dec = self.decision_from_hash_state(&state); 75 | let reason = PolicyDecisionReason::from(state); 76 | return PolicyEngineResult {filepath: "".to_string(), hash: hash.to_string(), decision: dec, reason} 77 | } 78 | }; 79 | } 80 | 81 | /// Kill a target process by PID 82 | pub fn kill(&self, pid: i32) { 83 | let target_pid = Pid::from_raw(pid); 84 | if let Err(_) = signal::kill(target_pid, signal::SIGKILL) { 85 | eprintln!("Error sending SIGKILL to process with pid {pid}") 86 | } 87 | } 88 | } 89 | 90 | -------------------------------------------------------------------------------- /src/rust_santa_daemon/src/santa-daemon/cache.rs: -------------------------------------------------------------------------------- 1 | use std::fs; 2 | use std::collections::VecDeque; 3 | use std::time::SystemTime; 4 | use std::error::Error; 5 | use std::os::linux::fs::MetadataExt; 6 | 7 | use rustc_hash::FxHashMap; 8 | 9 | /// SantaCacheSignature 10 | #[derive(Clone, Eq, PartialEq)] 11 | pub struct CacheSignature { 12 | // pub filepath: String, 13 | pub inode: u64, 14 | pub last_mod: u64, 15 | pub created: u64, 16 | } 17 | impl ToString for CacheSignature { 18 | fn to_string(&self) -> String { 19 | let uniq_sig = format!("{}||{}||{}",self.last_mod, self.inode, self.created); 20 | String::from(&uniq_sig) 21 | } 22 | } 23 | 24 | // CacheSignature implementation 25 | impl CacheSignature { 26 | pub fn new(filepath: &str) -> Result> { 27 | // get file metadata for signature 28 | let meta = fs::metadata(filepath).expect("should be able to read file"); 29 | // mod time 30 | let last_mod = meta.modified()? 31 | .duration_since(SystemTime::UNIX_EPOCH)? 32 | .as_secs(); 33 | // created 34 | let created = meta.created()? 35 | .duration_since(SystemTime::UNIX_EPOCH)? 36 | .as_secs(); 37 | // inode 38 | let inode = meta.st_ino(); 39 | 40 | Ok(CacheSignature { 41 | inode, 42 | last_mod, 43 | created, 44 | }) 45 | } 46 | } 47 | 48 | 49 | #[derive(Clone, Eq, PartialEq)] 50 | /// SantaCache struct 51 | pub struct SantaCache { 52 | // this is the actual cache that will be searched against 53 | buffer: FxHashMap, 54 | // each time we insert a new item into the hashmap, push its key to the back of this vec. 55 | keyvec: VecDeque, 56 | // max size of the cache 57 | capacity: usize, 58 | } 59 | 60 | 61 | /// SantaCache: a cache to hold the hashes of the most recently hashed files to avoid having to do 62 | /// the (expensive) hashing operation on each exectution. A unique signature is created using file metadata 63 | /// (inode, last modified time, etc) to use as a key into the cache. The cache has a max capacity, at which 64 | /// point the oldest item in the cache is removed during each subsequent insert. 65 | impl SantaCache { 66 | /// Create a new SantaCache instance with a given max capacity 67 | pub fn new(capacity: usize) -> SantaCache { 68 | SantaCache { 69 | buffer: FxHashMap::default(), 70 | keyvec: VecDeque::with_capacity(capacity), 71 | capacity, 72 | } 73 | } 74 | 75 | /// Get the current number of items in the cache 76 | pub fn len(&self) -> usize { 77 | self.buffer.len() 78 | } 79 | 80 | /// Search the cache for the given key 81 | pub fn find(&self, sig: &str) -> Option<&String> { 82 | self.buffer.get(sig) 83 | } 84 | 85 | /// Insert an item into the cache, taking care of managing the queue and removing entries as 86 | /// needed. 87 | pub fn insert(&mut self, sig: String, hash: String) { 88 | // println!("Inserting into cache: {sig}"); 89 | // push the signature onto the keyvec. 90 | self.keyvec.push_back(sig.clone()); 91 | 92 | // insert the entry onto the hashmap 93 | self.buffer.entry(sig.clone()).or_insert_with(|| hash.clone()); 94 | 95 | // we have to know whether we need to remove entries 96 | if self.keyvec.len() == self.capacity { 97 | // pop the oldest signature from the front of the queue 98 | let remove_key = self.keyvec.pop_front().unwrap_or("".to_string()); 99 | 100 | // now we use the key we popped from the keyvec to remove the hashmap entry 101 | self.buffer.remove(&remove_key); 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/rust_santa_daemon/src/santa-daemon/daemon.rs: -------------------------------------------------------------------------------- 1 | use std::path::Path; 2 | use std::error::Error; 3 | use libsanta::{ 4 | hash_file_at_path, 5 | consts::{SANTA_BASE_PATH, XPC_SOCKET_PATH}, 6 | SantaMode, 7 | uxpc::SantaXpcServer, 8 | engine_types::{PolicyEnginePathTarget, PolicyEngineResult, PolicyDecision, PolicyDecisionReason, PolicyEngineStatus}, 9 | }; 10 | 11 | use crate::{engine::{SantaEngine}, cache::{CacheSignature, SantaCache}}; 12 | use crate::netlink::{NetlinkAgent, NlSantaCommand}; 13 | 14 | /// SantaDaemon object 15 | pub struct SantaDaemon { 16 | pub netlink: NetlinkAgent, 17 | pub engine: SantaEngine, 18 | pub xpc_rx: SantaXpcServer, 19 | pub cache: SantaCache, 20 | } 21 | 22 | /// A SantaDaemon instance 23 | impl SantaDaemon { 24 | pub fn new(mode: SantaMode) -> Result> { 25 | // ensure the /opt/santa directory exists 26 | let santa_base = Path::new(SANTA_BASE_PATH); 27 | if !santa_base.exists() { 28 | std::fs::create_dir_all(santa_base)?; 29 | } 30 | 31 | let mut daemon = SantaDaemon { 32 | netlink: NetlinkAgent::new(Some(0), &[])?, 33 | engine: SantaEngine::new(mode), 34 | xpc_rx: SantaXpcServer::new(XPC_SOCKET_PATH, true), 35 | cache: SantaCache::new(1000), 36 | }; 37 | daemon.init()?; 38 | Ok(daemon) 39 | } 40 | 41 | /// Get engine status 42 | pub fn status(&self) -> PolicyEngineStatus { 43 | let rule_count = self.engine.rules.0.len(); 44 | let cache_count = self.cache.len(); 45 | let mode = format!("{}", self.engine.mode); 46 | PolicyEngineStatus { mode, rule_count, cache_count } 47 | } 48 | 49 | /// Return a PolicyDecision for the target pointed to by PolicyEnginePathTarget, only performing 50 | /// a hashing operation if the target's signature is not in the hash cache. 51 | pub fn check(&mut self, target: &PolicyEnginePathTarget) -> PolicyEngineResult { 52 | // normalize the path and return it as a string 53 | let filepath = target.canonical_string(); 54 | 55 | // calculate a signature using file metadata 56 | let uniq_sig = match CacheSignature::new(&target.path_string()) { 57 | // Skip using the cache if we were unable to generate a cache signature 58 | Err(_) => { 59 | // do the hash operation 60 | let hash: String = match hash_file_at_path(&target.path()) { 61 | None => { 62 | eprintln!("failed to hash file at path"); 63 | let decision = PolicyDecision::from(self.engine.mode); 64 | let reason = PolicyDecisionReason::Error; 65 | return PolicyEngineResult { filepath, hash: "".to_string(), decision, reason } 66 | }, 67 | Some(h) => h, 68 | }; 69 | 70 | // make a decision 71 | let mut pres = self.engine.decide(&hash); 72 | pres.filepath = filepath; 73 | return pres 74 | } 75 | Ok(s) => {s}, 76 | }; 77 | 78 | 79 | // check if the signature is in the cache 80 | match self.cache.find(&uniq_sig.to_string()) { 81 | // Cache Hit 82 | Some(hash) => { 83 | // return the result 84 | let mut res = self.engine.decide(&hash); 85 | res.filepath = filepath; 86 | return res 87 | // PolicyEngineResult { filepath, hash: String::from(hash), decision, reason } 88 | }, 89 | None => { 90 | // do the hash operation 91 | let hash: String = match hash_file_at_path(&target.path()) { 92 | None => { 93 | eprintln!("failed to hash file at path"); 94 | let decision = PolicyDecision::from(self.engine.mode); 95 | let reason = PolicyDecisionReason::Error; 96 | return PolicyEngineResult { filepath, hash: "".to_string(), decision, reason } 97 | }, 98 | Some(h) => h, 99 | }; 100 | self.cache.insert(uniq_sig.to_string(), hash.clone()); 101 | let mut res = self.engine.decide(&hash); 102 | res.filepath = filepath; 103 | return res 104 | } 105 | } 106 | } 107 | 108 | /// Initialize the daemon 109 | fn init(&mut self) -> Result<(), Box> { 110 | // Check in with the kernel 111 | self.checkin()?; 112 | 113 | // NOTE: the daemon's netlink socket is set to be nonblocking so that both 114 | // the netlink socket and the unix xpc socket can be processed without 115 | // blocking each other. 116 | self.set_nonblocking(); 117 | Ok(()) 118 | } 119 | 120 | /// Set the netlink socket to non-blocking 121 | fn set_nonblocking(&mut self) { 122 | if let Err(_) = self.netlink.socket.nonblock() { 123 | eprintln!("SantaDaemon failed to set netlink socket to nonblocking") 124 | } 125 | } 126 | 127 | /// Do check-in with the kernel module 128 | fn checkin(&mut self) -> Result<(), Box> { 129 | self.netlink.send_cmd(&NlSantaCommand::MsgCheckin, &"")?; 130 | self.netlink.recv()?; 131 | Ok(()) 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/rust_santa_daemon/src/libsanta/engine_types.rs: -------------------------------------------------------------------------------- 1 | // std imports 2 | use std::path::PathBuf; 3 | use serde::{Deserialize, Serialize}; 4 | 5 | // local imports 6 | use crate::{SantaMode, Jsonify, Loggable, LoggerSource}; 7 | use crate::rules::RuleTypes; 8 | 9 | /// HashState 10 | #[derive(Clone, Copy)] 11 | pub enum HashState { 12 | HashOk, 13 | HashBlock, 14 | HashUnknown, 15 | } 16 | /// Derive a HashState from a PolicyRule 17 | impl From for HashState { 18 | fn from(s: RuleTypes) -> HashState { 19 | match s { 20 | RuleTypes::Allow => HashState::HashOk, 21 | RuleTypes::Block => HashState::HashBlock, 22 | } 23 | } 24 | } 25 | 26 | 27 | /// PolicyDecisionReason: the reason for a given policy decision 28 | #[derive(Serialize, Deserialize, Clone, Copy, Debug)] 29 | pub enum PolicyDecisionReason { 30 | AllowListed, 31 | BlockListed, 32 | Unknown, 33 | Error, 34 | } 35 | /// Derive a PolicyDecisionReason from a HashState 36 | impl From for PolicyDecisionReason { 37 | fn from(s: HashState) -> PolicyDecisionReason { 38 | match s { 39 | HashState::HashOk => PolicyDecisionReason::AllowListed, 40 | HashState::HashBlock => PolicyDecisionReason::BlockListed, 41 | HashState::HashUnknown => PolicyDecisionReason::Unknown, 42 | } 43 | } 44 | } 45 | /// Implement ToString trait for PolicyDecisionReason 46 | impl ToString for PolicyDecisionReason { 47 | fn to_string(&self) -> String { 48 | match self { 49 | PolicyDecisionReason::AllowListed => String::from("allowlisted"), 50 | PolicyDecisionReason::BlockListed => String::from("blocklisted"), 51 | PolicyDecisionReason::Unknown => String::from("unknown binary"), 52 | PolicyDecisionReason::Error => String::from("ERROR"), 53 | } 54 | } 55 | } 56 | 57 | 58 | /// PolicyDecision: an enum for the different decisions the policy engine will return 59 | #[derive(Serialize, Deserialize, Clone, Copy, Eq, PartialEq, Debug)] 60 | pub enum PolicyDecision { 61 | Allow, 62 | Block, 63 | } 64 | /// Convert a PolicyDecision to String 65 | impl ToString for PolicyDecision { 66 | fn to_string(&self) -> String { 67 | match self { 68 | PolicyDecision::Allow => String::from("ALLOW"), 69 | PolicyDecision::Block => String::from("BLOCK"), 70 | } 71 | } 72 | } 73 | /// Derive a PolicyDecision from a PolicyRule 74 | impl From for PolicyDecision { 75 | fn from(s: RuleTypes) -> PolicyDecision { 76 | match s { 77 | RuleTypes::Allow => PolicyDecision::Allow, 78 | RuleTypes::Block => PolicyDecision::Block, 79 | } 80 | } 81 | } 82 | /// Derive a policy decision from a SantaMode 83 | impl From for PolicyDecision { 84 | fn from(s: SantaMode) -> PolicyDecision { 85 | match s { 86 | SantaMode::Monitor => PolicyDecision::Allow, 87 | SantaMode::Lockdown => PolicyDecision::Block, 88 | } 89 | } 90 | } 91 | // Derive a PolicyDecision from a HashState 92 | 93 | 94 | /// PolicyEngineResult 95 | #[derive(Deserialize, Serialize, Debug, Clone)] 96 | pub struct PolicyEngineResult { 97 | pub filepath: String, 98 | pub hash: String, 99 | pub decision: PolicyDecision, 100 | pub reason: PolicyDecisionReason, 101 | } 102 | /// PolicyEngineResult logging method 103 | impl Loggable for PolicyEngineResult { 104 | fn log(&self, src: LoggerSource) { 105 | println!("{}: {} ({}) {} -> {}", 106 | src.to_string(), 107 | self.reason.to_string(), 108 | self.decision.to_string(), 109 | self.filepath, 110 | self.hash); 111 | } 112 | } 113 | /// Implement Jsonify trait for PolicyEngineResult 114 | impl Jsonify for PolicyEngineResult {} 115 | 116 | 117 | /// PolicyEngineStatus: A struct describing the current status of the PolicyEngine 118 | #[derive(Deserialize, Serialize, Debug, Clone)] 119 | pub struct PolicyEngineStatus { 120 | pub mode: String, 121 | pub rule_count: usize, 122 | pub cache_count: usize, 123 | } 124 | /// Implement Jsonify trait for PolicyEngineStatus 125 | impl Jsonify for PolicyEngineStatus {} 126 | 127 | 128 | /// PolicyEngineRuleTarget: ffff that represents the different types of rule targets 129 | pub enum PolicyEngineRuleTarget { 130 | Path(PathBuf), 131 | ShaHash(String), 132 | } 133 | 134 | /// PolicyEnginePathTarget: Enum that represents the different path-based targets used by 135 | /// the policy engine. 136 | pub enum PolicyEnginePathTarget { 137 | PidExePath(u32), 138 | FilePath(PathBuf), 139 | } 140 | // From trait to output a PolicyEnginePathTarget::PidExePath when provided a u32 141 | impl From for PolicyEnginePathTarget { 142 | fn from(n: u32) -> Self { 143 | PolicyEnginePathTarget::PidExePath(n) 144 | } 145 | } 146 | // From trait to output a PolicyEnginePathTarget::FilePath when provided a String 147 | impl From for PolicyEnginePathTarget { 148 | fn from(n: PathBuf) -> Self { 149 | PolicyEnginePathTarget::FilePath(n) 150 | } 151 | } 152 | // PolicyEnginePathTarget implementation 153 | impl PolicyEnginePathTarget { 154 | pub fn path_string(&self) -> String { 155 | match self { 156 | PolicyEnginePathTarget::PidExePath(pid) => format!("/proc/{pid}/exe"), 157 | PolicyEnginePathTarget::FilePath(path) => String::from(format!("{}", path.display())), 158 | } 159 | } 160 | 161 | pub fn path(&self) -> PathBuf { 162 | match self { 163 | PolicyEnginePathTarget::PidExePath(pid) => PathBuf::from(format!("/proc/{pid}/exe")), 164 | PolicyEnginePathTarget::FilePath(path) => PathBuf::from(path), 165 | } 166 | } 167 | 168 | #[allow(dead_code)] 169 | pub fn canonical(&self) -> PathBuf { 170 | match self.path().canonicalize() { 171 | Ok(x) => x, 172 | Err(_) => self.path(), 173 | } 174 | } 175 | 176 | pub fn canonical_string(&self) -> String { 177 | match self.path().canonicalize() { 178 | Ok(x) => { 179 | if let Some(f) = x.to_str() { 180 | return String::from(f) 181 | } else { 182 | return self.path_string() 183 | } 184 | } 185 | Err(_) => { 186 | return self.path_string() 187 | }, 188 | } 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /src/rust_santa_daemon/src/santa-daemon/netlink.rs: -------------------------------------------------------------------------------- 1 | use std::process; 2 | use std::error::Error; 3 | 4 | pub const NL_SANTA_PROTO: u8 = 30; 5 | pub const NL_SANTA_FAMILY_NAME: &str = "gnl_santa"; 6 | 7 | use neli::{ 8 | neli_enum, 9 | consts::{nl::*, socket::*}, 10 | genl::{Genlmsghdr, Nlattr}, 11 | nl::{Nlmsghdr, NlPayload}, 12 | socket::NlSocketHandle, 13 | types::{Buffer, GenlBuffer}, 14 | }; 15 | 16 | 17 | /// Enum of known commands that have been registered for operations with the kernel module. 18 | /// This corresponds to the GNL_SANTA_ATTRIBUTE enum on the kernel side. 19 | #[neli_enum(serialized_type = "u8")] 20 | pub enum NlSantaCommand { 21 | Unspec = 0, 22 | // We expect MSG commands to have NlSantaAttribute:Msg 23 | Msg = 1, // Generic message type (string) 24 | MsgCheckin = 2, // Checkin from agent (string) 25 | MsgDoHash = 3, // Checkin from agent (string) 26 | MsgHashDone = 4,// Agent finished hash operation 27 | ReplyWithNlmsgErr = 5, 28 | } 29 | // Implement necessary trait for the neli lib on the NlSantaCommand enum. 30 | impl neli::consts::genl::Cmd for NlSantaCommand{} 31 | 32 | 33 | /// Enum of known netlink attributes that have been defined for operations with the kernel module. 34 | /// This corresponds to the GNL_SANTA_ATTRIBUTE enum on the kernel side. 35 | #[neli_enum(serialized_type = "u16")] 36 | pub enum NlSantaAttribute { 37 | Unspec = 0, 38 | // We expect MSG attributes to be NULL terminated C strings 39 | Msg = 1, 40 | } 41 | // Implement necessary trait for the neli lib on the NlSantaAttribute enum. 42 | impl neli::consts::genl::NlAttrType for NlSantaAttribute{} 43 | 44 | 45 | /// Netlink socket wrapper object with send and recv methods 46 | pub struct NetlinkAgent { 47 | pub family_id: u16, 48 | pub socket: NlSocketHandle, 49 | pub groups: Vec, 50 | } 51 | 52 | /// NetlinkAgent implementation. 53 | impl NetlinkAgent { 54 | /// Create a new instance of a NetlinkAgent. 55 | pub fn new(pid: Option, groups: &[u32]) -> Result> { 56 | // create and bind the socket 57 | let mut socket = NlSocketHandle::connect( 58 | NlFamily::Generic, 59 | pid, 60 | groups, 61 | )?; 62 | 63 | // resolve family ID 64 | let family_id = socket.resolve_genl_family(NL_SANTA_FAMILY_NAME)?; 65 | 66 | Ok(NetlinkAgent { family_id, socket, groups: Vec::from(groups) }) 67 | } 68 | 69 | /// Send a specific `NlSantaCommand` and message payload via Netlink; the socket handle passed 70 | /// in should already be initialized and bound using `NlSocketHandle::connect()`. 71 | pub fn send_cmd(&mut self, command: &NlSantaCommand, 72 | msg_data: &str) -> Result<(), Box> { 73 | // set up attributes + payload 74 | let mut attrs: GenlBuffer = GenlBuffer::new(); 75 | attrs.push( 76 | Nlattr::new( 77 | false, 78 | false, 79 | // the attribute in which the data will be stored 80 | NlSantaAttribute::Msg, 81 | // the actual payload data 82 | msg_data, 83 | )?, 84 | ); 85 | 86 | // The generic netlink header, contains the attributes (actual data) as payload. 87 | let genlhdr = Genlmsghdr::new( 88 | // the custom command we've defined in NlSantaCommand 89 | command.clone(), 90 | // this is the custom protocol version, application specific 91 | NL_SANTA_PROTO, 92 | // contains the actual payload data 93 | attrs, 94 | ); 95 | 96 | // Construct the Nlmsghdr struct that will be passed to send(). 97 | let nlhdr = { 98 | let len = None; 99 | let nl_type = self.family_id; 100 | let flags = NlmFFlags::new(&[NlmF::Request]); 101 | let seq = None; 102 | let pid = Some(process::id()); 103 | let payload = NlPayload::Payload(genlhdr); 104 | Nlmsghdr::new(len, nl_type, flags, seq, pid, payload) 105 | }; 106 | 107 | // Send the request 108 | self.socket.send(nlhdr)?; 109 | Ok(()) 110 | } 111 | 112 | /// Receive a netlink message using the opened socket 113 | pub fn recv(&mut self) 114 | -> Result, String> { 115 | // If the socket is in non-blocking mode the Result'ing Option may be None if no 116 | // data could be immediately read from the socket, which isn't an issue. In blocking 117 | // mode, the Result will either be Some(Nlmsghdr) or NlError; errors are an issue regardless 118 | // of the blocking context. 119 | match self.socket.recv() { 120 | Ok(msg) => { 121 | let mess: Option>> = msg; 122 | match mess { 123 | // Some means we were able to read a message from the socket 124 | Some(x) => { 125 | if let Ok(pay) = x.get_payload() { 126 | let cmd: NlSantaCommand = pay.cmd; 127 | let attr_handle = pay.get_attr_handle(); 128 | let x = attr_handle.get_attr_payload_as_with_len::(NlSantaAttribute::Msg); 129 | if let Ok(payload) = x { 130 | return Ok(Some((cmd, payload))) 131 | } else { 132 | return Err("failed to parse payload from the attr".to_string()) 133 | } 134 | } else { 135 | return Err("failed to get payload from nlmsgh header".to_string()) 136 | } 137 | } 138 | // None means a message couldn't be immediately read from the socket, which is okay 139 | // since the netlink socket it set to be non-blocking; we just move on and try to read again 140 | // on the next iteration 141 | None => { 142 | return Ok(None) 143 | } 144 | } 145 | }, 146 | Err(e) => { 147 | let err = format!("error on netlink recv: {e}"); 148 | Err(err.to_string()) 149 | } 150 | } 151 | } 152 | } 153 | 154 | 155 | -------------------------------------------------------------------------------- /src/rust_santa_daemon/src/libsanta/rules.rs: -------------------------------------------------------------------------------- 1 | // std imports 2 | use std::fmt; 3 | use std::fs; 4 | use std::path::PathBuf; 5 | use clap::ValueEnum; 6 | use serde::{Deserialize, Serialize}; 7 | 8 | use rustc_hash::FxHashMap; 9 | 10 | // local imports 11 | use crate::Jsonify; 12 | use crate::commands::RuleCommandInputType; 13 | use crate::consts::{SANTAD_NAME, RULES_DB_PATH, SANTA_BASE_PATH}; 14 | use crate::engine_types::PolicyDecision; 15 | use crate::hash_file_at_path; 16 | 17 | 18 | /// Read the default rules database file 19 | fn read_rules_db_file() -> Result, String> { 20 | // Read the file 21 | if let Ok(rules_json) = fs::read_to_string(RULES_DB_PATH) { 22 | // Read the JSON contents of the file as a hashmap. 23 | let rules = serde_json::from_str(&rules_json); 24 | if let Ok(rules_json) = rules { 25 | return Ok(rules_json) 26 | } else { 27 | let msg = format!("{SANTAD_NAME}: Failed to parse JSON to hashmap"); 28 | eprintln!("{}", msg.to_string()); 29 | Err(msg.to_string()) 30 | } 31 | // Something went wrong 32 | } else { 33 | let msg = format!("{SANTAD_NAME}: Failed to read file to string: {RULES_DB_PATH}"); 34 | eprintln!("{}", msg); 35 | Err(msg.to_string()) 36 | } 37 | } 38 | 39 | /// Write a RuleDb instance out to the default rules path 40 | fn write_json_to_file(rules: &J, path: &str) { 41 | // do some checks to be sure parent dirs all exist before we do fs::write() 42 | let filepath = PathBuf::from(path); 43 | if !filepath.exists() { 44 | // this expect is safe because the try_exists() call would return true if path was "/" 45 | // (which is the only path that would cause the parent() call to fail) 46 | let parent = filepath.parent().expect("path should not be /"); 47 | if !parent.exists() { 48 | if let Err(_) = std::fs::create_dir_all(parent) { 49 | eprintln!("{SANTAD_NAME}: Could not create directory at {}", parent.display()); 50 | } 51 | } 52 | 53 | } 54 | // serialize the rules to pretty json and write to the file 55 | let current_rules_json = format!("{}\n", rules.jsonify_pretty()); 56 | // this expect is safe because parent dirs that didn't exist should have been created above 57 | fs::write(path, current_rules_json).expect("parent dirs should exist"); 58 | } 59 | 60 | /// PolicyRule: an emum for the different type of rules that can exist 61 | #[derive(Deserialize, Serialize, Debug, Clone, Copy, ValueEnum)] 62 | pub enum RuleTypes { 63 | Allow, 64 | Block, 65 | } 66 | /// Display trait for PolicyRule 67 | impl fmt::Display for RuleTypes { 68 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 69 | match self { 70 | RuleTypes::Allow => write!(f, "ALLOW"), 71 | RuleTypes::Block => write!(f, "BLOCK"), 72 | } 73 | } 74 | } 75 | 76 | /// PolicyEngineRuleTarget: ffff that represents the different types of rule targets 77 | pub enum PolicyEngineRuleTarget { 78 | Path(PathBuf), 79 | ShaHash(String), 80 | } 81 | 82 | 83 | #[derive(Deserialize, Serialize, Debug, Clone)] 84 | pub struct RulesDb (pub FxHashMap); 85 | impl Jsonify for RulesDb {} 86 | 87 | impl RulesDb { 88 | pub fn new() -> RulesDb { 89 | // check if the rules file exits 90 | let rules_filepath = std::path::PathBuf::from(RULES_DB_PATH); 91 | if !rules_filepath.exists() { 92 | // it doesn't so lets check if the parent directory exists and create it if not 93 | let santa_path = std::path::PathBuf::from(SANTA_BASE_PATH); 94 | if !santa_path.exists() { 95 | if let Err(_) = std::fs::create_dir(santa_path) { 96 | eprintln!("Could not create santa directory at {SANTA_BASE_PATH}"); 97 | } 98 | } 99 | // create an empty rules file 100 | if let Err(_) = std::fs::File::create(rules_filepath.as_path()) { 101 | eprintln!("Could not create empty rules file"); 102 | } 103 | // return the empty db, we don't need to read an empty rules db 104 | RulesDb(FxHashMap::default()) 105 | } else { 106 | // the rules DB file already existed, read it 107 | if let Ok(rules) = read_rules_db_file() { 108 | RulesDb(rules) 109 | } else { 110 | RulesDb(FxHashMap::default()) 111 | } 112 | } 113 | } 114 | /// Sync the daemon's ruleset back to the rules db file 115 | fn sync_rules(&self) { 116 | write_json_to_file(self, RULES_DB_PATH) 117 | } 118 | 119 | /// Add a new rule 120 | pub fn add_rule(&mut self, hash: &RuleCommandInputType, rule: RuleTypes) -> String { 121 | match hash { 122 | RuleCommandInputType::Hash(val) => { 123 | println!("{SANTAD_NAME}: adding {} rule for hash {val}", 124 | PolicyDecision::from(rule).to_string()); 125 | 126 | let _ = match self.0.insert(val.to_string(), rule) { 127 | Some(old) => { 128 | // we updated an existing rule 129 | self.sync_rules(); 130 | return format!("Updated existing {}", old.to_string()) 131 | }, 132 | None => { 133 | // we inserted a new rule 134 | self.sync_rules(); 135 | return "Inserted".to_string() 136 | }, 137 | }; 138 | }, 139 | RuleCommandInputType::Path(val) => { 140 | if let Some(hash) = hash_file_at_path(&val) { 141 | let _ = match self.0.insert(hash.to_string(), rule) { 142 | Some(old) => { 143 | // we updated an existing rule 144 | self.sync_rules(); 145 | return format!("Updated existing {}", old) 146 | }, 147 | None => { 148 | // we inserted a new rule 149 | self.sync_rules(); 150 | return "Inserted".to_string() 151 | }, 152 | }; 153 | } else { 154 | eprintln!("failed to hash file at path: {}", val.display()); 155 | return "Failed to insert".to_string() 156 | } 157 | }, 158 | } 159 | } 160 | 161 | /// Remove a rule 162 | pub fn remove_rule(&mut self, hash: &RuleCommandInputType) -> Option<&'static str> { 163 | match hash { 164 | RuleCommandInputType::Hash(val) => { 165 | println!("{SANTAD_NAME}: removing rule for hash {val}"); 166 | if let Some(_) = self.0.remove(val) { 167 | self.sync_rules(); 168 | return Some("Removed") 169 | } 170 | None 171 | }, 172 | RuleCommandInputType::Path(val) => { 173 | if let Some(hash) = hash_file_at_path(&val) { 174 | if let Some(_) = self.0.remove(&hash) { 175 | self.sync_rules(); 176 | return Some("Removed") 177 | } 178 | None 179 | } else { 180 | eprintln!("failed to hash file at path: {}", val.display()); 181 | return Some("Failed to hash file at path while attempting to remove") 182 | } 183 | }, 184 | } 185 | } 186 | } 187 | -------------------------------------------------------------------------------- /src/rust_santa_daemon/src/santactl/main.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | use std::{time::Duration, path::PathBuf}; 3 | use clap::{Parser, Subcommand}; 4 | 5 | // Local imports 6 | use libsanta::{ 7 | Jsonify, 8 | consts::{XPC_SOCKET_PATH, XPC_CLIENT_PATH}, 9 | rules::RuleTypes, 10 | uxpc::{SantaXpcClient, SantaXpcServer}, 11 | commands::{ 12 | CommandTypes, 13 | SantaCtlCommand, 14 | RuleAction, 15 | StatusCommand, 16 | FileInfoCommand, 17 | RuleCommandInputType, 18 | RuleCommand 19 | }, 20 | }; 21 | 22 | #[allow(dead_code)] 23 | fn sender_msg_thread(msg: T) { 24 | // create the client socket and send the message 25 | let mut client = SantaXpcClient::new(XPC_SOCKET_PATH); 26 | let serial_bytes = msg.jsonify(); 27 | client.send(serial_bytes.as_bytes()).unwrap(); 28 | 29 | // sleep to give the listener a chance to recv the message 30 | thread::sleep(Duration::from_millis(1)); 31 | } 32 | 33 | // Validator for sha256 hash strings given in args 34 | fn hash_validator(s: &str) -> Result { 35 | if s.len() > 64 { 36 | return Err("Invalid hash: too long".to_string()); 37 | } else if s.len() < 64 { 38 | return Err("Invalid hash: too short".to_string()); 39 | } 40 | let x = "abcdef1234567890ABCDEF"; 41 | for hash_c in s.chars() { 42 | if !x.contains(hash_c) { 43 | return Err("Invalid character in hash".to_string()) 44 | } 45 | } 46 | Ok(s.to_string()) 47 | } 48 | 49 | /// santactl is used to interact with the santa-daemon 50 | #[derive(Parser)] 51 | struct Cli { 52 | /// Subcommands 53 | #[command(subcommand)] 54 | command: SubCommands, 55 | } 56 | 57 | // Top-level Santactl subcommands 58 | #[derive(Subcommand)] 59 | pub enum SubCommands { 60 | /// Get status info from the daemon 61 | Status, 62 | /// Analyze and get info on a target file 63 | Fileinfo { 64 | path: PathBuf, 65 | }, 66 | /// Manage the daemon's ruleset 67 | Rule { 68 | #[command(subcommand)] 69 | action: RuleSubCommands, 70 | } 71 | } 72 | 73 | // Santactl rule subcommands 74 | #[derive(Subcommand)] 75 | pub enum RuleSubCommands { 76 | /// Show rules 77 | Show, 78 | /// Insert a rule 79 | #[command(group(clap::ArgGroup::new("ver") 80 | .required(true) 81 | .args(["block", "allow"]) 82 | ), 83 | group(clap::ArgGroup::new("ver2") 84 | .required(true) 85 | .args(["file", "sha"]) 86 | ) 87 | )] 88 | Insert { 89 | /// Create an allow rule 90 | #[arg(short, long, action, required=false)] 91 | allow: bool, 92 | /// Create an block rule 93 | #[arg(short, long, action, required=false)] 94 | block: bool, 95 | /// Insert a rule by hashing the given file 96 | #[arg(short, long, required=false, value_parser = clap::value_parser!(PathBuf))] 97 | file: Option, 98 | /// Insert a rule for a SHA256 hash 99 | #[arg(short, long, value_name="SHA256", required=false, value_parser = hash_validator)] 100 | sha: Option, 101 | }, 102 | /// Remove a rule 103 | Remove { 104 | hash: String, 105 | }, 106 | } 107 | 108 | fn main() { 109 | let args = Cli::parse(); 110 | let cmd; 111 | match &args.command { 112 | SubCommands::Status => { 113 | let stat = StatusCommand {}; 114 | cmd = SantaCtlCommand { 115 | ctype: CommandTypes::Status, 116 | command: stat.jsonify(), 117 | }; 118 | } 119 | SubCommands::Fileinfo { path } => { 120 | if !path.exists() { 121 | eprintln!("Path not found: {}\n", path.display()); 122 | return 123 | } 124 | 125 | let fileinfo = FileInfoCommand { path: path.to_owned() }; 126 | cmd = SantaCtlCommand { 127 | ctype: CommandTypes::FileInfo, 128 | command: fileinfo.jsonify(), 129 | }; 130 | } 131 | SubCommands::Rule { action } => { 132 | match action { 133 | // Insert rule command 134 | RuleSubCommands::Insert { file: path, sha: hash, allow, block:_ } => { 135 | if let Some(p) = path { 136 | // we have to have been given a path 137 | if !p.exists() { 138 | eprintln!("Path not found: {}", p.display()); 139 | return 140 | } 141 | let rulecmd = RuleCommand { 142 | action: RuleAction::Insert, 143 | target: RuleCommandInputType::Path(p.clone()), 144 | policy: (if *allow {RuleTypes::Allow} else {RuleTypes::Block}), 145 | }; 146 | cmd = SantaCtlCommand { 147 | ctype: CommandTypes::Rule, 148 | command: rulecmd.jsonify(), 149 | } 150 | } else if let Some(h) = hash { 151 | let rulecmd = RuleCommand { 152 | action: RuleAction::Insert, 153 | target: RuleCommandInputType::Hash(h.clone()), 154 | policy: (if *allow {RuleTypes::Allow} else {RuleTypes::Block}), 155 | // policy: *rule, 156 | }; 157 | cmd = SantaCtlCommand { 158 | ctype: CommandTypes::Rule, 159 | command: rulecmd.jsonify(), 160 | } 161 | } else { 162 | unreachable!() 163 | } 164 | }, 165 | // Remove rule command 166 | RuleSubCommands::Remove { hash } => { 167 | let rule = RuleTypes::Allow; // won't be used 168 | let rulecmd = RuleCommand { 169 | action: RuleAction::Remove, 170 | target: RuleCommandInputType::Hash(String::from(hash)), 171 | policy: rule, 172 | }; 173 | cmd = SantaCtlCommand { 174 | ctype: CommandTypes::Rule, 175 | command: rulecmd.jsonify(), 176 | } 177 | }, 178 | RuleSubCommands::Show {} => { 179 | let rulecmd = RuleCommand { 180 | action: RuleAction::Show, 181 | target: RuleCommandInputType::Hash(String::from("")), 182 | policy: RuleTypes::Allow, // won't be used, but need a value 183 | }; 184 | cmd = SantaCtlCommand { 185 | ctype: CommandTypes::Rule, 186 | command: rulecmd.jsonify(), 187 | } 188 | }, 189 | } 190 | } 191 | } 192 | 193 | // create the XPC server socket 194 | let server = SantaXpcServer::new(XPC_CLIENT_PATH, false); 195 | 196 | // send the command msg in a thread 197 | thread::spawn(move || { 198 | // create the client socket and send the message 199 | let mut client = SantaXpcClient::new(XPC_SOCKET_PATH); 200 | let serial_bytes = cmd.jsonify(); 201 | client.send(serial_bytes.as_bytes()).unwrap(); 202 | 203 | // sleep to give the listener a chance to recv the message 204 | thread::sleep(Duration::from_millis(1)); 205 | }); 206 | 207 | // sleep to give the sender thread a chance to send the message 208 | thread::sleep(Duration::from_millis(1)); 209 | 210 | // wait for the response 211 | if let Some(result) = server.recv() { 212 | println!("{result}"); 213 | } 214 | } 215 | -------------------------------------------------------------------------------- /src/rust_santa_daemon/src/santa-daemon/main.rs: -------------------------------------------------------------------------------- 1 | /// Rust implementation of the Santa daemon 2 | mod daemon; 3 | mod netlink; 4 | mod engine; 5 | mod tracer; 6 | mod cache; 7 | 8 | use std::{ 9 | error::Error, 10 | fs::OpenOptions, 11 | path::{PathBuf, Path} 12 | }; 13 | 14 | use daemonize::Daemonize; 15 | use clap::Parser; 16 | use nix::unistd::Pid; 17 | use nix::sys::wait::{WaitStatus, self}; 18 | 19 | use libsanta::{ 20 | {SantaMode, Loggable, LoggerSource, Jsonify}, 21 | uxpc::SantaXpcClient, 22 | consts::{SANTAD_NAME, XPC_CLIENT_PATH}, 23 | engine_types::{PolicyDecision, PolicyEnginePathTarget}, 24 | commands::{ 25 | SantaCtlCommand, 26 | CommandTypes, 27 | RuleAction, 28 | RuleCommand, 29 | FileInfoCommand, 30 | StatusCommand, 31 | RuleCommandInputType, 32 | }, 33 | }; 34 | use daemon::SantaDaemon; 35 | use netlink::NlSantaCommand; 36 | 37 | pub const SANTA_LOG: &str = "/var/log/santad.log"; 38 | pub const SANTA_ERRLOG: &str = "/var/log/santad_err.log"; 39 | 40 | /// santa-daemon 41 | #[derive(Parser)] 42 | struct Cli { 43 | /// Whether the process should daemonize or not 44 | #[arg(short, long, action)] 45 | daemonize: bool, 46 | } 47 | 48 | // Check for a uxpc message and handle it if there is one 49 | fn santactl_worker(mut daemon: SantaDaemon) -> SantaDaemon { 50 | if let Some(data) = daemon.xpc_rx.recv() { 51 | if let Ok(payload) = serde_json::from_str::(&data) { 52 | match &payload.ctype { 53 | CommandTypes::Rule => { 54 | if let Ok(cmd) = serde_json::from_str::(&payload.command) { 55 | let msg; 56 | match cmd.action { 57 | // Insert rules command 58 | RuleAction::Insert => { 59 | let what_happened = daemon.engine.rules.add_rule(&cmd.target, cmd.policy); 60 | match cmd.target { 61 | RuleCommandInputType::Hash(hash) => { 62 | msg = format!( 63 | "{} rule for hash {}: {}", 64 | what_happened, hash, cmd.policy 65 | ); 66 | }, 67 | RuleCommandInputType::Path(p) => { 68 | msg = format!( 69 | "{} rule for file {}: {}", 70 | what_happened, p.display(), cmd.policy 71 | ); 72 | }, 73 | } 74 | }, 75 | // Remove rules command 76 | RuleAction::Remove => { 77 | if let Some(what_happened) = 78 | daemon.engine.rules.remove_rule(&cmd.target) { 79 | match cmd.target { 80 | RuleCommandInputType::Hash(hash) => { 81 | msg = format!( 82 | "{} rule for hash: {}", what_happened, hash); 83 | }, 84 | RuleCommandInputType::Path(p) => { 85 | msg = format!( 86 | "{} rule for hash of file: {}", 87 | what_happened, p.display() 88 | ); 89 | }, 90 | } 91 | } else { 92 | match cmd.target { 93 | RuleCommandInputType::Hash(hash) => { 94 | msg = format!("No rule for hash '{}'", hash); 95 | }, 96 | RuleCommandInputType::Path(p) => { 97 | msg = format!( 98 | "No rule for hash of file: {}", p.display() 99 | ); 100 | }, 101 | } 102 | } 103 | }, 104 | // Show rules command 105 | RuleAction::Show => { 106 | msg = daemon.engine.rules.jsonify_pretty(); 107 | }, 108 | } 109 | let mut xclient = SantaXpcClient::new(XPC_CLIENT_PATH); 110 | if let Err(err) = xclient.send(msg.as_bytes()) { 111 | eprintln!( 112 | "{SANTAD_NAME}: Failed to send message to XPC client - {err}" 113 | ); 114 | } 115 | return daemon; 116 | } 117 | }, 118 | CommandTypes::FileInfo => { 119 | if let Ok(cmd) = serde_json::from_str::(&payload.command) { 120 | let path = PathBuf::from(&cmd.path); 121 | if !path.exists() { 122 | eprintln!( 123 | "{SANTAD_NAME}:FileInfoHandler | File not found - {}", 124 | cmd.path.display() 125 | ) 126 | } 127 | let target = PolicyEnginePathTarget::FilePath(path); 128 | let answer = daemon.check(&target).jsonify_pretty(); 129 | let mut xclient = SantaXpcClient::new(XPC_CLIENT_PATH); 130 | if let Err(err) = xclient.send(answer.as_bytes()) { 131 | eprintln!( 132 | "{SANTAD_NAME}: Failed to send message to XPC client - {err}" 133 | ); 134 | } 135 | return daemon 136 | } 137 | }, 138 | CommandTypes::Status => { 139 | if let Ok(_) = serde_json::from_str::(&payload.command) { 140 | let status = daemon.status().jsonify_pretty(); 141 | let mut xclient = SantaXpcClient::new(XPC_CLIENT_PATH); 142 | if let Err(err) = xclient.send(status.as_bytes()) { 143 | eprintln!("{SANTAD_NAME}: Failed to send message to XPC client - {err}"); 144 | } 145 | } 146 | }, 147 | } 148 | } else { 149 | eprintln!("Invalid message format for : {}", data); 150 | } 151 | }; 152 | daemon 153 | } 154 | 155 | // Check for a netlink message and handle it if there is one 156 | fn netlink_worker(mut daemon: SantaDaemon) -> SantaDaemon { 157 | // Check for messages from the kernel on the netlink socket 158 | match daemon.netlink.recv() { 159 | Ok(res) => { 160 | // No errors on the recv(), lets check if we got a message 161 | if let Some((cmd, payload)) = res { 162 | match cmd { 163 | NlSantaCommand::MsgDoHash => { 164 | // parse the pid from the payload 165 | let pid: i32 = match payload.parse() { 166 | Ok(p) => p, 167 | Err(e) => { 168 | eprintln!("{}", e.to_string()); 169 | return daemon 170 | } 171 | }; 172 | 173 | match tracer::attacher(Pid::from_raw(pid)) { 174 | Ok(_) => { 175 | // println!("{SANTAD_NAME}: attached to pid {pid}"); 176 | match wait::waitpid(Pid::from_raw(pid), None) { 177 | Ok(WaitStatus::Exited(_,code)) => { 178 | // what should we do if the process exited? 179 | eprintln!( 180 | "{}: pid {} exited with code {}", 181 | SANTAD_NAME, pid, code 182 | ); 183 | }, 184 | Ok(WaitStatus::Stopped(p, _sig)) => { 185 | // this means we attached and have control of the process 186 | // println!("{SANTAD_NAME}: pid {pid} stopped with {}", sig); 187 | let target = PolicyEnginePathTarget::from(pid as u32); 188 | // get an answer 189 | let answer = daemon.check(&target); 190 | // log the answer 191 | answer.log(LoggerSource::SantaDaemon); 192 | 193 | // kill the process if it should be blocked 194 | if let PolicyDecision::Block = answer.decision { 195 | if let Err(_e) = tracer::detacher(p) { 196 | eprintln!("{SANTAD_NAME}: {_e}"); 197 | }; 198 | // println!("{SANTAD_NAME}: detached from pid {pid}"); 199 | daemon.engine.kill(p.as_raw()); 200 | println!("{SANTAD_NAME}: killed pid {p}"); 201 | return daemon 202 | } else { 203 | if let Err(_e) = tracer::detacher(p) { 204 | eprintln!("{SANTAD_NAME}: {_e}") 205 | }; 206 | // println!("{SANTAD_NAME}: detached from pid {pid}"); 207 | } 208 | }, 209 | Ok(_) => { 210 | eprintln!( 211 | "{}: Unexpected signal while waiting to attach pid {}", 212 | SANTAD_NAME, pid); 213 | }, 214 | Err(_) => { 215 | eprintln!("{}: error while waiting for pid {}", 216 | SANTAD_NAME, pid); 217 | } 218 | } 219 | } 220 | Err(_e) => { 221 | // we failed to attach to the process with ptrace, we'll let it 222 | // race the daemon for now 223 | eprintln!("{SANTAD_NAME}: {_e}"); 224 | let target = PolicyEnginePathTarget::from(pid as u32); 225 | let answer = daemon.check(&target); 226 | // log the answer 227 | answer.log(LoggerSource::SantaDaemon); 228 | // kill the process if it should be blocked 229 | if let PolicyDecision::Block = answer.decision { 230 | daemon.engine.kill(pid); 231 | } 232 | return daemon 233 | } 234 | } 235 | }, 236 | _ => { 237 | eprintln!("{SANTAD_NAME}: received unknown command"); 238 | } 239 | } 240 | } 241 | }, 242 | Err(err) => eprintln!("{SANTAD_NAME}: netlink recv error - {err}"), 243 | } 244 | daemon 245 | } 246 | 247 | /// The main worker loop that handles incoming messages 248 | fn worker_loop() -> Result<(), Box> { 249 | // instantiate the daemon instance 250 | let mut daemon = SantaDaemon::new(SantaMode::Monitor)?; 251 | 252 | // do stuff forever 253 | loop { 254 | // Check for messages from the kernel on the netlink socket 255 | daemon = santactl_worker(daemon); 256 | // Check for messages from santactl on the unix socket 257 | daemon = netlink_worker(daemon); 258 | }; 259 | } 260 | 261 | 262 | /// Main 263 | fn main() -> Result<(), ()> { 264 | // Parse command-line args 265 | let args = Cli::parse(); 266 | println!("{SANTAD_NAME}: Entering main message processing loop..."); 267 | 268 | // determine whether we should fork to the background or run normally 269 | if args.daemonize { 270 | // stderr output file 271 | let stderr_path = Path::new(SANTA_ERRLOG); 272 | let stderr = match OpenOptions::new().append(true).create(true).open(stderr_path) { 273 | Ok(file) => {file}, 274 | Err(e) => { 275 | eprintln!("Error: {e}"); 276 | return Ok(()) 277 | }, 278 | }; 279 | 280 | // stdout output file 281 | let stdout_path = Path::new(SANTA_LOG); 282 | let stdout = match OpenOptions::new().append(true).create(true).open(stdout_path) { 283 | Ok(file) => {file}, 284 | Err(e) => { 285 | eprintln!("Error: {e}"); 286 | return Ok(()) 287 | }, 288 | }; 289 | 290 | // create the daemon instance with stdout/stderr redirection 291 | let daemonized = Daemonize:: 292 | new() 293 | .stderr(stderr) 294 | .stdout(stdout); 295 | 296 | // start up 297 | match daemonized.start() { 298 | Ok(_) => { 299 | println!("Successfully daemonized the santad process..."); 300 | if let Err(err) = worker_loop() { 301 | eprintln!("Error encountered during the main processing loop: {err}"); 302 | } 303 | } 304 | Err(err) => eprintln!("Failed to daemonize the process: {err}"), 305 | }; 306 | } else { 307 | // we're not daemoizing, do stuff forever 308 | if let Err(err) = worker_loop() { 309 | eprintln!("Error encountered during the main processing loop: {err}"); 310 | } 311 | } 312 | 313 | Ok(()) 314 | } 315 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # santa for linux proof-of-concept 2 | 3 | This is a proof-of-concept clone of Google's [Santa](https://github.com/google/santa), a binary authorization system for macOS. The design is similar in the use of both a kernel module and userland daemon component to make policy decisions based on the SHA256 hash of the target file being executed. 4 | 5 | ```sh 6 | # show the current rules 7 | $ santactl rule show 8 | { 9 | "a92d9b7533984599bb263f703b5968db9a07f49aa6bb416faa535cd781debcbb": "Block", 10 | "f5d5379e0ec9b97813f546bd12029657b7c51135fcd8439bca9333ab1dfdf557": "Allow" 11 | } 12 | 13 | # the allowlisted binary 14 | $ ./allowme 15 | i should be ALLOWED - my PID is 135 16 | 17 | # the blocklisted binary 18 | $ ./blockme 19 | Killed 20 | 21 | # logs 22 | $ cat /var/log/santad.log 23 | Successfully daemonized the santad process... 24 | [...] 25 | [santa-DAEMON]: UNKNOWN (ALLOW) /usr/bin/santactl -> 2585c6fef89e4b231c2a8ef16779b6475a2f0678f7bb7deaa3ddd30e56a5d20b 26 | [santa-DAEMON]: ALLOWLISTED (ALLOW) /allowme -> f5d5379e0ec9b97813f546bd12029657b7c51135fcd8439bca9333ab1dfdf557 27 | [santa-DAEMON]: BLOCKLISTED (BLOCK) /blockme -> a92d9b7533984599bb263f703b5968db9a07f49aa6bb416faa535cd781debcbb 28 | [santa-DAEMON]: UNKNOWN (ALLOW) /usr/bin/coreutils -> 60271e6b1fee7fdfa8a4f25410bcfb6d6cb5e4c8ff236cb0b928ea577130a5da 29 | ``` 30 | 31 | ## Features 32 | 33 | 1. Multiple enforcement modes: Monitor mode for enforcing a blocklist policy only and Lockdown mode for enforcing an allowlist policy (i.e. only allowlisted binaries are allowed). 34 | 2. SHA256-based rules: create allowlist/blocklist rules based on the SHA256 hash of target binaries. The ruleset can be provided via JSON file using a simple k:v format: `": ` or inserted at runtime using the `santactl rule insert` command. 35 | 3. Hash Cache: the daemon implements a caching layer to avoid having to re-hash recently hashed files to improve performance. The cache is implemented as a fixed-size FIFO queue, and the oldest entries are only removed once the cache capacity is reached. 36 | 37 | ## Known Issues/Limitations 38 | Extensive testing has not been done yet and this is very much still a proof-of-concept implementation. It's not meant to be functional on a full machine or even useful for anything practical at this point. 39 | 40 | ## TODO & Unimplemented Features 41 | 42 | * Scope-based rules (i.e. path-based rules) 43 | * Cleaner exception handling in the daemon 44 | * Allow the daemon to re-checkin in case of failures 45 | * Improve IPC validation/authentication between components 46 | 47 | --- 48 | 49 | # Architecture & Design 50 | 51 | ## Execution Flow 52 | The sequence of events that take place on each execution and the process that Santa takes to make a decision on whether execution will be allowed or denied is described below. 53 | 54 | ### Kernel 55 | 1. The kernel module hooks calls to the kernel function `finalize_exec()` using a kprobe pre-handler. After a call to an execve variant, this function is called to complete the exec setup process, right before execution is actually handed to the binary’s entry point 56 | - The module gets the PID of the process that is executing the target binary by reading from `task_struct *current` 57 | 2. The kernel module sends a message containing the target PID to the daemon over a generic netlink socket. 58 | 59 | ### User-Space 60 | 1. The daemon loops indefinitely, processes incoming messages from the kernel. Upon receiving a message it parses the PID from the message payload. 61 | 2. The daemon attaches the the process pointed to by the PID via ptrace and holds execution 62 | 2. The daemon gets the SHA256 hash of the target binary 63 | - It first calculates a unique signature using file metadata and checks the cache to see if the signature is found. If it is, this hash is used. 64 | - If the signature was not found in the cache, the daemon calculates the hash by reading from `/proc//exe` and performing the shasum operation 65 | 3. The daemon checks whether the hash is present on the blocklist or allowlist 66 | - If on the allowlist: execution is allowed 67 | - If on the blocklist: execution is blocked 68 | - If neither: the file is unknown and the decisions is based on whether Lockdown mode is enabled 69 | 4. If execution should be blocked, the daemon sends a `SIGKILL` signal to the target PID. Otherwise the daemon detaches from the process and execution is allowed to proceed. 70 | 71 | ## Components 72 | ### Kernel Module 73 | 74 | The kernel module is responsible for the initial interception of the new execution and collecting required metadata that the daemon will need in order to make a final determination about whether execution will be allowed to continue or blocked. 75 | 76 | The module gathers the PID of the target binary as parsed from the `current` task struct and sends a message to the daemon in over a generic netlink socket using a custom protocol and command. The kernel module can also handle incoming netlink messages from the daemon. 77 | 78 | The module uses the kprobe kernel infrastructure to accomplish this hooking. Rather than hooking the `execve__*` syscall functions directly, the kprobe is applied to the function `finalize_exec()`; this is done because by the time that function is called we can be assured the target binary has been loaded into memory and the data in `/proc//` has been updated. This ensures the correct data is read when the daemon reads `/proc//exe` to get calculate the hash of the binary that will be executed. Hooking earlier in the exec process results in `/proc//exe` always pointing to the shell binary from which the exec spawned. 79 | 80 | ### Santa Daemon 81 | 82 | The daemon is reponsible for calculating the hash of the target binary and making execution decisions based on whether the target binary’s hash is allowlisted, blocklisted, or unknown. The daemon opens and binds to the kernel’s Netlink socket that it uses to establish a comms channel with the kernel module and wait for incoming messages. 83 | 84 | Upon receiving a message from the kernel, the daemon parses the PID from the message payload and uses it to read from `/proc//exe` in order to calculate the hash of the file being executed. Once the SHA256 hash has been calculated, the daemon checks whether the hash is present on either the allowlist or blocklist, and takes the appropriate action. If the hash is on neither, then it is unknown, and the execution decision is determined by the mode: block in Lockdown, allow in Monitor. 85 | 86 | ### Santactl 87 | 88 | The `santactl` binary is used to interact with the daemon at runtime. It can be used to insert or remove rules, show known rules, and get daemon information such as the current mode and size of the ruleset. It also offers a feature for having the daemon’s policy engine analyze a target file and report whether it is known and would be allowed or blocked. 89 | 90 | ## IPC 91 | 92 | Two different IPC mechanisms are used to handle bi-directional communication between the different components: Generic Netlink and Unix domain sockets. 93 | 94 | ### Kernel-Daemon Communication: Generic Netlink 95 | 96 | The kernel module and daemon components communicate over a Netlink socket using a custom generic netlink protocol. The kernel module registers a new Netlink family and associated handlers for the different commands the protocol understands. There are 4 supported commands: 97 | 98 | ``` 99 | MSG - Generic message command 100 | CHECK-IN - Command the daemon sends to check-in w/ kernel 101 | DO-HASH - Command the kernel mod sends to daemon to init hash job 102 | HASH-DONE - Command the daemon sends the kernel to signal hash job completion 103 | ``` 104 | 105 | Messages are automatically validated by the kernel through the generic netlink interface and on the daemon side through Rust’s strong typing and exhaustive pattern checking. 106 | 107 | ### Santactl-Daemon Communication: Unix Domain sockets 108 | 109 | Communication between the `santactl` and the daemon happens over standard Unix domain sockets. At runtime, the daemon creates and binds to a socket at `/opt/santa/santad.xpc` where it expects to receive messages from `santactl`. Similarly, `santactl` will create and bind to a socket at `/opt/santa/santactl.xpc` where it expects to receive responses back from the daemon. Each of these components connects to the other’s receiver socket to send messages. Messages are defined using structs that derive the `serde::Serialize` and `serde::Deserialize` traits, and are JSON serialized before being sent on the socket and deserialized back to their respective structs on the receiving end. 110 | 111 | --- 112 | 113 | # Concepts 114 | ## Mode 115 | 116 | The Santa daemon operates in one of two modes: 117 | 118 | - **Monitor:** executions are hooked and explicit blocklist rules are honored, but unknown binaries are allowed to run. 119 | - **Lockdown**: the same as monitor mode, except the default policy is to block any binary that is not explicitly allowlisted. 120 | 121 | The mode is currently hardcoded into the daemon binary and changing the mode requires recompiling the binary. 122 | 123 | **TODO: Add option to switch modes using `santactl`.** 124 | 125 | WARNING: Lockdown mode will almost certainly bork the system and make it completely unusable without having hashed and allowlisted at least everything in `/bin:/usr/bin:/sbin:/usr/sbin` first. I haven’t tested this mode at all yet. 126 | 127 | ## Rules 128 | 129 | This current implementation only supports rules defined by the SHA256 hash of a target binary. The daemon reads the ruleset at runtime from a JSON file at `/opt/santa/rules.json`. This file has a simple format: 130 | 131 | ```json 132 | { 133 | "": "" 134 | } 135 | ``` 136 | 137 | Its also possible to add or remove rules using the `santactl rule ` subcommands. 138 | 139 | Although the macOS version of Santa supports creating rules based on the signing certificate for signed applications, this doesn’t translate well to the Linux ecosystem since application signing is not really a thing there, so that likely won’t be added to this version. 140 | 141 | **TODO: add support for scope-based rules (i.e. path-based allowlisting)** 142 | 143 | ## Cache 144 | 145 | The daemon implements a caching mechanism to keep the hashes of the most recently hashed files and avoid having to re-hash files on each execution, since that operations can be computationally expensive depending on the size of the target binary. 146 | 147 | The cache is implemented as a fixed-size FIFO queue using a combination of a `HashMap` and vector that tracks inserted keys in an ordered fashion. Upon reaching the cache capacity, the oldest keys in the vector queue are dropped and removed from the HashMap. Cache lookups get the benefit of HashMap lookup speeds. 148 | 149 | --- 150 | 151 | # Binaries 152 | 153 | ## santa-daemon 154 | 155 | ``` 156 | santa-daemon 157 | 158 | Usage: santa-daemon [OPTIONS] 159 | 160 | Options: 161 | -d, --daemonize Whether the process should daemonize or not 162 | -h, --help Print help information 163 | ``` 164 | 165 | **NOTE**: When the daemon is started with the `-d` flag to daemonize, it will log STDOUT to `/var/log/santad.log` and STDERR to `/var/log/santad_err.log`. 166 | 167 | ## santactl 168 | 169 | ``` 170 | santactl is used to interact with the santa-daemon 171 | 172 | Usage: santactl 173 | 174 | Commands: 175 | status Get status info from the daemon 176 | fileinfo Analyze and get info on a target file 177 | rule Manage the daemon's ruleset 178 | help Print this message or the help of the given subcommand(s) 179 | 180 | Options: 181 | -h, --help Print help information 182 | ``` 183 | 184 | ### Daemon Status 185 | This command can be used to query stats from the santa daemon. 186 | 187 | ```bash 188 | $ santactl status 189 | { 190 | "mode": "Monitor", 191 | "rule_count": 2, 192 | "cache_count": 4 193 | } 194 | ``` 195 | 196 | ### Rule Management 197 | This command can be used to view and manage the ruleset at runtime. 198 | 199 | ``` 200 | Manage the daemon's ruleset 201 | 202 | Usage: santactl rule 203 | 204 | Commands: 205 | show Show rules 206 | insert Insert rules 207 | delete Delete rules 208 | help Print this message or the help of the given subcommand(s) 209 | 210 | Options: 211 | -h, --help Print help information 212 | ``` 213 | 214 | ### File Info 215 | 216 | ``` 217 | Analyze and get info on a target file 218 | 219 | Usage: santactl fileinfo 220 | 221 | Arguments: 222 | 223 | 224 | Options: 225 | -h, --help Print help information 226 | ``` 227 | 228 | ```bash 229 | $ santactl fileinfo --path /testbin 230 | { 231 | "filepath": "/testbin", 232 | "hash": "ece6694532cee1c661623a6029a2f0563df841e0d2a7034077f7d8d86178ae8a", 233 | "decision": "Allow", 234 | "reason": "Unknown" 235 | } 236 | ``` 237 | --- 238 | 239 | # Build and Run the Buildroot+QEMU Environment 240 | 241 | The `ext-tree/` directory contains an external buildroot tree pre-configured to build a 5.4.58 Linux kernel, the Santa kernel module and binaries, and a minimal root filesystem with everything included and configured to start at boot. The kernel image and root filesystem can be run via QEMU. 242 | 243 | ``` 244 | ├── br-output 245 | ├── ext-tree 246 | │   ├── Config.in 247 | │   ├── configs 248 | │   ├── external.desc 249 | │   ├── external.mk 250 | │   ├── overlay/ 251 | │   └── package/ 252 | ``` 253 | 254 | 1. `ext-tree/`: the external buildroot tree preconfigured to build the kernel module and daemon, along with a 5.4.58 kernel and a root filesystem image containing the module and daemon. 255 | - `ext-tree/configs`: contains the kernel and buildroot configuration files from which new builds can be run 256 | - `ext-tree/package`: buildroot package recipes for the kernel module and daemon components 257 | - `ext-tree/overlay`: buildroot filesystem overlay files 258 | 2. `src/rust_santa_daemon`: the source code for the new santa daemon written in Rust 259 | 3. `src/santa_kmod`: the source code for the santa kernel module 260 | 4. `local-build.sh`: a convenience script to run a complete build of the buildroot environment and the santa packages 261 | 4. `qemu-run.sh`: a convenience script to run a QEMU VM with the kernel and root filesystem images 262 | 263 | ## build 264 | **NOTE: Local builds have only been tested on Ubuntu 20.04 and Debian 11.0 stable.** 265 | 266 | ### install dependencies 267 | ```bash 268 | sudo apt update && apt install -y \ 269 | build-essential \ 270 | bzip2 \ 271 | gzip \ 272 | lzop \ 273 | liblzma-dev \ 274 | liblzo2-dev \ 275 | ocaml-nox \ 276 | gawk \ 277 | p7zip-full \ 278 | python3 \ 279 | python3-lzo \ 280 | python3-pip \ 281 | squashfs-tools \ 282 | tar \ 283 | unzip \ 284 | perl \ 285 | rsync \ 286 | fakeroot \ 287 | ccache ecj fastjar \ 288 | gettext git java-propose-classpath libelf-dev libncurses5-dev \ 289 | libncursesw5-dev libssl-dev python python2.7-dev \ 290 | python3-setuptools python3-dev subversion \ 291 | pkg-config \ 292 | wget \ 293 | cpio \ 294 | bc \ 295 | zlib1g-dev 296 | ``` 297 | 298 | ### full build 299 | From the root directory of the repo, run the following command to download buildroot and initialize a new build to output to the `br-output` directory: 300 | 301 | ```bash 302 | mkdir -p br-output 303 | wget -c https://buildroot.org/downloads/buildroot-2022.08.tar.gz -O - | tar -xz 304 | cd buildroot-2022.08/ 305 | make O="$PWD/../br-output" BR2_EXTERNAL="$PWD/../ext-tree" rust-santa-clone-qemu_x86_64_defconfig 306 | cd ../br-output 307 | ``` 308 | 309 | The buildroot kernel image, minimal root filesystem image, santa kernel module, and santa daemon can be built using these commands: 310 | 311 | ```bash 312 | # the targets say 'rebuild' but this still works on the first run 313 | make -j12 santa_kmod-rebuild 314 | make -j12 rust_santa_daemon-rebuild 315 | make -j12 all 316 | ``` 317 | 318 | ### rebuilding the daemon 319 | 320 | to rebuild the daemon component and filesystem image only, run this command from the output directory (`br-output`): 321 | 322 | ```bash 323 | make -j12 rust_santa_daemon-rebuild; make -j12 all 324 | ``` 325 | 326 | ### rebuilding the kernel module 327 | 328 | to rebuild the kernel module and filesystem image only, run this command from the output directory (`br-output`): 329 | 330 | ```bash 331 | make -j12 santa_kmod-rebuild; make -j12 all 332 | ``` 333 | 334 | 335 | ## running the image w/ QEMU 336 | the resulting kernel image and root filesystem will have the kernel module and daemon binaries included, as well as config files to ensure both are automatically loaded and started at boot. 337 | 338 | the image can be run with QEMU using the following command: 339 | 340 | ```bash 341 | export IMAGE_DIR="br-output/images" 342 | qemu-system-x86_64 \ 343 | -m 512M \ 344 | -M pc \ 345 | -cpu qemu64 \ 346 | -kernel ${IMAGE_DIR}/bzImage \ 347 | -drive file="${IMAGE_DIR}"/rootfs.ext2,if=virtio,format=raw \ 348 | -append "rw nokaslr panic=1 root=/dev/vda console=tty1 console=ttyS0" \ 349 | -no-reboot \ 350 | -nographic \ 351 | -serial mon:stdio \ 352 | -s \ 353 | -net nic,model=virtio -net user 354 | ``` 355 | 356 | ## santa auto-start in the vm 357 | The filesystem that is created as part of the buildroot VM contains files that will configure the Santa kernel module to be loaded and the santa-daemon process to start automatically at boot: 358 | 359 | - `ext-tree/overlay/etc/init.d/S90modules` 360 | - `ext-tree/overlay/etc/init.d/S99santa_daemon` 361 | 362 | -------------------------------------------------------------------------------- /src/santa_kmod/santa_clone.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | // Maxlen for symbol targets for probing 14 | #define MAX_SYMBOL_LEN 64 15 | // Max netlink payload 16 | #define MAX_PAYLOAD 1024 17 | // Custom version for our protocol 18 | #define NL_SANTA_CUSTOM_PROTO 30 19 | // Module name 20 | #define KMOD_NAME "santa-KMOD" 21 | // Custom Netlink family name 22 | #define FAMILY_NAME "gnl_santa" 23 | 24 | /** 25 | * ================================================================================================ 26 | * GLOBALS 27 | * ================================================================================================ 28 | * 29 | * Agent PID (port id) of the daemon in userspace. The kmod will save this value once it 30 | * receives a checkin command from the daemon. 31 | */ 32 | static int agent_pid = -1; 33 | /* Completion object used to hold execs while the daemon sends back a response */ 34 | 35 | /** 36 | * ================================================================================================ 37 | * NETLINK SETUP 38 | * ================================================================================================ 39 | * 40 | * ==================== 41 | * GNL CALLBACK (PROTOTYPES) 42 | * ==================== 43 | */ 44 | /* callback for handling msg command */ 45 | int gnl_cb_santa_msg_doit(struct sk_buff *sender_skb, struct genl_info *info); 46 | /* no-op callback for do-hash command */ 47 | int gnl_cb_santa_do_hash_doit(struct sk_buff *sender_skb, struct genl_info *info); 48 | /* callback for handling hash-done command */ 49 | int gnl_cb_santa_hash_done_doit(struct sk_buff *sender_skb, struct genl_info *info); 50 | /* callback for handling check-in message */ 51 | int gnl_cb_santa_checkin_doit(struct sk_buff *sender_skb, struct genl_info *info); 52 | /* error reply callback */ 53 | int gnl_cb_doit_reply_error(struct sk_buff *sender_skb, struct genl_info *info); 54 | 55 | /* 56 | * ==================== 57 | * PROTOCOL ATTRIBUTES 58 | * ==================== 59 | * These are the attributes that we want to share in netlink family. 60 | * You can understand an attribute as a semantic type. This is the payload of Netlink messages. 61 | * GNl: Generic Netlink 62 | */ 63 | enum GNL_SANTA_ATTRIBUTE { 64 | /* 0 is never used (=> UNSPEC) */ 65 | GNL_SANTA_A_UNSPEC, 66 | /* We expect a MSG to be a null-terminated C-string. */ 67 | GNL_SANTA_A_MSG, 68 | /* Unused marker field to get the length/count of enum entries. No real attribute. */ 69 | __GNL_SANTA_A_MAX, 70 | }; 71 | /*ffffber of elements in `enum GNL_SANTA_ATTRIBUTE`. */ 72 | #define GNL_SANTA_ATTRIBUTE_ENUM_LEN (__GNL_SANTA_A_MAX) 73 | /* The number of actual usable attributes in `enum GNL_SANTA_ATTRIBUTE`. (-1 because UNSPEC) */ 74 | #define GNL_SANTA_ATTRIBUTE_COUNT (GNL_SANTA_ATTRIBUTE_ENUM_LEN - 1) 75 | 76 | /** 77 | * ==================== 78 | * PROTOCOL COMMANDS 79 | * ==================== 80 | * Enumeration of all commands (functions) that our custom protocol on top 81 | * of generic netlink supports. This can be understood as the action that 82 | * we want to trigger on the receiving side. 83 | */ 84 | typedef enum GNL_SANTA_COMMAND { 85 | /* 0 is never used (=> UNSPEC) first real command is "1" (>0) */ 86 | GNL_SANTA_C_UNSPEC, 87 | /** 88 | * When this command is received, we expect the attribute `GNL_SANTA_ATTRIBUTE::GNL_SANTA_A_MSG` to 89 | * be present in the Generic Netlink request message. 90 | */ 91 | GNL_SANTA_C_MSG, 92 | // CHECK-IN command 93 | GNL_SANTA_C_MSG_CHECKIN, 94 | // DO HASH command (this is sent by the kmod, not handled by it) 95 | GNL_SANTA_C_MSG_DO_HASH, 96 | // HASH DONE command 97 | GNL_SANTA_C_MSG_HASH_DONE, 98 | // Reply with error 99 | GNL_SANTA_C_REPLY_WITH_NLMSG_ERR, 100 | /* Unused marker field to get the length/count of enum entries. No real attribute. */ 101 | __GNL_SANTA_C_MAX, 102 | } SantaCommand_t; 103 | 104 | /* Number of elements in `enum GNL_SANTA_COMMAND`. */ 105 | #define GNL_SANTA_COMMAND_ENUM_LEN (__GNL_SANTA_C_MAX) 106 | /* The number of actual usable commands in `enum GNL_SANTA_COMMAND`. */ 107 | #define GNL_SANTA_COMMAND_COUNT (GNL_SANTA_COMMAND_ENUM_LEN - 1) 108 | 109 | /* The length of the genl_ops struct for gnl_santa_ops. */ 110 | #define GNL_SANTA_OPS_LEN (GNL_SANTA_COMMAND_COUNT) 111 | 112 | /** 113 | * ==================== 114 | * GNL OPERATIONS 115 | * ==================== 116 | * An array with all operations that will be supported by our custom protocol 117 | */ 118 | struct genl_ops gnl_santa_ops[GNL_SANTA_OPS_LEN] = { 119 | // MSG 120 | { 121 | .cmd = GNL_SANTA_C_MSG, 122 | .flags = 0, 123 | .internal_flags = 0, 124 | /* Callback handler when a request with the specified ".cmd" above is received. 125 | * Always validates the payload except one set NO_STRICT_VALIDATION flag in ".validate" 126 | * See: https://elixir.bootlin.com/linux/v5.11/source/net/netlink/genetlink.c#L717 127 | * 128 | * Quote from: https://lwn.net/Articles/208755 129 | * "The 'doit' handler should do whatever processing is necessary and return 130 | * zero on success, or a negative value on failure. Negative return values 131 | * will cause a NLMSG_ERROR message to be sent while a zero return value will 132 | * only cause a NLMSG_ERROR message to be sent if the request is received with 133 | * the NLM_F_ACK flag set." 134 | * 135 | * You can find this in Linux code here: 136 | * https://elixir.bootlin.com/linux/v5.11/source/net/netlink/af_netlink.c#L2499 137 | */ 138 | .doit = gnl_cb_santa_msg_doit, // handler 139 | .dumpit = NULL, 140 | .start = NULL, 141 | .done = NULL, 142 | .validate = 0, 143 | }, 144 | // MSG_CHECKIN 145 | { 146 | .cmd = GNL_SANTA_C_MSG_CHECKIN, 147 | .flags = 0, 148 | .internal_flags = 0, 149 | .doit = gnl_cb_santa_checkin_doit, // handler 150 | .dumpit = NULL, 151 | .start = NULL, 152 | .done = NULL, 153 | .validate = 0, 154 | }, 155 | // MSG_DO_HASH (no-op on the kernel side) 156 | { 157 | .cmd = GNL_SANTA_C_MSG_DO_HASH, 158 | .flags = 0, 159 | .internal_flags = 0, 160 | .doit = gnl_cb_santa_do_hash_doit, // handler (we reuse the msg-do-it since we have to provide a handler here) 161 | .dumpit = NULL, 162 | .start = NULL, 163 | .done = NULL, 164 | .validate = 0, 165 | }, 166 | // MSG_HASH_DONE 167 | { 168 | .cmd = GNL_SANTA_C_MSG_HASH_DONE, 169 | .flags = 0, 170 | .internal_flags = 0, 171 | .doit = gnl_cb_santa_hash_done_doit, // handler 172 | .dumpit = NULL, 173 | .start = NULL, 174 | .done = NULL, 175 | .validate = 0, 176 | }, 177 | // MSG_REPLY_ERROR 178 | { 179 | .cmd = GNL_SANTA_C_REPLY_WITH_NLMSG_ERR, 180 | .flags = 0, 181 | .internal_flags = 0, 182 | .doit = gnl_cb_doit_reply_error, // handler 183 | .dumpit = NULL, 184 | .start = NULL, 185 | .done = NULL, 186 | .validate = 0, 187 | } 188 | }; 189 | 190 | /** 191 | * ==================== 192 | * GNL POLICY 193 | * ==================== 194 | * Attribute policy: defines which attribute has which type (e.g int, char * etc). 195 | * This get validated for each received Generic Netlink message, if not deactivated 196 | * in `gnl_santa_ops[].validate`. 197 | * See https://elixir.bootlin.com/linux/v5.11/source/net/netlink/genetlink.c#L717 198 | */ 199 | static struct nla_policy gnl_santa_policy[GNL_SANTA_ATTRIBUTE_ENUM_LEN] = { 200 | [GNL_SANTA_A_UNSPEC] = {.type = NLA_UNSPEC}, 201 | [GNL_SANTA_A_MSG] = {.type = NLA_NUL_STRING} // MSG expects a null-terminated C string 202 | }; 203 | 204 | /** 205 | * ==================== 206 | * GNL FAMILY 207 | * ==================== 208 | * Definition of the custom netlink protocol family we'll be registering. 209 | */ 210 | static struct genl_family gnl_santa_family = { 211 | // have the kernel auto assign the id 212 | .id = 0, 213 | // we don't use custom additional header info / user specific header 214 | .hdrsize = 0, 215 | // The name of this family, used by userspace application to get the numeric ID 216 | .name = FAMILY_NAME, 217 | // family specific version number; can be used to evolve application over time (multiple versions) 218 | .version = NL_SANTA_CUSTOM_PROTO, 219 | // delegates all incoming requests to callback functions 220 | .ops = gnl_santa_ops, 221 | // length of array `gnl_santa_ops` 222 | .n_ops = GNL_SANTA_OPS_LEN, 223 | // attribute policy (for validation of messages). Enforced automatically, except ".validate" in 224 | // corresponding ".ops"-field is set accordingly. 225 | .policy = gnl_santa_policy, 226 | // Number of attributes / bounds check for policy (array length) 227 | .maxattr = GNL_SANTA_ATTRIBUTE_ENUM_LEN, 228 | // Owning Kernel module of the Netlink family we register. 229 | .module = THIS_MODULE, 230 | // if your application must handle multiple netlink calls in parallel (where one should not block the next 231 | // from starting), set this to true! otherwise all netlink calls are mutually exclusive 232 | .parallel_ops = 0, 233 | // set to true if the family can handle network namespaces and should be presented in all of them 234 | .netnsok = 0, 235 | // called before an operation's doit callback 236 | .pre_doit = NULL, 237 | // called after an operation's doit callback 238 | .post_doit = NULL, 239 | }; 240 | 241 | /** 242 | * ==================== 243 | * NO-OP GNL DO_HASH CALLBACK HANDLER IMPLEMENTATION 244 | * ==================== 245 | */ 246 | int gnl_cb_santa_do_hash_doit(struct sk_buff *sender_skb, struct genl_info *info) { 247 | return 0; 248 | } 249 | 250 | /** 251 | * ==================== 252 | * GNL MSG CALLBACK HANDLER IMPLEMENTATION 253 | * ==================== 254 | */ 255 | int gnl_cb_santa_msg_doit(struct sk_buff *sender_skb, struct genl_info *info) { 256 | char *recv_msg; 257 | struct nlattr *na; 258 | 259 | // check we got info in a good state 260 | if (info == NULL) { 261 | pr_err("An error occurred in %s():\n", __func__); 262 | return -EINVAL; 263 | } 264 | 265 | // We'll only accept messages from the pid from the daemon that checked in 266 | if (agent_pid > 0 && info->snd_portid != agent_pid) { 267 | pr_err("[%s]: message doesn't appear to be from the daemon, ignoring\n", KMOD_NAME); 268 | return 0; 269 | } 270 | 271 | // Get the attribute at the index indicated by the respective attribute enum (e.g. GNL_SANTA_A_MSG) 272 | na = info->attrs[GNL_SANTA_A_MSG]; 273 | if (!na) { 274 | pr_err("no info->attrs[%i]\n", GNL_SANTA_A_MSG); 275 | return -EINVAL; // we return here because we expect to recv a msg 276 | } 277 | 278 | // Read the data portion of the nlattr 279 | recv_msg = (char *) nla_data(na); 280 | if (recv_msg == NULL) { 281 | pr_err("error while receiving data\n"); 282 | } else { 283 | pr_info("received: '%s'\n", recv_msg); 284 | } 285 | return 0; 286 | } 287 | 288 | /** 289 | * ==================== 290 | * GNL MSG_CHECKIN CALLBACK HANDLER IMPLEMENTATION 291 | * ==================== 292 | */ 293 | int gnl_cb_santa_checkin_doit(struct sk_buff *sender_skb, struct genl_info *info) { 294 | struct sk_buff *reply_skb; 295 | int rc; 296 | void *msg_head; 297 | char resp_msg[MAX_PAYLOAD]; 298 | 299 | // check we got info in a good state 300 | if (info == NULL) { 301 | // should never happen 302 | pr_err("An error occurred in %s():\n", __func__); 303 | return -EINVAL; 304 | } 305 | 306 | // only accept messages from the daemon 307 | if (agent_pid > 0 && info->snd_portid != agent_pid) { 308 | pr_err("[%s]: message doesn't appear to be from the daemon, ignoring\n", KMOD_NAME); 309 | return 0; 310 | } 311 | 312 | // ensure it's the first checkin 313 | if (agent_pid < 0) { 314 | // update the agent_pid global if it is the first check-in 315 | agent_pid = info->snd_portid; 316 | strcpy(resp_msg, "CHECKIN-OK"); 317 | } else { 318 | pr_err("[%s]: ignoring bad check-in; the daemon has already checked-in", KMOD_NAME); 319 | return 0; 320 | } 321 | 322 | /* Send a message back */ 323 | // Allocate some memory, since the size is not yet known use NLMSG_GOODSIZE 324 | reply_skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL); 325 | if (reply_skb == NULL) { 326 | pr_err("An error occurred in %s():\n", __func__); 327 | return -ENOMEM; 328 | } 329 | 330 | // Create the message headers 331 | msg_head = genlmsg_put( 332 | reply_skb, // buffer for netlink message: struct sk_buff * 333 | info->snd_portid, // sending port (not process) id: int 334 | 0, // sequence number: int (might be used by receiver, but not mandatory) 335 | &gnl_santa_family, // struct genl_family * 336 | 0, // flags for Netlink header: int; application specific and not mandatory 337 | GNL_SANTA_C_MSG // The command/operation (u8) from `enum GNL_SANTA_COMMAND` 338 | ); 339 | if (msg_head == NULL) { 340 | rc = ENOMEM; 341 | pr_err("An error occurred in %s():\n", __func__); 342 | return -rc; 343 | } 344 | 345 | // Add a GNL_SANTA_A_MSG attribute (actual value/payload to be sent) 346 | rc = nla_put_string(reply_skb, GNL_SANTA_A_MSG, resp_msg); 347 | if (rc != 0) { 348 | pr_err("An error occurred in %s():\n", __func__); 349 | return -rc; 350 | } 351 | 352 | /* Finalize the message: 353 | * Corrects the netlink message header (length) to include the appended 354 | * attributes. Only necessary if attributes have been added to the message. 355 | */ 356 | genlmsg_end(reply_skb, msg_head); 357 | 358 | // Send the response 359 | rc = genlmsg_reply(reply_skb, info); 360 | if (rc != 0) { 361 | pr_err("An error occurred in %s():\n", __func__); 362 | return -rc; 363 | } 364 | return 0; 365 | } 366 | 367 | /** 368 | * ==================== 369 | * GNL MSG_HASH_DONE CALLBACK HANDLER IMPLEMENTATION 370 | * ==================== 371 | */ 372 | int gnl_cb_santa_hash_done_doit(struct sk_buff *sender_skb, struct genl_info *info) { 373 | // check we got info in a good state 374 | if (info == NULL) { 375 | // should never happen 376 | pr_err("An error occurred in %s():\n", __func__); 377 | return -EINVAL; 378 | } 379 | // only accept messages from the daemon 380 | if (agent_pid > 0 && info->snd_portid != agent_pid) { 381 | pr_err("[%s]: message doesn't appear to be from the daemon, ignoring\n", KMOD_NAME); 382 | return 0; 383 | } 384 | return 0; 385 | } 386 | 387 | // placeholder for example error reply handler 388 | int gnl_cb_doit_reply_error(struct sk_buff *sender_skb, struct genl_info *info) { 389 | // TODO: we should do something better here 390 | return -EINVAL; 391 | } 392 | 393 | 394 | /** 395 | * ==================== 396 | * CUSTOM GNL SANTA send_cmd() 397 | * ==================== 398 | */ 399 | static int gnl_santa_send_cmd(char *msg) { 400 | struct sk_buff *reply_skb; 401 | void *msg_head; 402 | int rc; 403 | 404 | // check if we know the agent PID yet, bail if not 405 | if (agent_pid < 0) { 406 | printk(KERN_ERR "agent has not checked in yet, don't know the PID. is it running?\n"); 407 | return -1; 408 | } 409 | 410 | // Allocate some memory, since the size is not yet known use NLMSG_GOODSIZE 411 | reply_skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL); 412 | if (reply_skb == NULL) { 413 | pr_err("An error occurred in %s():\n", __func__); 414 | return -ENOMEM; 415 | } 416 | 417 | // Create the message headers 418 | msg_head = genlmsg_put( 419 | reply_skb, // buffer for netlink message: struct sk_buff * 420 | agent_pid, // sending port (not process) id: int 421 | 0, // sequence number: int (might be used by receiver, but not mandatory) 422 | &gnl_santa_family, // struct genl_family * 423 | 0, // flags for Netlink header: int; application specific and not mandatory 424 | GNL_SANTA_C_MSG_DO_HASH // the command/op from the GNL_SANTA_COMMAND enum 425 | ); 426 | if (msg_head == NULL) { 427 | rc = ENOMEM; 428 | pr_err("An error occurred in %s(): after genlmsg_put\n", __func__); 429 | return -rc; 430 | } 431 | 432 | // Add a GNL_SANTA_A_MSG attribute (actual value/payload to be sent) 433 | rc = nla_put_string(reply_skb, GNL_SANTA_A_MSG, msg); 434 | if (rc != 0) { 435 | pr_err("An error occurred in %s(): after nla_put_string\n", __func__); 436 | return -rc; 437 | } 438 | 439 | // Finalize the message: 440 | genlmsg_end(reply_skb, msg_head); 441 | 442 | // Send the message back 443 | // see https://elixir.bootlin.com/linux/v5.8.9/source/include/net/genetlink.h#L326 444 | rc = genlmsg_unicast(&init_net, reply_skb, agent_pid); 445 | if (rc != 0) { 446 | pr_err("An error occurred in %s(): after genlmsg_unicast\n", __func__); 447 | return -rc; 448 | } 449 | return 0; 450 | } 451 | 452 | 453 | /** 454 | * ================================================================================================ 455 | * KPROBE SETUP 456 | * ================================================================================================ 457 | * The kprobe infrastructure is used to intercept calls to finalize_exec(), which 458 | * effectively allows us to intercept execve calls at the last part, once the exe 459 | * data has been read into memory and the exe/fs data structures flushed and updated. 460 | */ 461 | /* Symbol that will be probed and module param setup */ 462 | static char symbol[MAX_SYMBOL_LEN] = "finalize_exec"; 463 | module_param_string(symbol, symbol, sizeof(symbol), 0644); 464 | static struct kprobe kpr = { .symbol_name = symbol,}; 465 | 466 | /** 467 | * ======================== 468 | * KPROBE PRE_HANDLER: finalize_exec() 469 | * ======================== 470 | * Pre-handler for finalize_exec() 471 | */ 472 | static int handler_pre_finalize_exec(struct kprobe *p, struct pt_regs *regs) 473 | { 474 | // check if we know the agent PID yet, bail if not 475 | if (agent_pid < 0) { 476 | pr_err("[%s]: daemon hasn't checked in yet, skipping...\n", KMOD_NAME); 477 | return 0; 478 | } 479 | 480 | // send the message to the daemon 481 | char msg[16] = {0}; 482 | snprintf(msg, sizeof(msg), "%d", current->pid); 483 | int res = gnl_santa_send_cmd(msg); 484 | if (res != 0) { 485 | pr_err("[%s]: ERROR %s() ret=%d\n", KMOD_NAME, __func__, res); 486 | return 0; 487 | } 488 | return 0; 489 | } 490 | 491 | 492 | /** 493 | * ======================== 494 | * KPROBE FAULT HANDLER 495 | * ======================== 496 | * Pre-handler for finalize_exec() 497 | */ 498 | // fault handler 499 | static int handler_fault(struct kprobe *p, struct pt_regs *regs, int trapnr) 500 | { 501 | pr_info("[%s kprobe_FAULT] fault_handler: p->addr = 0x%px, trap #%dn", 502 | symbol, p->addr, trapnr); 503 | /* Return 0 because we don't handle the fault. */ 504 | return 0; 505 | } 506 | 507 | 508 | // KERNEL MODULE INIT 509 | static int __init hyperprobe_init(void) 510 | { 511 | // SET UP FOR PROBE 512 | // set the pre, post, and fault handlers (use NULL for optional ones) 513 | kpr.pre_handler = handler_pre_finalize_exec; 514 | kpr.post_handler = NULL; 515 | kpr.fault_handler = handler_fault; 516 | 517 | int ret = register_kprobe(&kpr); 518 | if (ret < 0) { 519 | pr_err("register_kprobe failed, returned %d\n", ret); 520 | return ret; 521 | } 522 | pr_info("Inserted kprobe at %px for symbol %s\n", kpr.addr, symbol); 523 | 524 | // SET UP FOR NETLINK 525 | pr_info("Initializing the netlink protocol for the module\n"); 526 | 527 | // register the family with its ops and policies 528 | int rc = genl_register_family(&gnl_santa_family); 529 | if (rc != 0) { 530 | pr_err("Error creating netlink socket\n"); 531 | return -10; 532 | } 533 | pr_info("santa-KMOD init succeeded!\n"); 534 | return 0; 535 | } 536 | 537 | // KERNEL MODULE EXIT 538 | static void __exit hyperprobe_exit(void) 539 | { 540 | unregister_kprobe(&kpr); 541 | pr_info("kprobe at %px for symbol %s unregistered\n", kpr.addr, symbol); 542 | int ret = genl_unregister_family(&gnl_santa_family); 543 | if (ret != 0) { 544 | pr_err("failed to unregister netlink proto: %i\n", ret); 545 | return; 546 | } 547 | pr_info("santa-KMOD netlink socket released\n"); 548 | } 549 | 550 | module_init(hyperprobe_init) 551 | module_exit(hyperprobe_exit) 552 | MODULE_LICENSE("GPL"); 553 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------