Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Require minimum key size for HMAC algorithm #835

Merged
merged 3 commits into from
Jul 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,22 @@ $configuration = Configuration::forSymmetricSigner(
);
```

Currently supported symmetric algorithms:

| Name | Description | Class | Key length req. |
| --------- | ------------------ | ---------------------------------------- | --------------- |
| `HS256` | HMAC using SHA-256 | `\Lcobucci\JWT\Signer\Hmac\Sha256` | 32 bytes |
| `HS384` | HMAC using SHA-384 | `\Lcobucci\JWT\Signer\Hmac\Sha384` | 48 bytes |
| `HS512` | HMAC using SHA-512 | `\Lcobucci\JWT\Signer\Hmac\Sha512` | 64 bytes |

Deprecated symmetric algorithms in `v4`:

| Name | Description | Class | Key length req. |
| --------- | ------------------ | ---------------------------------------- | --------------- |
| `HS256` | HMAC using SHA-256 | `\Lcobucci\JWT\Signer\Hmac\UnsafeSha256` | 1 byte |
| `HS384` | HMAC using SHA-384 | `\Lcobucci\JWT\Signer\Hmac\UnsafeSha384` | 1 byte |
| `HS512` | HMAC using SHA-512 | `\Lcobucci\JWT\Signer\Hmac\UnsafeSha512` | 1 byte |

#### For asymmetric algorithms

Asymmetric algorithms use a **private key** for signature creation and a **public key** for verification.
Expand All @@ -91,6 +107,18 @@ $configuration = Configuration::forAsymmetricSigner(
The implementation of ECDSA algorithms have a constructor dependency.
Use the `create()` named constructor to avoid having to handle it (e.g.: `Lcobucci\JWT\Signer\Ecdsa\Sha256::create()`).

Currently supported asymmetric algorithms:

| Name | Description | Class |
| ------- | ------------------------------- | ----------------------------------- |
| `ES256` | ECDSA using P-256 and SHA-256 | `\Lcobucci\JWT\Signer\Ecdsa\Sha256` |
| `ES384` | ECDSA using P-384 and SHA-384 | `\Lcobucci\JWT\Signer\Ecdsa\Sha384` |
| `ES512` | ECDSA using P-521 and SHA-512 | `\Lcobucci\JWT\Signer\Ecdsa\Sha512` |
| `RS256` | RSASSA-PKCS1-v1_5 using SHA-256 | `\Lcobucci\JWT\Signer\Rsa\Sha256` |
| `RS384` | RSASSA-PKCS1-v1_5 using SHA-384 | `\Lcobucci\JWT\Signer\Rsa\Sha384` |
| `RS512` | RSASSA-PKCS1-v1_5 using SHA-512 | `\Lcobucci\JWT\Signer\Rsa\Sha512` |
| `EdDSA` | EdDSA signature algorithms | `\Lcobucci\JWT\Signer\Eddsa` |

#### For no algorithm

!!! Warning
Expand Down
4 changes: 4 additions & 0 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,7 @@ parameters:
ignoreErrors:
- '#.*OpenSSLAsymmetricKey.*#'
- '#Call to method .* of deprecated class Lcobucci\\JWT\\Signer\\Key\\LocalFileReference#'
- """
#^Instantiation of deprecated class Lcobucci\\\\JWT\\\\Signer\\\\Hmac\\\\UnsafeSha\\d\\d\\d\\:
Deprecated since v4\\.2$#
"""
10 changes: 10 additions & 0 deletions src/Signer/Hmac.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,18 @@

use function hash_equals;
use function hash_hmac;
use function strlen;

abstract class Hmac implements Signer
{
final public function sign(string $payload, Key $key): string
{
$actualKeyLength = strlen($key->contents());
$expectedKeyLength = $this->minimumBytesLengthForKey();
if ($actualKeyLength < $expectedKeyLength) {
throw InvalidKeyProvided::tooShort($expectedKeyLength, $actualKeyLength);
}

return hash_hmac($this->algorithm(), $payload, $key->contents(), true);
}

Expand All @@ -21,4 +28,7 @@ final public function verify(string $expected, string $payload, Key $key): bool
}

abstract public function algorithm(): string;

/** @return positive-int */
abstract public function minimumBytesLengthForKey(): int;
}
5 changes: 5 additions & 0 deletions src/Signer/Hmac/Sha256.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,9 @@ public function algorithm(): string
{
return 'sha256';
}

public function minimumBytesLengthForKey(): int
{
return 32;
}
}
5 changes: 5 additions & 0 deletions src/Signer/Hmac/Sha384.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,9 @@ public function algorithm(): string
{
return 'sha384';
}

public function minimumBytesLengthForKey(): int
{
return 48;
}
}
5 changes: 5 additions & 0 deletions src/Signer/Hmac/Sha512.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,9 @@ public function algorithm(): string
{
return 'sha512';
}

public function minimumBytesLengthForKey(): int
{
return 64;
}
}
25 changes: 25 additions & 0 deletions src/Signer/Hmac/UnsafeSha256.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);

namespace Lcobucci\JWT\Signer\Hmac;

use Lcobucci\JWT\Signer\Hmac;

/** @deprecated Deprecated since v4.2 */
final class UnsafeSha256 extends Hmac
{
public function algorithmId(): string
{
return 'HS256';
}

public function algorithm(): string
{
return 'sha256';
}

public function minimumBytesLengthForKey(): int
{
return 1;
}
}
25 changes: 25 additions & 0 deletions src/Signer/Hmac/UnsafeSha384.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);

namespace Lcobucci\JWT\Signer\Hmac;

use Lcobucci\JWT\Signer\Hmac;

/** @deprecated Deprecated since v4.2 */
final class UnsafeSha384 extends Hmac
{
public function algorithmId(): string
{
return 'HS384';
}

public function algorithm(): string
{
return 'sha384';
}

public function minimumBytesLengthForKey(): int
{
return 1;
}
}
25 changes: 25 additions & 0 deletions src/Signer/Hmac/UnsafeSha512.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);

namespace Lcobucci\JWT\Signer\Hmac;

use Lcobucci\JWT\Signer\Hmac;

/** @deprecated Deprecated since v4.2 */
final class UnsafeSha512 extends Hmac
{
public function algorithmId(): string
{
return 'HS512';
}

public function algorithm(): string
{
return 'sha512';
}

public function minimumBytesLengthForKey(): int
{
return 1;
}
}
6 changes: 6 additions & 0 deletions src/Signer/InvalidKeyProvided.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,10 @@ public static function cannotBeEmpty(): self
{
return new self('Key cannot be empty');
}

public static function tooShort(int $expectedLength, int $actualLength): self
{
return new self('Key provided is shorter than ' . $expectedLength . ' bytes,'
. ' only ' . $actualLength . ' bytes provided');
}
}
26 changes: 19 additions & 7 deletions test/functional/HmacTokenTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Hmac\Sha512;
use Lcobucci\JWT\Signer\Hmac\UnsafeSha256;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Signer\Key\LocalFileReference;
use Lcobucci\JWT\Token;
Expand Down Expand Up @@ -34,6 +35,7 @@
* @covers \Lcobucci\JWT\Signer\Hmac
* @covers \Lcobucci\JWT\Signer\Hmac\Sha256
* @covers \Lcobucci\JWT\Signer\Hmac\Sha512
* @covers \Lcobucci\JWT\Signer\Hmac\UnsafeSha256
* @covers \Lcobucci\JWT\SodiumBase64Polyfill
* @covers \Lcobucci\JWT\Validation\Validator
* @covers \Lcobucci\JWT\Validation\RequiredConstraintsViolated
Expand All @@ -46,7 +48,10 @@ class HmacTokenTest extends TestCase
/** @before */
public function createConfiguration(): void
{
$this->config = Configuration::forSymmetricSigner(new Sha256(), InMemory::plainText('testing'));
$this->config = Configuration::forSymmetricSigner(
new Sha256(),
InMemory::base64Encoded('Z0Y6xrhjGQYrEDsP+7aQ3ZAKKERSBeQjP33M0H7Nq6s=')
);
}

/** @test */
Expand Down Expand Up @@ -94,7 +99,10 @@ public function signatureAssertionShouldRaiseExceptionWhenKeyIsNotRight(Token $t

$this->config->validator()->assert(
$token,
new SignedWith($this->config->signer(), InMemory::plainText('testing1'))
new SignedWith(
$this->config->signer(),
InMemory::base64Encoded('O0MpjL80kE382RyX0rfr9PrNfVclXcdnru2aryanR2o=')
)
);
}

Expand Down Expand Up @@ -127,14 +135,18 @@ public function signatureValidationShouldSucceedWhenKeyIsRight(Token $token): vo
/** @test */
public function everythingShouldWorkWhenUsingATokenGeneratedByOtherLibs(): void
{
$data = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJoZWxsbyI6IndvcmxkIn0.Rh'
$config = Configuration::forSymmetricSigner(
new UnsafeSha256(),
InMemory::plainText('testing')
);
$data = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJoZWxsbyI6IndvcmxkIn0.Rh'
. '7AEgqCB7zae1PkgIlvOpeyw9Ab8NGTbeOH7heHO0o';

$token = $this->config->parser()->parse($data);
$token = $config->parser()->parse($data);
assert($token instanceof Token\Plain);
$constraint = new SignedWith($this->config->signer(), $this->config->verificationKey());
$constraint = new SignedWith($config->signer(), $config->verificationKey());

self::assertTrue($this->config->validator()->validate($token, $constraint));
self::assertTrue($config->validator()->validate($token, $constraint));
self::assertEquals('world', $token->claims()->get('hello'));
}

Expand All @@ -148,7 +160,7 @@ public function signatureValidationWithLocalFileKeyReferenceWillOperateWithKeyCo

$validKey = LocalFileReference::file($key);
$invalidKey = InMemory::plainText('file://' . $key);
$signer = new Sha256();
$signer = new UnsafeSha256();
$configuration = Configuration::forSymmetricSigner($signer, $validKey);
$validator = $configuration->validator();

Expand Down
8 changes: 1 addition & 7 deletions test/performance/Hmac/HmacBench.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,12 @@
namespace Lcobucci\JWT\Hmac;

use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\SignerBench;
use PhpBench\Benchmark\Metadata\Annotations\Groups;

/** @Groups({"Hmac"}) */
abstract class HmacBench extends SignerBench
{
private const ENCODED_KEY = 'hJtXIZ2uSN5kbQfbtTNWbpdmhkV8FJG+Onbc6mxCcYg=';

protected function signingKey(): Key
{
return $this->createKey();
Expand All @@ -23,8 +20,5 @@ protected function verificationKey(): Key
return $this->createKey();
}

private function createKey(): Key
{
return InMemory::base64Encoded(self::ENCODED_KEY);
}
abstract protected function createKey(): Key;
}
7 changes: 7 additions & 0 deletions test/performance/Hmac/Sha256Bench.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,18 @@

use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Signer\Key\InMemory;

final class Sha256Bench extends HmacBench
{
protected function signer(): Signer
{
return new Sha256();
}

protected function createKey(): Key
{
return InMemory::base64Encoded('n5p7sBK+dvBmSKNlQIFrsuB1cnmnwsxGyWXPgRSZtWY=');
}
}
7 changes: 7 additions & 0 deletions test/performance/Hmac/Sha384Bench.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,18 @@

use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Signer\Hmac\Sha384;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Signer\Key\InMemory;

final class Sha384Bench extends HmacBench
{
protected function signer(): Signer
{
return new Sha384();
}

protected function createKey(): Key
{
return InMemory::base64Encoded('kNUb8KvJC+fvhPzIuimwWHleES3AAnUjI+UIWZyor5HT33st9KIjfPkgtfu60UL2');
}
}
9 changes: 9 additions & 0 deletions test/performance/Hmac/Sha512Bench.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,20 @@

use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Signer\Hmac\Sha512;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Signer\Key\InMemory;

final class Sha512Bench extends HmacBench
{
protected function signer(): Signer
{
return new Sha512();
}

protected function createKey(): Key
{
return InMemory::base64Encoded(
'OgXKIs+aZCQgXnDfi8mAFnWVo+Xn3JTR7BvT/j1Q1zP9oRx9xGg4jmpq00RsPPDclYi8+jRl664pu4d0zan2ow=='
);
}
}
4 changes: 2 additions & 2 deletions test/unit/JwtFacadeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ protected function setUp(): void
{
$this->clock = new FrozenClock(new DateTimeImmutable('2021-07-10'));
$this->signer = new Sha256();
$this->key = InMemory::plainText('foo');
$this->key = InMemory::base64Encoded('qOIXmZRqZKY80qg0BjtCrskM6OK7gPOea8mz1H7h/dE=');
$this->issuer = 'bar';
}

Expand Down Expand Up @@ -190,7 +190,7 @@ public function badKey(): void

(new JwtFacade())->parse(
$this->createToken(),
new SignedWith($this->signer, InMemory::plainText('xyz')),
new SignedWith($this->signer, InMemory::base64Encoded('czyPTpN595zVNSuvoNNlXCRFgXS2fHscMR36dGojaUE=')),
new StrictValidAt($this->clock),
new IssuedBy($this->issuer)
);
Expand Down
12 changes: 12 additions & 0 deletions test/unit/Signer/Hmac/Sha256Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,16 @@ public function algorithmMustBeCorrect(): void

self::assertEquals('sha256', $signer->algorithm());
}

/**
* @test
*
* @covers ::minimumBytesLengthForKey
*/
public function minimumBytesLengthForKeyMustBeCorrect(): void
{
$signer = new Sha256();

self::assertSame(32, $signer->minimumBytesLengthForKey());
}
}
Loading