gGamma CTF

This was a capture the flag project at my university (AUB), provided by Dr. Hussein Bakri, the creator of this CTF.

Table of Contents:

  1. Scanning

    • TCP Scan

    • UDP Scan

  2. Port 80

    • Directory Brute-Forcing (Gobuster)

    • Web server Vulnerability Scanning (Nikto)

    • Source Code Inspection

    • Steganography

    • Admin Login

    • Exploiting File Upload

    • Initial Foothold (www-data)

  3. Privilege Escalation

    • Linpeas

    • Manual Privilege Escalation Techniques

    • Kernel Exploit

    • Root Flag

  4. Other Attack Vectors

    • Trying other Privilege Escalation Exploits

    • Nessus Scan

    • Exploring Other Ports

  5. Remediations and Recommendations for Machine Owner

  6. References

1- Scanning

TCP

Results

Ports Open:

Aggressive Scan on Open Ports

Results:

UDP

Results:

Vulnerability Scanning

Results:

2- Port 80

Gobuster

Results:

Important Directories:

Nikto

Results:

Firefox

Now, lets open the website on firefox:

Lets visit "http://192.168.229.158"

Source code:

Source code for "http://192.168.229.158" After deeply inspecting the source code, nothing seems suspicious.

/administrator

Now, lets check the source code for this directory, which appeared in 'nikto' and in 'gobuster':

Login Page:

Source Code:

There is an important comment in the source code, which is: " Find the image hidden around, Do you know steganography in images bud? "

/images

Lets now move onto the /images directory, since steganography is likely present as mentioned in the hint above.

Flag.txt found!

Lets read its content.

Flag.txt: "Almost there!

Odin is the god of wisdom. He bestoys "hidden" knowledge that only the initiate can know. Did you notice something hidden in its image?

Dr. Hussein Bakri "

Hint: There is something hidden in odin's image.

In this directory also, we can see that there is a png file named OdinHiddenKnowledge.png.

Lets check it out:

Steganography

Lets now download this image to out attacker machine, in order to do some steganography, and find what is hidden inside it.

exiftool

strings

nothing seems suspicious

steghide

binwalk

Important things found here:

  • A PNG starting at 0x0.

  • ZLib compressed data at 0x29.

  • A suspicious header at 0x4661.

Lets now extract them:

Result:

Lets check this directory: OdinHiddenKnowledge.png.extracted_

Results:

  • There is an empty file 29.

  • There is a zip file 29.zlib.

Lets check the contents of 29.zlib:

result:

Lets decompress this zip:

Nothing important.

zsteg

Results:

There is an EXTREMELY important hint:

Hint: "godofhacking is HusseinBakri. This incantation allows you access for sure"

Lets try those as credentials in the /administrator.

username: godofhacking password: HusseinBakri

And........ we are in!

File Upload

Lets try now to upload a php reverse shell.

Note: We still need to know where those uploads go to.

From pentest monkey, I downloaded a reverse shell, and modified the port and the ip.

Now, lets try to upload the reverse shell.

When I pressed on submit, it redirected me to this page:

So, I wasn't able to upload.

Lets see what is the cause of this problem.

Lets try to rename my file from pentest_monkey_php_reverse_shell.php to pentest_monkey_php_reverse_shell.php.jpg, and try to re-upload.

Still, not working.

Lets try renaming it to .phtml and .php3 and .png.

  • phtml didn't work.

  • php3 didn't work also.

  • png also didn't work.

Before I move onto burp suite, for one last time, I am going to upload a true png file, and a true jpg file, to confirm that uploading isn't working.

... and yes, both also didn't work.

Lets try our luck and SSH into the machine using those credentials:

username: godofhacking password: HusseinBakri

Didn't work.

Before we move on, this seems suspicious: ff4085ad157354dc8ea67a848e7c2270b4a19282713cf3a7ecf8e0ffbb159ed1

It is found here in the source code:

And, when I upload a file, it takes me to "http://192.168.229.158/administrator/ff4085ad157354dc8ea67a848e7c2270b4a19282713cf3a7ecf8e0ffbb159ed1.php"

This looks like a hash.

Lets visit this website "https://hashes.com/en/decrypt/hash", and decrypt it to see if it contains something useful.

Output: `ff4085ad157354dc8ea67a848e7c2270b4a19282713cf3a7ecf8e0ffbb159ed1:upload

Nice. So this hash is upload.

I will try to append upload to the url, and try to reupload.

The resulting url: http://192.168.229.158/administrator/husseinbakri.php/upload

Lets try to re-upload the reverse shell file:

The site says: The image format must be jpg,jpeg,gif,png

Lets change the extension to .jpg.php:

Upload Success (Top left).

What we have to do now is trigger a reverse shell.

Before that, I noticed that everything works after /administrator, what I mean by this, is if I write http://192.168.229.158/administrator/husseinbakri.php/test for example, I can upload a file, and it works.

So, now, lets trigger this reverse shell:

I tried entering http://192.168.229.158/administrator/husseinbakri.php/reverse_shell.jpg.php, but didn't work.

I then searched in all the directories that were previously found, such as images, vendor..., but also the reverse shell wasn't there.

However, I noticed something important. When I was uploading in http://192.168.229.158/administrator/husseinbakri.php/, it was taking me to this url: "http://192.168.229.158/administrator/ff4085ad157354dc8ea67a848e7c2270b4a19282713cf3a7ecf8e0ffbb159ed1.php"

So, what I did now, is I edited the url, and renamed it to "http://192.168.229.158/administrator/reverse_shell.jpg.php".

and boom! It worked!

In the meantime, a netcat session was opened with:

Now, lets upgrade the connection using:

3- Privilege Escalation

Enumerating www-data

Lets do some enumeration, since now we have our initial foothold on the machine:

Kernel:

Files:

Lets check usernames on the system:

Username found: exploiter

SSH Bruteforce

Since we found a username named exploiter, lets try to bruteforce into ssh.

Result:

Nothing found in the first 2286 tries...

Linpeas

Now, i will upload linpeas from my host machine to the vulnerable machine.

On my host machine (In the directory that contains linpeas.sh):

On the target machine, lets go to the /tmp directory and download linpeas.sh:

Making the script executable:

Running linpeas:

Important things found from linpeas.sh"

  • The sudo version (1.8.19p1) on the system may be vulnerable to the "Baron Samedit" exploit.

  • Exploit CVE-2021-4034 ("PwnKit"); This is a known privesc vulnerability in pkexec (part of Polkit). The system appears vulnerable to it.

  • The /usr/share/openssh/sshd_config file is world-readable.

  • The /tmp folder is writable, and LinPEAS has identified writable files owned by www-data and others in /tmp and /var/tmp.

  • Several cron jobs are running, and /etc/cron.daily, /etc/cron.weekly, and similar directories are populated.

  • Several SUID binaries (/usr/bin/pkexec, /usr/lib/snapd/snap-confine) are present.

  • A .bash_history file is available for the apache2 user.

Exploit db

3 exploits found for our ubuntu version:

Manual Privilege Escalation

SUID

Result:

I searched for each one on GTFOBins, but nothing useful was found.

Sudo

Lets check which commands can be run with sudo without password:

We dont have the password of www-data, so this doesnt work.

Capabilities

Lets go to GTFOBins and check if this is found.

There is only "File read" and "Sudo".

So, this didn't work also.

Cronjobs

Results:

Lets check the cron.hourly:

We can't edit any of those.

Lets move to another method.

Kernel

We found previously by the command uname -r, that the kernel version is 4.10.0-19-generic.

Lets search on searchsploit for vulnerabilities associated with this version.

Results:

Lets try this one:

Lets copy it first to our current directory:

Now, lets move the exploit to the target machine:

On our attacker machine, lets start an http server:

On the netcat session:

Lets now compile the exploit:

Making it executable:

Running it:

Result:

And we are root!

Lets now upgrade the shell:

Lets seach now for the flag

Result:

Result:

So the root flag is: flag{2893d890e8847d5575ac33229a037ca4}.

4- Extra Attack Vectors

Privilege escalation

First one

Lets re-check the kernel version:

Now, Lets search on searchsploit for any other exploits:

Results:

There is one that caught my attention:

Our kernel version is in this range. Lets try it out.

First, lets check the exploit to see if there are any needed modifications before we run the exploit on the vulnerable machine.

There is this line: gcc -m32 -static -o exploit exploit.c

So, we need this compiler. I asked Chat GPT for the compiler:

ChatGPT output:

So, I did this command, and compiled the exploit:

Now, lets move this exploit to the vulnerable machine:

On our attacker machine, lets start an http server on port 8080:

On the nc session, lets run:

Result:

It didn't work.

Second One:

Our ubuntu version is 17.04

Lets try another exploit from exploit db.

In exploit-db website, lets type ubuntu 17.04

This is the exploit, lets check out the code before we try it.

Lets now transfer it to the vulnerable machine.

On the attacker machine, lets open an http server:

On the Target machine, lets go to the /tmp directory.

Note: ChatGPT helped with this command:

Lets now run the exploit:

Didn't work.

Nessus Scan

Lets Specify the IP:

Launching Scan:

Results:

1- JQuery 1.2 < 3.5.0 Multiple XSS

https://blog.jquery.com/2020/04/10/jquery-3-5-0-released/

https://security.paloaltonetworks.com/PAN-SA-2020-0007

2- SSH Terrapin Prefix Truncation Weakness (CVE-2023-48795)

https://terrapin-attack.com/

Those were the main 2 vulnerabilities found.

Other Ports

SSH

Scan:

Results:

Version: OpenSSH 7.4p1 (Ubuntu 10) This is an older version of OpenSSH, and it may have known vulnerabilities that could be exploited.

CVE-2018-15473

This exploit targets openSSH < 7.7 - user enumeration. Steps:

Lets Download the Exploit:

Lets now Create a python Virtual Environment to install dependencies:

Now, lets run the exploit to check if www-data and root are valid users:

Bruteforce SSH

Since we now know that www-data and root are valid users, we'll run a bruteforce attack on ssh:

Result:

Unfortunately, it didn't work on www-data.

Now, Lets try on root.

Result:

Also, didn't work.

OpenSSH < 6.6 SFTP - Command Execution

We first check the code. It needs username: password. Since we don't know them, we can't use this exploit.

CVE-2016-10009

Following the steps in the CVE:

Lets compile the code:

Lets connect to another machine using "ssh -A". Then, on the remote machine:

To do the above, I sent the code to the other machine using the exploited port 80 using http.server, so now the compiled evil_lib.so is on the target machine.

Now we run the code as specified:

It didn't work.

Port 5355

Looked for exploits of port 5355 on exploit-db. None found. Searched the web for "port 5355 vulnerabilities". No exploits found. Using searchsploit:

Port 68

  • Looked for exploits of port 68 on exploit-db. None found.

  • This might be relevant: (source: https://www.sonicwall.com/blog/cve-2018-1111- network-manager-command-injection-vulnerability)

Further examining this CVE, it specifically targets Red Hat-based distributions and their dhclient implementation. Ubuntu 10 (or any Debian-based distribution) does not use the same vulnerable script mechanism in dhclient, so this exploit would not work directly on Ubuntu 10.

Since we have access to the machine from exploiting port 80, I checked the version of dhclient to see what are some relevant vulnerabilities:

Run searchsploit:

5- Remediations and Recommendations for Machine Owner

Passwords

What Makes a Password Strong?

In today's digital age, hackers have advanced tools that can crack weak passwords in seconds. To stay secure, your password needs to be unique, complex, and not tied to your personal information.

How to Create a Secure Password

  • Complexity is Key:

A strong password should have at least 16 characters, mixing uppercase and lowercase letters, numbers, and symbols. For example: MySecureP@ssw0rd2024!.

  • Avoid Personal Information:

Don’t use your name, birthday, or anything linked to your identity like in the exploited machine the password is a name "HusseinBakri".

  • Passphrases Work Wonders:

Use memorable yet random sentences. Instead of a random mix, try something like:

"ILoveToTravelInItaly2024!".

It's long, personal to your hobbies, and easy for you to recall but tough for hackers to guess.

Server-Side Fix to Prevent .jpg.php Uploads

  1. Server-Side File Type Validation

First, ensure that the backend performs strict validation on the MIME type of the file. In your jQuery backend (if you’re using a backend written in PHP or Node.js, for example), check the MIME type to confirm the uploaded file is indeed an image and not a disguised PHP script.

Here’s a basic example using PHP to validate uploaded files:

// Get the MIME type of the uploaded file $fileMimeType = mime_content_type($_FILES['fileInput']['tmp_name']); // Only allow image MIME types $allowedMimeTypes = ['image/jpeg', 'image/png']; if (!in_array($fileMimeType, $allowedMimeTypes)) { die('Invalid file type. Only JPEG and PNG files are allowed.'); }

  1. Check File Extensions and File Content

Don't rely only on the file extension (e.g., .jpg.php) as attackers can easily manipulate file names. Use functions that inspect the file's content because in our case we put a reverse shell that give us an access to the machine , so if the content of the uploaded file was inspected, the risk of exploiting the machine will be reduced. For instance, ensure that .php scripts are not uploaded by checking the first few bytes of the file content.

Example in PHP:

$fileContent = file_get_contents($_FILES['fileInput']['tmp_name']); if (strpos($fileContent, '<?php') !== false) { die('File contains PHP code. Upload rejected.'); }

  1. Disable Script Execution in Upload Directory

You can configure your server to disallow the execution of any PHP files in the upload directory because in our case when we upload the reverse shell we execute it. If you’re using Apache, for example, you can add this to the .htaccess file:

<FilesMatch "\.(php|phar|phtml)$"> Deny from all </FilesMatch>

For Nginx, you can use the following directive in your configuration:

nginx

location /uploads/ { deny all; location ~ \.php$ { return 403; } }

  1. Set Proper File Permissions

Ensure that uploaded files have restrictive permissions so they can't be executed. For example:

chmod 0644 /path/to/uploads/*

  1. Integrating with jQuery for Upload Handling

The jQuery backend code will handle the validation and also help prevent malicious file uploads so this can reduce the exploitation of the machine like we did. Here's how you can modify the jQuery code to support secure file upload:

$(document).ready(function () { $('#uploadForm').on('submit', function (e) { let fileInput = $('#fileInput')[0].files[0]; // Check if a file is selected if (!fileInput) { alert('Please select a file to upload.'); e.preventDefault(); return; } // Validate file extension let allowedExtensions = /(\.jpg|\.jpeg|\.png)$/i; if (!allowedExtensions.exec(fileInput.name)) { alert('Invalid file type. Please upload a .jpg or .png file.'); e.preventDefault(); return; } // Optional: File size limit (e.g., 2MB) if (fileInput.size > 2 * 1024 * 1024) { alert('File size exceeds the 2MB limit.'); e.preventDefault(); return; } alert('File validated. Uploading...'); }); });

Steps to Prevent Privilege Escalation:

  1. Upgrade the Operating System:

- The Ubuntu 17.04 ( OS of the exploited machine ) reached its end of life (EOL) in January 2018, meaning it no longer receives security updates.

- Action: Upgrade to a currently supported version of Ubuntu (e.g., Ubuntu 22.04 LTS or later).

- Why: Supported versions receive regular updates, patching critical vulnerabilities automatically.

  1. Keep the System Updated:

- Regularly apply updates using the following commands:

``` sudo apt update

sudo apt upgrade -y

sudo apt dist-upgrade -y ```

  1. Upgrade the Kernel:

The privilege escalation step is performed using kernel exploitation, and this because the kernel is not up to date so it had a potential to be exploited.

Consider upgrading the Linux kernel to a more secure and supported version:

sudo apt install --install-recommends linux-generic-hwe-22.04

  1. Implement Security Best Practices:

- Enable Automatic Security Updates:

``` sudo apt install unattended-upgrades

sudo dpkg-reconfigure -plow unattended-upgrades ```

- Limit Privileged Access:

- Review user accounts with administrative privileges.

- Use sudo responsibly and restrict administrative commands.

  1. Enable Kernel Hardening:

- Use the following security modules:

- AppArmor: Pre-installed in Ubuntu, enforce it with:

```bash

sudo systemctl enable apparmor

sudo systemctl start apparmor

```

- SELinux: Consider using SELinux for additional protection.

- Enable key kernel protection settings in /etc/sysctl.conf:

```

kernel.randomize_va_space=2 # Enable Address Space Layout Randomization (ASLR)

kernel.kptr_restrict=2 # Hide kernel pointers

```

  1. Apply Mandatory Access Control (MAC) Policies:

- Implement restrictive permissions using tools like AppArmor, SELinux, or Grsecurity. So when we need to access anything we need permission and this reduce the potential of taking directly the session like we do in our exploit.

Business Impact

Failing to address outdated operating systems and kernels could lead to severe data breaches, ransomware attacks, and compliance violations. Upgrading ensures a more secure, stable environment with reduced attack surfaces.

Priority: High

Due to the critical nature of kernel exploitation vulnerabilities, immediate action is required to prevent potential compromises.

Preventing Information Leaks from Image Files

  1. Avoid Embedding Sensitive Data in Media Files

- Refrain from embedding sensitive data such as credentials, personal details, or secret keys within image files or other media. Instead, use secure storage mechanisms specifically designed for sensitive data like in the exploit machine we use the image OdinHiddenKnowledge.png to gather username and password information so we conclude that the username is: "godofhacking" and the password is: "HusseinBakri"

- Why: Hidden data can be extracted using steganographic analysis tools like zsteg, potentially exposing critical information. ( like we did in the exploit machine)

  1. Scrub Metadata Before Sharing Files

- Remove metadata from images using tools such as ExifTool to prevent information leaks, including file creator details, GPS coordinates, and device information.

- Example Command:

exiftool -all= filename.png

- Why: Metadata often contains sensitive information that could be used for reconnaissance or targeted attacks.

  1. Use Encryption for Sensitive Data Storage

- If hiding information in files is unavoidable, ensure it is securely encrypted using strong encryption algorithms (e.g., AES-256) and that access is restricted.

- Why: Encryption ensures that even if data is extracted, it cannot be accessed without decryption keys.

  1. Conduct Regular Security Assessments

- Perform regular security assessments, including file content analysis, metadata inspection, and steganographic testing, to detect and mitigate potential hidden data leaks. So we prevent that the information leakage again (like in the the exploited machine).

- Why: Continuous monitoring helps identify vulnerabilities before they can be exploited.

  1. Employee Awareness and Training

- Educate employees and collaborators about the risks of embedding or inadvertently leaving sensitive information in image files. Include security best practices in onboarding and ongoing training sessions.

- Why: Human error is a leading cause of data exposure. Training reduces this risk by fostering security awareness. Also in the exploited machine it can be a human error that forgot to remove useful information.

Business Impact

Information leaks from image files can lead to data breaches, reputational damage, and regulatory fines if sensitive data is exposed. Implementing the recommended practices helps ensure the privacy and security of critical data shared internally or externally.

Priority: Medium to High

Depending on the nature of the data being shared, this issue can range from moderate to critical. Immediate action is recommended for environments handling sensitive or confidential data.

6- References

  • Dr. Hussein Bakri Lecture Notes

  • Chatgpt

  • https://blog.jquery.com/2020/04/10/jquery-3-5-0-released/

  • https://security.paloaltonetworks.com/PAN-SA-2020-0007

  • https://terrapin-attack.com/

  • https://www.exploit-db.com/search

  • https://crackstation.net/

  • https://pentestmonkey.net/cheat-sheet/ssh-cheat-sheet

  • https://thehackernews.com/2024/11/decades-old-security-vulnerabilities.html

  • https://ubuntu.com/security/notices/USN-5355-1

  • https://medium.com/@nirvana.elahi/title-llmnr-link-local-multicast-name-resolution-exploring-its-functionality-vulnerabilities-407fb69fb509

  • https://privsec.harvard.edu/use-strong-passwords

  • https://www.bu.edu/tech/support/information-security/security-for-everyone/how-to-choose-a-strong-password/

  • https://www.one.com/en/website-security/create-a-secure-password

  • https://docs.kernel.org/security/self-protection.html

  • https://www.briskinfosec.com/blogs/blogsdetail/How-hackers-bypass-file-upload-and-how-to-prevent-it-

  • https://blog.devsecopsguides.com/file-upload-vulnerabilities

  • https://www.exploit-db.com/exploits/42275

Last updated