├── .gitignore ├── .travis.yml ├── LICENSE.md ├── README.md ├── composer.json ├── src ├── DI │ └── TotpAuthenticatorExtension.php ├── Security │ └── TotpAuthenticator.php ├── Utils │ └── TimeProvider.php └── exceptions.php └── tests ├── TotpAuthenticatorTests ├── netteDiExtensionTest.phpt ├── randomSecretTest.phpt ├── totpSecretTest.phpt └── verifyCodeTest.phpt ├── bootstrap.php └── php.ini-unix /.gitignore: -------------------------------------------------------------------------------- 1 | vendor 2 | composer.lock 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: php 2 | sudo: false 3 | 4 | php: 5 | - 7.2 6 | - 7.3 7 | - 7.4 8 | 9 | env: 10 | - NETTE_VERSION="^2.4" 11 | - NETTE_VERSION="^3.0" 12 | 13 | before_install: 14 | - if php --ri xdebug >/dev/null;then phpenv config-rm xdebug.ini; fi 15 | - travis_retry composer self-update 16 | 17 | install: 18 | - composer require "nette/di:${NETTE_VERSION}" --dev --no-update 19 | - travis_retry composer update --prefer-source --no-interaction 20 | 21 | script: 22 | - vendor/bin/tester -c tests/php.ini-unix tests/TotpAuthenticatorTests 23 | 24 | after_failure: 25 | - 'for i in $(find ./tests -name \*.actual); do echo "--- $i"; cat $i; echo; echo; done' 26 | 27 | jobs: 28 | include: 29 | - stage: QA 30 | name: Static Analysis 31 | php: 7.4 32 | env: NETTE_VERSION="^3.0" 33 | script: 34 | - vendor/bin/phpstan analyze --no-progress --no-interaction --level max src/ 35 | 36 | - stage: QA 37 | name: Code Coverage 38 | php: 7.4 39 | env: NETTE_VERSION="^3.0" 40 | script: 41 | - vendor/bin/tester -p phpdbg -c tests/php.ini-unix -s --coverage coverage.xml --coverage-src src/ tests/TotpAuthenticatorTests 42 | after_success: 43 | - bash <(curl --retry 3 -s https://codecov.io/bash) 44 | 45 | cache: 46 | directories: 47 | - $HOME/.composer/cache 48 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014, Jiří Pudil 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 5 | 6 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 7 | 8 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 9 | 10 | 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 11 | 12 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Oops/TotpAuthenticator 2 | 3 | ## 🏚️ THIS PROJECT HAS BEEN ABANDONED 4 | 5 | Please use https://github.com/jiripudil/otp for an up-to-date, more feature-rich implementation of one-time passwords. 6 | 7 | --- 8 | 9 | Oops/TotpAuthenticator implements the [TOTP algorithm](http://tools.ietf.org/html/rfc6238) that lets you easily set up a two-factor authentication mechanism. The TOTP, in short, generates a pseudo-random six-digit number based on current Unix time and given seed (a base32 string of at least 16 characters). The seed is shared between you and mobile app and passed to the app via a QR code. Whenever you need to authenticate the user, ask them to enter the code generated by the application, and verify it against the code generated by your server. 10 | 11 | 12 | ## Installation and requirements 13 | 14 | ```bash 15 | $ composer require oops/totp-authenticator 16 | ``` 17 | 18 | Oops/TotpAuthenticator requires PHP >= 7.2. 19 | 20 | 21 | ## Usage 22 | 23 | If you use Nette's DI container, you can easily integrate Oops/TotpAuthenticator with a few lines of configuration: 24 | 25 | ``` 26 | extensions: 27 | totp: Oops\TotpAuthenticator\DI\TotpAuthenticatorExtension 28 | 29 | totp: 30 | timeWindow: 1 31 | issuer: MyApp 32 | ``` 33 | 34 | Otherwise, you can directly instantiate `Oops\TotpAuthenticator\Security\TotpAuthenticator` and optionally configure it: 35 | 36 | ```php 37 | $totpAuthenticator = (new Oops\TotpAuthenticator\Security\TotpAuthenticator) 38 | ->setIssuer('MyApp') 39 | ->setTimeWindow(1); 40 | ``` 41 | 42 | The `timeWindow` option sets a benevolence that compensates for possible differences between your server's time and the app's time. The default value is 1, which means the code for previous or next 30-second block would be also considered valid. You can set it to zero if you want to be super strict, but I'd strongly recommend not setting it to a higher value than one. 43 | 44 | The `issuer` is optional, but is quite useful if you use some generic value as the user's account name, such as their email address. As multiple services can use that same value as a way of identifying the user, you should provide `issuer` to distinguish your app's code in the TOTP app. 45 | 46 | 47 | ### Setting up 2FA 48 | 49 | First, you need to generate a secret - a base32 string - that is shared between you and the application. `TotpAuthenticator` provides a method for that. The secret must be unique to the user and should thus be stored somewhere with other user data, e.g. in the database. Just remember to encrypt it as it is a very sensitive piece of information. 50 | 51 | ```php 52 | $secret = $totpAuthenticator->getRandomSecret(); 53 | ``` 54 | 55 | Then, you can display the secret and unique account name (e.g. user's email address) to the user, or, more conveniently, provide them with a QR code containing the URI in a specific format. Again, `TotpAuthenticator` can build the URI for you: 56 | 57 | ```php 58 | $uri = $totpAuthenticator->getTotpUri($secret, $accountName); 59 | ``` 60 | 61 | 62 | ### Verification 63 | 64 | Once the user has set up the account in their TOTP app, you can ask them to enter the 6-digit code and easily verify it against the secret: 65 | 66 | ```php 67 | if ($totpAuthenticator->verifyCode($code, $secret)) { 68 | // successfully verified 69 | 70 | } else { 71 | // incorrect code 72 | } 73 | ``` 74 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "oops/totp-authenticator", 3 | "description": "Two-factor authenticator via TOTP algorithm.", 4 | "keywords": ["security", "authentication", "2fa", "totp"], 5 | "type": "library", 6 | "license": "BSD-3-Clause", 7 | "authors": [ 8 | { 9 | "name": "Jiří Pudil", 10 | "email": "me@jiripudil.cz", 11 | "homepage": "http://jiripudil.cz" 12 | } 13 | ], 14 | "support": { 15 | "email": "me@jiripudil.cz", 16 | "issues": "https://github.com/o2ps/TotpAuthenticator/issues" 17 | }, 18 | "require": { 19 | "php": "^7.2", 20 | "paragonie/constant_time_encoding": "^2.0" 21 | }, 22 | "require-dev": { 23 | "nette/di": "^3.0", 24 | "nette/tester": "^2.3.1", 25 | "mockery/mockery": "^1.3", 26 | "phpstan/phpstan": "^0.12" 27 | }, 28 | "suggest": { 29 | "nette/di": "Optional integration with Nette's DI container" 30 | }, 31 | "autoload": { 32 | "psr-4": { 33 | "Oops\\TotpAuthenticator\\": "src/" 34 | }, 35 | "classmap": [ 36 | "src/exceptions.php" 37 | ] 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/DI/TotpAuthenticatorExtension.php: -------------------------------------------------------------------------------- 1 | 1, 19 | 'issuer' => '', 20 | ]; 21 | 22 | 23 | public function loadConfiguration() 24 | { 25 | $builder = $this->getContainerBuilder(); 26 | $config = $this->validateConfig($this->defaults); 27 | 28 | Validators::assertField($config, 'timeWindow', 'int'); 29 | Validators::assertField($config, 'issuer', 'string:1..'); 30 | 31 | $builder->addDefinition($this->prefix('timeProvider')) 32 | ->setFactory(TimeProvider::class) 33 | ->setAutowired(FALSE); 34 | 35 | $builder->addDefinition($this->prefix('authenticator')) 36 | ->setFactory(TotpAuthenticator::class, [$this->prefix('@timeProvider')]) 37 | ->addSetup('setTimeWindow', [$config['timeWindow']]) 38 | ->addSetup('setIssuer', [$config['issuer']]); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/Security/TotpAuthenticator.php: -------------------------------------------------------------------------------- 1 | timeProvider = $timeProvider ?? new TimeProvider(); 26 | } 27 | 28 | 29 | public function setTimeWindow(int $timeWindow): self 30 | { 31 | $this->timeWindow = $timeWindow; 32 | return $this; 33 | } 34 | 35 | 36 | public function setIssuer(string $issuer): self 37 | { 38 | $this->issuer = $issuer; 39 | return $this; 40 | } 41 | 42 | 43 | public function getTotpUri(string $secret, string $accountName): string 44 | { 45 | $accountName = rawurlencode($accountName); 46 | $issuer = $this->issuer !== NULL ? rawurlencode($this->issuer) : NULL; 47 | return 'otpauth://totp/' . ($issuer !== NULL ? "$issuer:" : '') . "{$accountName}?secret={$secret}" . ($issuer !== NULL ? "&issuer=$issuer" : ''); 48 | } 49 | 50 | 51 | public function getRandomSecret(int $length = 20): string 52 | { 53 | return Base32::encodeUpper(random_bytes($length)); 54 | } 55 | 56 | 57 | /** 58 | * @param string|int $code 59 | */ 60 | public function verifyCode($code, string $secret): bool 61 | { 62 | for ($offset = -$this->timeWindow; $offset <= $this->timeWindow; $offset++) { 63 | if (hash_equals((string) $code, $this->getOneTimePassword($secret, $offset))) { 64 | return TRUE; 65 | } 66 | } 67 | 68 | return FALSE; 69 | } 70 | 71 | 72 | private function getOneTimePassword(string $secret, int $offset): string 73 | { 74 | if ( ! preg_match('/^[A-Z2-7]+$/', $secret)) { 75 | throw new InvalidArgumentException("Secret contains invalid characters. Make sure it is a valid uppercase base32 string."); 76 | } 77 | 78 | if (strlen($secret) < 16) { 79 | throw new InvalidArgumentException("Secret is too short. It must be at least 128 bits long."); 80 | } 81 | 82 | $timestamp = $this->getTimestamp($offset); 83 | $secret = Base32::decodeUpper($secret); 84 | 85 | $hash = hash_hmac('sha1', $timestamp, $secret, TRUE); 86 | $offset = ord($hash[19]) & 0xF; 87 | 88 | $value = ( 89 | ((ord($hash[$offset+0]) & 0x7F) << 24) | 90 | ((ord($hash[$offset+1]) & 0xFF) << 16) | 91 | ((ord($hash[$offset+2]) & 0xFF) << 8) | 92 | ((ord($hash[$offset+3]) & 0xFF)) 93 | ) % 1e6; 94 | 95 | return str_pad((string) $value, 6, '0', STR_PAD_LEFT); 96 | } 97 | 98 | 99 | private function getTimestamp(int $offset): string 100 | { 101 | $timestamp = floor(($this->timeProvider->getMicroTime() + ($offset * 30)) / 30); 102 | return pack('N*', 0) . pack('N*', $timestamp); 103 | } 104 | 105 | } 106 | -------------------------------------------------------------------------------- /src/Utils/TimeProvider.php: -------------------------------------------------------------------------------- 1 | load(static function (Compiler $compiler): void { 14 | $compiler->addExtension('totp', new TotpAuthenticatorExtension()); 15 | $compiler->addConfig([ 16 | 'totp' => [ 17 | 'timeWindow' => 2, 18 | 'issuer' => 'jiripudil.cz', 19 | ], 20 | ]); 21 | }); 22 | 23 | $container = new $containerClassName(); 24 | 25 | \assert($container instanceof \Nette\DI\Container); 26 | $totp = $container->getByType(TotpAuthenticator::class, false); 27 | Assert::notNull($totp); 28 | 29 | Assert::match( 30 | '~^otpauth://totp/jiripudil\.cz:jiripudil\?secret=[A-Z2-7]{32}&issuer=jiripudil\.cz$~', 31 | $totp->getTotpUri($totp->getRandomSecret(), 'jiripudil') 32 | ); 33 | -------------------------------------------------------------------------------- /tests/TotpAuthenticatorTests/randomSecretTest.phpt: -------------------------------------------------------------------------------- 1 | getRandomSecret()); 13 | Assert::notEqual($seed1, $googleAuthenticator->getRandomSecret()); 14 | -------------------------------------------------------------------------------- /tests/TotpAuthenticatorTests/totpSecretTest.phpt: -------------------------------------------------------------------------------- 1 | getTotpUri($googleAuthenticator->getRandomSecret(), 'jiripudil') 15 | ); 16 | 17 | $googleAuthenticator = (new TotpAuthenticator(new TimeProvider()))->setIssuer('jiripudil.cz'); 18 | Assert::match( 19 | '~^otpauth://totp/jiripudil\.cz:jiripudil\?secret=[A-Z2-7]{32}&issuer=jiripudil\.cz$~', 20 | $googleAuthenticator->getTotpUri($googleAuthenticator->getRandomSecret(), 'jiripudil') 21 | ); 22 | 23 | $googleAuthenticator = (new TotpAuthenticator(new TimeProvider()))->setIssuer('Jiří Pudil'); 24 | Assert::match( 25 | '~^otpauth://totp/Ji%C5%99%C3%AD%20Pudil:Ji%C5%99%C3%AD%20Pudil\?secret=[A-Z2-7]{32}&issuer=Ji%C5%99%C3%AD%20Pudil$~', 26 | $googleAuthenticator->getTotpUri($googleAuthenticator->getRandomSecret(), 'Jiří Pudil') 27 | ); 28 | -------------------------------------------------------------------------------- /tests/TotpAuthenticatorTests/verifyCodeTest.phpt: -------------------------------------------------------------------------------- 1 | shouldReceive('getMicroTime')->andReturn(1415778000)->getMock(); 13 | 14 | $googleAuthenticator = (new TotpAuthenticator($timeProvider))->setTimeWindow(0); 15 | Assert::false($googleAuthenticator->verifyCode('209170', $seed)); // offset = -2 16 | Assert::false($googleAuthenticator->verifyCode('101895', $seed)); // offset = -1 17 | Assert::true($googleAuthenticator->verifyCode('292224', $seed)); // offset = 0 18 | Assert::false($googleAuthenticator->verifyCode('800413', $seed)); // offset = +1 19 | Assert::false($googleAuthenticator->verifyCode('223013', $seed)); // offset = +2 20 | 21 | $googleAuthenticator = (new TotpAuthenticator($timeProvider))->setTimeWindow(1); 22 | Assert::false($googleAuthenticator->verifyCode('209170', $seed)); // offset = -2 23 | Assert::true($googleAuthenticator->verifyCode('101895', $seed)); // offset = -1 24 | Assert::true($googleAuthenticator->verifyCode('292224', $seed)); // offset = 0 25 | Assert::true($googleAuthenticator->verifyCode('800413', $seed)); // offset = +1 26 | Assert::false($googleAuthenticator->verifyCode('223013', $seed)); // offset = +2 27 | 28 | $googleAuthenticator = (new TotpAuthenticator($timeProvider))->setTimeWindow(2); 29 | Assert::true($googleAuthenticator->verifyCode('209170', $seed)); // offset = -2 30 | Assert::true($googleAuthenticator->verifyCode('101895', $seed)); // offset = -1 31 | Assert::true($googleAuthenticator->verifyCode('292224', $seed)); // offset = 0 32 | Assert::true($googleAuthenticator->verifyCode('800413', $seed)); // offset = +1 33 | Assert::true($googleAuthenticator->verifyCode('223013', $seed)); // offset = +2 34 | 35 | Mockery::close(); 36 | -------------------------------------------------------------------------------- /tests/bootstrap.php: -------------------------------------------------------------------------------- 1 |