GithubHelp home page GithubHelp logo

robthree / twofactorauth Goto Github PK

View Code? Open in Web Editor NEW
1.0K 49.0 128.0 392 KB

PHP library for Two Factor Authentication (TFA / 2FA)

License: MIT License

PHP 100.00%
qrcode php two-factor twofactorauth totp multi-factor security

twofactorauth's People

Contributors

andrej-griniuk avatar anvyst avatar brainfoolong avatar cedric-anne avatar fman42 avatar igorsantos07 avatar jonathantru avatar masterodin avatar mattie112 avatar modelrailroader avatar nicolascarpi avatar rmengels avatar robthree avatar savagecore avatar thomascorthals avatar willpower232 avatar xheaven avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

twofactorauth's Issues

Flaky test

It would be good to figure out how we can resolve the flaky test but hopefully everyone can see it passes sometimes!

I haven't had this flakiness happen locally so its likely to be the runner time being behind the time values returned by the various remote services.

A bypass to this problem could be to use a remote service as the default time provider for that instance of TwoFactorAuth but that would leave the actual default provider untested.

Thoughts @RobThree ?

Exception when code type is integer (expected string)

Actual behavior

While passing code parameter to verifyCode function and the code parameter is integer type the function crashes.

Expected behavior

verifyCode function verifies the code which is provided as integer.

Code to reproduce

$tfa = new RobThree\Auth\TwoFactorAuth("TEST");
$tfa->verifyCode("USJNHRTSCEAY2OME6IB7CLEE6HACYQGN", 123123);


Workaround

$tfa = new RobThree\Auth\TwoFactorAuth("TEST");
$tfa->verifyCode("USJNHRTSCEAY2OME6IB7CLEE6HACYQGN", (string) 123123);

Edit.

In case of the code starting by 0 the verifyCode function should prepend missing zeros based on the code generation length or drop the leading zeros from internal code generation. OR maybe just switch completely to integers as working with them is faster than strings = less cpu ticks = less co2 emission ๐Ÿšญ

Cached time from external time providers

I tried the demo and noticed that for the first time it ran correctly, but then after refresh it started complaining about mismatched times from convert-unix-time.com. I tracked it down to the request to the external website being cached. To prevent caching in curl you can add header Cache-Control: no-cache (https://stackoverflow.com/a/36043573/4088846) or add a random suffix to the url when calling file_get_contents (https://stackoverflow.com/a/21755086/4088846). Why are you not reusing the part from HttpTimeProvider anyway?

Location of MyProvider class when using phpqrcode and composer

Am loving the fact that this is so easy to use, many congratulations sir.

I have one question regarding the MyProvider.php class location when using PHPQRCode as per qr-code-providers

  1. I've placed the phpqrcode.php file in the same (composer) folder as TwoFactorAuth.php (./vendor/robthree/twofactorauth/lib)

  2. I've created the MyProvider.php file in the Providers/Qr folder (./vendor/robthree/twofactorauth/lib/Providers/Qr/MyProvider.php).

    1. The notes refer to that file named as myprovider.php when creating it, but I believe it should be MyProvider.php?
    2. I also believe that the namespace should be placed above the require/require_once?
  3. I've then taken your demo page, added my composer autoload.php to it and tried to get it working, but every time I attempt to run it, I get a missing phpqrcode.php file

Warning: require_once(../../phpqrcode.php): failed to open stream: No such file or directory in /var/www/vendor/robthree/twofactorauth/lib/Providers/Qr/MyProvider.php on line 3

Fatal error: require_once(): Failed opening required '../../phpqrcode.php' (include_path='.:/usr/share/php:/var/www/html/inc') in /var/www/vendor/robthree/twofactorauth/lib/Providers/Qr/MyProvider.php on line 3

  • Am I missing something really obvious here?

  • Should I not have placed those files in the vendor folder, but elsewhere in my application?

  • I've attached a screenshot of my vendor folder structure in the hope that assists?
    Screenshot from 2020-04-27 11-34-20

Fatal error: Uncaught Error: Call to undefined function RobThree\Auth\Providers\Time\socket_create()

And another one... but here I'm a bit confused about this error as it should be catch actually?

Fatal error: Uncaught Error: Call to undefined function RobThree\Auth\Providers\Time\socket_create() in /www/htdocs/xxxxxx/mydomain.tld/ssh/libs/googleauthenticator/vendor/robthree/twofactorauth/lib/Providers/Time/NTPTimeProvider.php:46 Stack trace: #0 /www/htdocs/xxxxxx/mydomain.tld/ssh/libs/googleauthenticator/vendor/robthree/twofactorauth/lib/TwoFactorAuth.php(236): RobThree\Auth\Providers\Time\NTPTimeProvider->getTime() #1 /www/htdocs/xxxxxx/mydomain.tld/ssh/libs/googleauthenticator/demo.php(38): RobThree\Auth\TwoFactorAuth->ensureCorrectTime() #2 {main} thrown in /www/htdocs/xxxxxx/mydomain.tld/ssh/libs/googleauthenticator/vendor/robthree/twofactorauth/lib/Providers/Time/NTPTimeProvider.php on line 46

with this code (from demo.php):

require_once 'vendor/autoload.php';
use \RobThree\Auth\TwoFactorAuth;

$tfa = new TwoFactorAuth('My Company');

    echo '<li>First create a secret and associate it with a user';
    $secret = $tfa->createSecret(160);  // Though the default is an 80 bits secret (for backwards compatibility reasons) we recommend creating 160+ bits secrets (see RFC 4226 - Algorithm Requirements)
    echo '<li>Next create a QR code and let the user scan it:<br><img src="' . $tfa->getQRCodeImageAsDataUri('My label', $secret) . '"><br>...or display the secret to the user for manual entry: ' . chunk_split($secret, 4, ' ');
    $code = $tfa->getCode($secret);
    echo '<li>Next, have the user verify the code; at this time the code displayed by a 2FA-app would be: <span style="color:#00c">' . $code . '</span> (but that changes periodically)';
    echo '<li>When the code checks out, 2FA can be / is enabled; store (encrypted?) secret with user and have the user verify a code each time a new session is started.';
    echo '<li>When aforementioned code (' . $code . ') was entered, the result would be: ' . (($tfa->verifyCode($secret, $code) === true) ? '<span style="color:#0c0">OK</span>' : '<span style="color:#c00">FAIL</span>');
    ?>
</ol>
<p>Note: Make sure your server-time is <a href="http://en.wikipedia.org/wiki/Network_Time_Protocol">NTP-synced</a>! Depending on the $discrepancy allowed your time cannot drift too much from the users' time!</p>
<?php
try {
    $tfa->ensureCorrectTime();
    echo 'Your hosts time seems to be correct / within margin';
} catch (RobThree\Auth\TwoFactorAuthException $ex) {
    echo '<b>Warning:</b> Your hosts time seems to be off: ' . $ex->getMessage();
}

Google / MS Authenticator

I write this hesitatingly as I'm not convinced that this is an issue with this code or not, but would like to throw out issues that we've started experiencing over the past few weeks. We use this library (1.7.0)to generate and authenticate using a QR code only but have experienced the following when using Google Authenticator (GA), Microsoft Authenticator (MA) and Duo (D).

  1. If a user is using an Android phone, GA, MA and D all work flawlessly when presented with the QR code and entering the PIN.
  2. If a user is using an IOS phone, then GA regularly has issues. MA and D work OK

Due to (2) we've been using both an IOS and Android based device to scan the same QR code, and using all three authenticators. The results are haphazard and don't appear to be following any logic, but we experience

  1. Sometimes IOS with GA manages to scan the code without any issues at all
  2. Sometimes IOS with GA scans the QR code but when entering in the same PIN as Android shows, the PIN gets rejected
  3. Sometimes IOS with GA scans the QR code but shows a completely different PIN as the Android does

All servers have NTP configured and checks no more than every 30 sec intervals. The devices themselves are configured in the same timezone and we've confirmed that their system times are within 1sec of each other.

So - I'm at a bit of a loss. I appreciate that we're not using the latest version but I find it odd that all of a sudden we've started seeing these issues. Yes I appreciate that it might be a problem with GA, but thought I would check in here first to see if this was a known issue (I didn't find anything) and there's nothing like getting advice from the horses' mouth, as it were.

Auth code is always true when the period time is over

Hi @RobThree ,
When I'm using your lib, I founded that if the period time is over, The auth code before still valid (attached video).
https://streamable.com/qdqvy

<?php
require_once __DIR__ . '/vendor/autoload.php';
$tfa = new RobThree\Auth\TwoFactorAuth('My Company');
$secret = 'NEJT2GA4E2A7M534';
echo $secret;
?>
<p><img src="<?php echo $tfa->getQRCodeImageAsDataUri('Khuyen Nguyen', $secret); ?>"></p>
<?php
$code = '326055'; //613491
$isValid = $tfa->verifyCode($secret, $code);
echo '<br>';
if ($isValid) {
    echo 'Valid';
} else {
    echo 'Invalid';
}

Please correct me.

Best storage type for secret in database

Hi!

Sorry if this is not the right place for it, but I would like to know which is the best datatype to save the secret in my db (I'm using Mysql).

These are my configs:
digits = 6, period = 60, algorithm = sha1.

Thanks!

Everything works fine until I change qrcode provider as suggested....

Does anyone have idea what could be wrong ?
I've downloaded phpqrcode.php saved it into same directory as 2factorauth as suggested , saved myprovider.php as suggested but getting error

Fatal error: Interface 'RobThree\twofactorauth\lib\Providers\Qr\IQRCodeProvider' not found in C:\xampp\htdocs\loginsystem\security.php on line 8

Any suggestion much appreciated!

Luka

CURLOPT_FOLLOWLOCATION and open_basedir

Hey, great work on the library, we've been testing it and it seems to be pretty robust. We ran into a minor issue and I'd like to propose a change:

Basically, BaseHTTPQRCodeProvider crashes if the open_basedir php directive is set, and it doesn't appear that a workaround exists:

http://stackoverflow.com/questions/19539922/php-can-curlopt-followlocation-and-open-basedir-be-used-together

And while "just turn the directive off" can be a solution for some, like the thread there suggests it can be a security liability to get rid of it. So I would vote to remove CURLOPT_FOLLOWLOCATION from the class, unless there's a compelling reason to keep it. Google Charts seems to work fine at least without redirects.

QRCode Redirect

Is there anyway to setup custom redirect for scanned QR Codes?

Thoughts about type hinting and supporting old php versions

Hello,

First, thank you for providing this library, I use it in my project: eLabFTW: the open source lab notebook โค๏ธ

I see that the minimum version for php is 5.6. Does it really makes sense to support a version that has been out of the game for 2 years now?

See my arguments:

By requiring a modern php version you push admins to update their stack and increase global internet security ยฎ, but more importantly you can move forward with your codebase and use modern features (that are not even new anymore) and make your life easier as a developer.

With that you open the door to better static analysis, and (this is why I'm here) users of the library can also type hint properly their code. My codebase is fully typed, except for getQRCodeImage ;)

Also, if users are still using php 5.6, it's quite unlikely that they regularly update their dependencies, so the argument of "but there are still people using 5.6 out there!" is moot IMHO. In the era of containers, one has no valid excuse for keeping around old php versions (except time and money of course, but that's another debate).

Please kindly indicate what are your reasons for supporting old php versions and if you'd consider dropping old versions in order to allow yourself and contributors to improve gradually the codebase with modern php language constructs, operators and features (and incidently, allow me to full type hint my code ;) ).

I'm willing to contribute to this work with PRs.

Best,
~Nico

PS: this blog post is an interesting read

Documentation update suggestion

Just a word of warning: there's no mention of ensuring that the curl module needs to be configured in PHP ("php -m | grep curl") or using the phpinfo(); page and then searching for the curl module.

endroid/qr-code compatibility issue

Using the latest TwoFactorAuth (v1.8.1) works perfectly with Endroid/qr-code v3.9.7 but it breaks if you try to use a more recent version. For instance v4.3.5, v4.4.0 or the very latest v4.4.1.

The error given is this:

PHP Fatal error: Uncaught Error: Class "Endroid\QrCode\ErrorCorrectionLevel" not found in vendor\robthree\twofactorauth\lib\Providers\Qr\EndroidQrCodeProvider.php:59

Demo Always fails.

I've copied the demo into a laravel 5.1 view.
Every time i load the page i get this line

When aforementioned code (893875) was entered, the result would be: FAIL

Obviously each time i refresh the code changes but it still fails. Only change i made in the demo was to remove

require_once 'loader.php';
Loader::register('../lib','RobThree\\Auth');

Since laravel will load the package.

Rename library from `TwoFactorAuth` to `TOTPAuth`

I would consider renaming the library from TwoFactorAuth to TOTPAuth, since in itself this is not a 2-factor authentication library.
It is potentially part of a 2-factor authentication setup when implemented alongside a second authentication method.

Renaming the library might help making it somewhat easier to find too. Though, that's just guessing.

Fatal Error

Hi there,

I'm getting the following;

Fatal error: Class 'RobThree\Auth\TwoFactorAuth' not found in /[REMOVED]/public_html/2fa.php on line 12

`

   <?php
    error_reporting(-1); 
    ini_set('display_errors', 1);

     require_once '2fa/demo/loader.php';
    Loader::register('2fa/lib','RobThree\\Auth');
    
    use \RobThree\Auth\TwoFactorAuth;
    
    $tfa = new TwoFactorAuth('MyApp');
	
	// Generate the code, store it inside the database, 
	// and generate the QR code for the user to scan, or provide the code
	// for the user to manually type into the app being used.
	
	// Generate User Image
	$secret = $tfa->createSecret(160);
	
echo "Two Factor Authentication Platform<br /><br />";
	echo "Secret Generated: " . $secret;
	echo "<br /><br /><br />";
	echo "Code for App: " . chunk_split($secret, 4, ' ');`

Why key can validate multiple use ?

when i validate key and success login , after i logout why it can use same key to validate

How can i implement it to expire key now after validate success.

thnak you

How to add custom image for the app?

Hi!

It appears that you cannot set a image for the icon in Google Authentication or similar applications that supports Google Authentication. When you have scanned the QR code, the icon for the service is a standard Android icon.

Is there any way to set this icon to something else?

QR image is truncated

Hello,

do you have any idea why the generated QR code is being truncated?
See the image attached.

Where should I look in your code to check the height?

Let me know if you need additional info.

Thanks.

qrgen

Why is method getQRText private?

awesome library, but I don't want to use any of the QRCode Providers, rather I pass the QRCodeText to the Client and have the Javascript Library qrcode.js render the QRCode.

Could you explain to me why the method getQRText() is private? Are you open to changing that to public?

How to use timeslice argument

As per your recent 1.6.2 release,

The verifyCode(...) method now has a new argument that returns the timeslice that matched the code so you can save the timeslice and prevent replay-attacks.

I'm not completely sure how to use the timeslice argument, would you always save it against the user and always pass it in from your records when verifying the user?

Thanks for your work

Composer lacking QrProviders

Hi, today I faced a long api.qrserver.com outage, so my QR codes were unable to be generated. I'm trying to use the EndroidQrCodeProvider, but the composer installation for robthree/twofactorauth doesn't come with these files (bug?), even with the endroid/qr-code dependency installed. Other files lacking too, like BaconQrCodeProvider.

demo for verifyCode()

Hello, could you possibly create a demo for how to use verifyCode(), for example, a login page of some sort? I'm not very experience with PHP, and don't quite understand how to do this, and when running the command 'php composer.phar require robthree/twofactorauth', I get the error 'Could not open input file: composer.phar', is it suppose to be composer.json?

Source folder as "src"

As convention for packages using PSR-4, the source folder should be named "src", shouldn't?

Support for logos in QR Codes

On quick research, I noticed that Endroid's library allows the embedding of image files in the middle of QR Codes. As that's necessary on my soon-to-be implementation, I'll have to extend TwoFactorAuth's class with that behavior. I want to publish it as a PR as well, if it doesn't feel out of scope for the project (I don't think it should be, anyway).

So, bottom-line: how would that implementation feel better on the project's style? We need two extra values (logo path & size): as more arguments on the constructor, or as an optional, extra method setLogo()?

verifyCode

verifyCode allways returns false in my code.
What I did:

  1. Store secret in session
  2. Use session secret to Display QR image while also displaying the code using getCode()
  3. Submit form with the entered code
  4. verifyCode allways return false

Any idea what could be the problem?

verify code always return false

Hi, I'm creating TwoFactorAuth instance in two different function. One function will generate the code and the other function will verify the code but I found out that it always return false when verifying the code. If I want to send out the code in the first function and use the other function for verification, are there any solution for this?

Newly generated secrets failing to verify codes

Hello,

I have been using your library in production for a couple of years now with no issue. We have had a bug come in where a user moving from non-2FA to 2FA could not get their code to verify. There is no issue with existing users verifying already set up codes.

I could reproduce this on production where neither the barcode nor the generated code would generate me an accepting code. I cannot reproduce it locally. I have also found that it works perfectly on our demo environment but the same problem occurs on our test/staging environment.

All servers are running robthree/twofactorauth version 1.8.
All servers are running PHP 7.4 though there are minor differences between minor versions PHP 7.4.27 (ubuntu 18) where the issuing is occurring, PHP 7.4.14 (ubuntu 18), 7.4.16 (windows 10) where the problem doesn't appear.

I have tried swapping out IRNGProvider and constructing with HttpTimeProvider, all of which work beautifully on the already working environments but return false from TwoFactorAuth::verifyCode on the affected environments.

I am struggling to think what I could be missing, some php packages that are required but not installed on the affecting environments? I would have hoped that any changes in the way underlying PHP functions (thinking random_bytes) work would have bene ruled out by swapping out Providers.

Any thoughts on this appreciated or indeed any "this is not enough info! we require x,y and z to help"- I've not bothered with code samples since the codes does work on "good" environments and the code itself is consistent across the environments. I just can't think what environmental component I may be missing that would explain the behaviour of existing codes verifying but newly generated ones not.

Travis will no longer build

If somebody is capable of fixing .travis.yml and phpunit.xml to make it build & run code coverage that would be very much appreciated!

Cannot use (or rather do not know how to use) PHPQRCODE

Hi,

I am very new to this project and am struggling to follow the guidelines for implementing phpqrcode. I believe I have followed the instructions. Downloaded and copied in phpqrcode.php into the lib folder, created myprovider.php in the QR subfolder of Providers and have the following as my demo script.

<?php
        require_once 'loader.php';
        Loader::register('../lib','RobThree\\Auth');

		
		
        use \RobThree\Auth\TwoFactorAuth;
        $mp = new RobThree\Auth\Providers\Qr\MyProvider();
	$tfa = new RobThree\Auth\TwoFactorAuth('MyApp', 6, 30, 'sha1', $mp);
		
        //$tfa = new TwoFactorAuth('MyApp');

        echo '<li>First create a secret and associate it with a user';
        $secret = $tfa->createSecret(160);  
		// Though the default is an 80 bits secret (for backwards compatibility reasons) we recommend creating 160+ bits secrets (see RFC 4226 - Algorithm Requirements)
        echo '<li>Next create a QR code and let the user scan it:<br><img src="' . $tfa->getQRCodeImageAsDataUri('My label', $secret) . '"><br>...or display the secret to the user for manual entry: ' . chunk_split($secret, 4, ' ');
        $code = $tfa->getCode($secret);
        echo '<li>Next, have the user verify the code; at this time the code displayed by a 2FA-app would be: <span style="color:#00c">' . $code . '</span> (but that changes periodically)';
        echo '<li>When the code checks out, 2FA can be / is enabled; store (encrypted?) secret with user and have the user verify a code each time a new session is started.';
        echo '<li>When aforementioned code (' . $code . ') was entered, the result would be: ' . (($tfa->verifyCode($secret, $code) === true) ? '<span style="color:#0c0">OK</span>' : '<span style="color:#c00">FAIL</span>');
?>

But I am getting the following error.

Fatal error: Class 'RobThree\Auth\Providers\Qr\MyProvider' not found in /var/www/html/vendor/robthree/twofactorauth/demo/demo1.php on line 15

Can anyone help please?

Andere code in "Google Authenticator" app

Ha Rob,

Ik probeer jouw TwoFactorAuth te gebruiken. Ik krijg een QR-code die scan in met de app "Google Authenticator" maar op het moment dat ik $tfa->getCode($secret); doe krijg ik een andere code te zien dan op mijn app. Op mijn server is NTP enabled. Enig idee wat hier fout gaat?

Mvg,
Jeroen

Google Authenticator only works with default values

When i alter the default values, like digits, or period, the generated code by Google's Authenticator no longer works.

When i use 6 digits and 30 seconds, all is fine.
When i delete account in Google Authenticator, change my web app values it to 8 digits and a period of 120 seconds, scan the new QR code: Google Authenticator no longer generates a valid 2FA code.

Not sure if this is a Google Authenticator issue, or an issue with this project, as the QR code supplies the right amount of seconds and digits in the url.

VerifyCode returns false / ensureCorrectTime issue

Hello,
I was trying to implement your library into my project.
The QR Code as well as the Code are being generated properly but I can't verify the Code.

After looking at the code I thought about, that the Time could be an issue. After trying the code
try { $tfa->ensureCorrectTime(); echo 'Your hosts time seems to be correct / within margin'; } catch (RobThree\Auth\TwoFactorAuthException $ex) { echo '<b>Warning:</b> Your hosts time seems to be off: ' . $ex->getMessage(); }

I get the following error
Uncaught Exception: Connection refused
extern/lib/Providers/Time/NTPTimeProvider.php Zeile 40
Backtrace
#0 extern/lib/TwoFactorAuth.php(157): RobThree\Auth\Providers\Time\NTPTimeProvider->getTime()
#1 extern/2fa.php(39): RobThree\Auth\TwoFactorAuth->ensureCorrectTime()
#2 {main}

NTPTimeProvider.php
/* Receive response and close socket */ if (socket_recv($sock, $recv, 48, MSG_WAITALL) === false) throw new \Exception(socket_strerror(socket_last_error($sock))); socket_close($sock);

So it's probably an Time issue I can't verify.

Also do I set the discrepancy in the TwoFactorAuth.php
like this public function verifyCode($secret, $code, $discrepancy = 4, $time = null, &$timeslice = 0)

or in my file with
$Ergebnis= $tfa->verifyCode($secret, $_POST['verification'], $discrepancy);

Many regards
Lukas

2fa

Good day,
Could you please explain to noob how to use your application step-by-step?
I've downloaded TwoFactorAuth, installed composer, launched "php composer.phar require robthree/twofactorauth", and stuck.
How do i create instance?
How do i attach it to my website?
How do i attach it to MS or Google Authenticator?
Thank you.

Fatal error: Uncaught Error: Class 'RobThree\Auth\Providers\Rng\CSRNGProvider' not found

Independend from my question about the composer thing I'm trying to use your library.

I got this error:
Fatal error: Uncaught Error: Class 'RobThree\Auth\Providers\Rng\CSRNGProvider' not found in /www/htdocs/xxxxx/path/to/my/project/vendor/robthree/twofactorauth/lib/TwoFactorAuth.php:334 Stack trace: #0 /www/htdocs/xxxxx/path/to/my/project/vendor/robthree/twofactorauth/lib/TwoFactorAuth.php(101): RobThree\Auth\TwoFactorAuth->getRngProvider() #1 /www/htdocs/xxxxx/path/to/my/project/demo.php(30): RobThree\Auth\TwoFactorAuth->createSecret() #2 {main} thrown in /www/htdocs/xxxxx/path/to/my/project/vendor/robthree/twofactorauth/lib/TwoFactorAuth.php on line 334

After commenting out line 334 the error continues for MCryptRNGProvider, I then commented this out and repeats for OpenSSLRNGProvider and also for HashRNGProvider.

The function random_bytes() exists and works properly (I'm running PHP 7.4).

That's my code so far:

require_once 'vendor/robthree/twofactorauth/lib/TwoFactorAuth.php';
$tfa = new RobThree\Auth\TwoFactorAuth('My Company');
$secret = $tfa->createSecret();
varDump($tfa);

Timing attack

I have a theoretical question about this snippet of code:

        // To keep safe from timing-attacks we iterate *all* possible codes even though we already may have
        // verified a code is correct. We use the timeslice variable to hold either 0 (no match) or the timeslice
        // of the match. Each iteration we either set the timeslice variable to the timeslice of the match
        // or set the value to itself.  This is an effort to maintain constant execution time for the code.
        for ($i = -$discrepancy; $i <= $discrepancy; $i++) {
            $ts = $timetamp + ($i * $this->period);
            $slice = $this->getTimeSlice($ts);
            $timeslice = $this->codeEquals($this->getCode($secret, $ts), $code) ? $slice : $timeslice;
        }

        return $timeslice > 0;

I wonder if the iteration of all possible code is really needed to keep safe from timing attack.
Eventually, if we do early return as soon as a code is correct, the only leaked information is the number of time slice checked.
What do you think?

Fatal Error

Keep getting this fatal error:

Fatal error: Uncaught Error: Class 'RobThree\Auth\Providers\Rng\CSRNGProvider'

Installed trough composer 3 times on different machines.

verifyCode() returning TRUE where on localhost but not where live

Thanks for this scripts, but as in the title. Things are working fine when on localhost, but when using it live on server, verifyCode() alwats returns false.

I used ensureCorrectTime(), and it is not throwing any exception
I also set $discrepancy to 10, but nothing

Here is my code:

$tfa = new TwoFactorAuth('Control');
$code = filter_input(INPUT_POST, 'code');

var_dump($tfa->verifyCode($secret, $code, 3));

Could it be a timezone issue? How can I debug this?

Install this package outside of project directory

I just noticed a problem with installing this package at the root of my webspace.

From within the root (/www/htdocs/xxxxx/) I ran composer require robthree/twofactorauth which was installed properly as /www/htdocs/xxxxx/vendor/robthree/twofactorauth/.

After copying the files demo.php and loader.php to my project directory (/www/htdocs/xxxxx/my/project/path/libs/2fa/) I changed the line
Loader::register('../lib','RobThree\\Auth');
to
Loader::register('/www/htdocs/xxxxx/vendor/robthree/twofactorauth/lib','RobThree\\Auth');
in order to set this absolute path. Calling demo.php displays a blank white page.

Even changing
require_once 'loader.php';
to
require_once '/www/htdocs/xxxxx/vendor/robthree/twofactorauth/demo/loader.php';
didn't change anything.

Installing the package within my project site works fine, I got the QR-Code and the text shown.

What am I missing to use this from a central path (to prevent it from multiple installations and updates)?

socket_recv(): unable to read from socket

Hello,

I was testing with the TwoFactorAuth library and got this warning while running the ensureCorrectTime function which is giving me some problems. I'm running this from a localhost laragon server with php 7.1.23 and i have tried running the php.net socket example to test if my sockets where working correctly and there doesn't seem to be any problems when i try that.

Is there something i am missing or doing wrong?

Greetings,
Robgeus

require_once 'twofaloader.php';
Twofaloader::register('/2faDependencies/TwofactorAuth','RobThree\\Auth');

use \RobThree\Auth\TwoFactorAuth;

class Twofa 
{

  public $twofa = null;

  public function __construct()
  {
    $this->tfa = new TwoFactorAuth('MyProject');

    try {
      $this->tfa->ensureCorrectTime();
      echo 'Your hosts time seems to be correct / within margin';
    } catch (RobThree\Auth\TwoFactorAuthException $ex) {
      echo '<b>Warning:</b> Your hosts time seems to be off: ' . $ex->getMessage();
    }
  }


}

afbeelding

Support for different authenticator versions?

I like this library. I have implemented TFA in my application and in all my tests, it seemed to work just fine.

I was testing with a couple of different iPhones using the Google Authenticator app, very straightforward.

However, upon deploying, the first user was using an older android phone. She installed Authenticator and took the picture of the QR. It 'seemed' to work, but Authenticator was showing a 6 digit code with a 30 seconds timeout (I have configured for an 8 digit code with a 1 minute timeout). Of course, the code does not work.

Has anybody seen anything similar? Are there different versions of Google Authenticator (there didn't seem to be when we installed it) I should be aware of?

Suggestions appreciated, we're 95% there!

Thanks for all the work on this!

Compatibility with Authy using sha256

Hi Rob,

It's mentioned in the docs about adjusting the algorithm from the default sha1. We are in a position we can insist our users use Authy for example, and from a quick google it seems it should support this algorithm, but I can't get codes from Authy verified if I set the algorithm to sha256. Only sha1 works. Can you clarify the situation here? What string exactly should I be supplying there?

BR,
Dean

Watermark in QR code when using the default QR Code provider

When using the default QR Code Provider the generated QR code contains a watermark which - at least for me - breaks scanning the code with the Authy app.

image-charts.com recently changed the behaviour regarding the creation of charts/QR codes. As per their website of today:
"QR Codes finaly came out of beta! Free users will have the watermark [..]"

Switching to "QRServerProvider" fixes the problem at hand.

Generate backup codes

Hi Rob! Nice work ๐Ÿ˜ƒ

Wondering how I can generate backup codes (that are never expired).

I use ->getCode($secret); but doesn't after 30sec, 1min it doesn't work or never worked. Any idea why and how to fix it?

Thx!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.