| 1 |
<?php |
| 2 |
/* |
| 3 |
* This file is part of the ManageWP Worker plugin. |
| 4 |
* |
| 5 |
* (c) ManageWP LLC <contact@managewp.com> |
| 6 |
* |
| 7 |
* For the full copyright and license information, please view the LICENSE |
| 8 |
* file that was distributed with this source code. |
| 9 |
*/ |
| 10 |
|
| 11 |
class MWP_Security_NonceManager |
| 12 |
{ |
| 13 |
|
| 14 |
private $context; |
| 15 |
|
| 16 |
private $nonceValidFor; |
| 17 |
|
| 18 |
private $nonceBlacklistedFor; |
| 19 |
|
| 20 |
/** |
| 21 |
* @param MWP_WordPress_Context $context |
| 22 |
* @param int $nonceValidFor How long (in seconds) is the nonce valid since its issue time. |
| 23 |
* @param int $nonceBlacklistedFor How long (in seconds) to keep used nonce in storage. |
| 24 |
*/ |
| 25 |
public function __construct(MWP_WordPress_Context $context, $nonceValidFor = 43200, $nonceBlacklistedFor = 86400) |
| 26 |
{ |
| 27 |
if ($nonceBlacklistedFor < $nonceValidFor) { |
| 28 |
throw new LogicException('Nonce blacklist time must be higher than nonce lifetime.'); |
| 29 |
} |
| 30 |
|
| 31 |
$this->context = $context; |
| 32 |
$this->nonceValidFor = $nonceValidFor; |
| 33 |
$this->nonceBlacklistedFor = $nonceBlacklistedFor; |
| 34 |
} |
| 35 |
|
| 36 |
/** |
| 37 |
* @param string $nonce |
| 38 |
* |
| 39 |
* @throws MWP_Security_Exception_NonceFormatInvalid |
| 40 |
* @throws MWP_Security_Exception_NonceExpired |
| 41 |
* @throws MWP_Security_Exception_NonceAlreadyUsed |
| 42 |
*/ |
| 43 |
public function useNonce($nonce) |
| 44 |
{ |
| 45 |
$parts = explode('_', $nonce); |
| 46 |
|
| 47 |
if (count($parts) !== 2) { |
| 48 |
throw new MWP_Security_Exception_NonceFormatInvalid(); |
| 49 |
} |
| 50 |
|
| 51 |
list($nonceValue, $issuedAt) = $parts; |
| 52 |
$issuedAt = (int) $issuedAt; |
| 53 |
|
| 54 |
if (!$nonceValue || !$issuedAt) { |
| 55 |
throw new MWP_Security_Exception_NonceFormatInvalid(); |
| 56 |
} |
| 57 |
|
| 58 |
if ($issuedAt + $this->nonceValidFor < time()) { |
| 59 |
throw new MWP_Security_Exception_NonceExpired(); |
| 60 |
} |
| 61 |
|
| 62 |
// There was a bug where the generated nonce was 42 characters long. |
| 63 |
$transientKey = substr('n_'.$nonceValue, 0, 40); |
| 64 |
$nonceUsed = $this->context->transientGet($transientKey); |
| 65 |
|
| 66 |
if ($nonceUsed !== false) { |
| 67 |
throw new MWP_Security_Exception_NonceAlreadyUsed(); |
| 68 |
} |
| 69 |
|
| 70 |
$this->context->transientSet($transientKey, $issuedAt, $this->nonceBlacklistedFor); |
| 71 |
} |
| 72 |
} |
| 73 |
|