Welcome to the realm of enhanced digital security! In a world where online threats loom large, safeguarding your digital presence has never been more critical. In this exploration, we delve into the intricate mechanisms of 2-Factor Authentication (2FA) apps, unraveling the technology that serves as a robust security shield for your online world.

As we embark on this journey, our primary objective is to demystify the inner workings of 2FA applications, offering you a comprehensive understanding of the layers of protection they add to your digital life. From the fundamental principles to the advanced features, we aim to equip you with the knowledge necessary to fortify your accounts against the ever-evolving landscape of cyber threats.

Join us as we uncover the secrets behind how these apps operate, why they are indispensable in today’s digital landscape, and how they empower you with the tools to ensure the security of your online identity. It’s time to discover the shield for your online world and take control of your digital security.

Intricacies of OTP Generation and Validation

The other day, just like any other day, I logged into an online service by providing my email and password. After that, instead of receiving an OTP (One-Time Password) on my mobile, I noticed that my mobile data was turned off. However, I could still generate the OTP using Google Authenticator on my phone and successfully logged in.

Normally, you might be familiar with services that send OTPs via SMS. So, I assumed that 2-Factor Authentication apps like Google Authenticator probably also receive a real-time OTP from the server to ensure security. But, what I observed was quite intriguing! If there’s no internet connection, where does the app get the OTP? And again, if I generate the OTP myself, how does the server validate it? Is it magic?

No, it’s not magic. Time to get started and dive into the astonishing story behind this phenomenon.

Mechanism for 2-factor Authentication

Let’s kick things off with a bit of talk about the mechanism for 2FA or 2-factor Authentication security. Typically, the authentication processes we come across, like logging into an online service using email and password or utilizing social logins (think Facebook or Google), primarily fall under the category of 1-Factor Authentication. Essentially, it depends on something you ‘know’ – in this case, a piece of information.

social platforms
Social Platforms

However, to beef up security a tad more, another step is added. If you’ve ever conducted transactions at an ATM or with a card at the bank, you’re familiar with the drill. Here, your authentication involves two factors: ‘Something You Know,’ which is your PIN, and ‘Something You Have/Possess,‘ which is your card. This means that even if someone were to snag your card, they wouldn’t be able to do much without the PIN. Similarly, if someone manages to extract your PIN through social engineering, it’s futile without the physical card.

Why use 2-factor Authentication?

Now, many of us often resort to weak passwords for our accounts, or in the unfortunate event of an online service’s database getting hacked, user data may be pilfered. Since a lot of folks tend to use the same password across multiple services, a compromise in one place could jeopardize the security of other accounts for that user. In such scenarios where security is fragile, 2-factor Authentication, while not foolproof, can provide an extra layer of protection.

How 2FA works
How 2FA works

Let’s keep it real – many people jot down their PINs somewhere visible, and some even go as far as scribbling it on their ATM cards. Now, imagine if that card goes MIA – the whole setup crumbles, right?

In this digital age, it’s crucial to understand that while 2FA does add a valuable layer of security, it’s not a silver bullet. It’s more like an extra lock on your virtual front door. So, while you’re out there battling the digital forces, keep those passwords robust and your PINs under wraps – because in this tech-driven world, security is the name of the game. Stay savvy, dear!

Brass tacks about 2-factor Authentication Mechanism

Time to cut to the chase. When you first install the Authenticator app on your mobile to set up 2FA for a service, the service will provide you with either a token or prompt you to scan a QR code. This is the initiation process where the server shares a secret with the Authenticator app and also keeps that secret on your end. Later on, when generating OTPs, this secret comes into play.

After the initiation, 2FA Authenticator apps primarily generate OTPs in two ways. One is HOTP, and the other is TOTP.

HOTP (HMAC-based One-time Password)

In the HOTP (HMAC-based One-time Password) system, during the initialization step, the secret is immediately shared with a Counter, which is also shared with the server app. Let’s assume this Counter starts at 1. Later, when you open the app to generate a token, the secret and Counter combine to create a hash, yielding a fixed-digit (usually 6-10 digits) OTP.

This OTP generation process happens entirely within the app, with no need for communication with the server. Now, when you input this OTP into the service you’re logging into, the server follows the same process of OTP generation using its stored secret and Counter. Since both the server and the app use the same algorithm and possess the same token and Counter, they generate the same OTP. Therefore, no communication during OTP generation is necessary.

The real kicker here is that each time you generate an OTP in the app, the Counter is incremented. Similarly, when the server verifies an OTP, it also increases its Counter. But here’s the catch – if you generate an OTP in the app and don’t use it, the app’s Counter keeps advancing. The next time you generate an OTP, your app’s Counter won’t match the server’s Counter. To tackle this, the server intelligently tries a limited number of OTPs (maybe 10 or 20) within a specified range.

Additionally, the server occasionally checks with your app, using a token to retrieve its current Counter, ensuring synchronization between them.

TOTP (Time-based One-time Password)

In TOTP, the process is quite similar to HOTP, with the only difference being that here the Counter is the Current Time. This means the Secret is combined with the Current Unix Time to generate the OTP. If you’re as clever as I am, you might be thinking, “Okay, if I generate an OTP in the app and later check it with the server, the OTP will be generated at different times. So, they won’t match exactly. What’s the deal?

Well, now, you’ve got it right. It’ll work just fine for you. I was looking for an attentive reader like you. To address the issue you’re thinking about, during TOTP generation, tokens are typically generated every 30 or 60 seconds. Let me simplify it a bit. The straightforward formula for TOTP generation is somewhat like this:

Time Counter = floor(Current Time since Unix Epoch / 30)

Suppose the Current Time is 1556293816. When you divide it by 30 and round it down mathematically, you get the Counter. Even if the Current Time changes to 1556293826 (10 seconds later), you’ll still get the same Counter. This ensures the Counter remains the same within a 30-second window. Therefore, even if you validate the generated OTP with the server a few seconds later, there won’t be any problem.

Time for an Anecdote!

Once in a gathering, Huzur (a wise figure) said, “There is a very peculiar tree. When its leaves fall on the ground, it turns into a tiger, and when they fall into the water, they become fish.” Hearing this, a person from Noakhali stood up and said, “Huzur, if the tree has half its leaves in the mud and the other half in the water, what will happen?” 

Anyway, since my home is also in Noakhali, I thought of you when I saw this TOTP process. After all, your clever mind might be pondering, “If I generate an OTP in the app, and then go to the server to check it, the OTP will be generated at different times, so the two will not exactly match. What’s the solution?” 

That’s why, during TOTP generation, the OTP typically changes a few seconds after being generated, providing a time buffer. So, no worries, it’s like a double OTP. 

Anyway, that’s a lot said. I hope you’ve grasped how Authenticator apps manage to function without real-time communication with the server or even when offline.

Integrating 2-factor authentication

I mainly integrated 2FA with a Laravel application a few months ago. In this scenario, a user, upon being logged in for the first time, enables the 2-Factor Authentication security mechanism from their account.

generating qr code and secret code for 2fa app
Generating QR Code And Secret Code For 2FA App

Then, when attempting to log in—meaning, after providing the correct login credentials—the user is directed to a page to submit a 2FA code. Until this authentication code is correctly submitted, the user won’t gain access to their account.

login screen
Login Screen
2fa otp verification screen
2FA OTP Verification Screen

Implementation insights

Firstly, I used a composer package pragmarx/google2fa . This package typically generates a secret key for 2FA and immediately creates a QR code for this secret key.

Then, I utilized the following code snippet to generate an authentication secret code for the user.

$google2fa = app('pragmarx.google2fa');
$google2fa_secret = $google2fa->generateSecretKey();

After generating the secret code, I created a QR code for the user by providing the application name, the user’s email address, and the generated secret key.

$QR_Image = $google2fa->getQRCodeInline(config('app.name'),$user->email,$google2fa_secret);

Finally, I updated the user’s record in the database with the generated secret code with encrypting it.

$encrypted_secret_code = encrypt($google2fa_secret);
//Updating in database for specific user
$this->updateUserSettings($encrypted_secret_code,true,$user);

Now, the user needs to validate the two-factor authentication code. For the validation process after user login, I used the following approach:

$google2fa = app('pragmarx.google2fa');
$google2fa_secret = decrypt($admin->google2fa_secret);
 if ($google2fa->verifyKey($google2fa_secret, $request->input('code'))){
       return true;
 } else{
        return false;
}

This approach validates the user-inputted two-factor authentication code against the stored secret key. If the code is valid, the login proceeds; otherwise, appropriate actions are taken.

Conclusion

In summary, the implementation of 2-Factor Authentication (2FA) in our Laravel application enhances user security by adding an extra layer of protection beyond passwords. The integration involved using the “pragmarx/google2fa” package to generate secret keys and QR codes for user setup. This approach significantly reduces the risk of unauthorized access, offering users a more robust and secure experience. Embracing such security measures is crucial in the ever-evolving landscape of web security. If you have any questions, feel free to drop them in the comments.

This page was last edited on 20 February 2024, at 5:12 pm