1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: 192: 193: 194: 195: 196: 197: 198: 199: 200: 201: 202: 203: 204: 205: 206: 207: 208: 209: 210: 211: 212: 213: 214: 215: 216: 217: 218: 219: 220: 221: 222: 223: 224: 225: 226: 227: 228: 229: 230: 231: 232: 233: 234: 235: 236: 237: 238: 239: 240: 241: 242: 243: 244: 245: 246: 247: 248: 249: 250: 251: 252: 253: 254: 255: 256: 257: 258: 259: 260: 261: 262: 263: 264: 265: 266: 267: 268: 269: 270: 271: 272: 273: 274: 275: 276: 277: 278: 279: 280: 281: 282: 283: 284: 285: 286: 287: 288: 289: 290: 291: 292: 293: 294: 295: 296: 297: 298: 299: 300: 301: 302: 303: 304: 305: 306: 307: 308: 309: 310: 311: 312: 313: 314: 315: 316: 317: 318: 319: 320: 321: 322: 323: 324: 325: 326: 327: 328: 329: 330: 331: 332: 333: 334: 335: 336: 337: 338: 339: 340: 341: 342: 343: 344: 345: 346: 347: 348: 349: 350: 351: 352: 353: 354: 355: 356: 357: 358: 359: 360: 361: 362: 363: 364: 365: 366: 367: 368: 369: 370: 371:
<?php
namespace TOTP;
/**
* A class for generating the codes compatible with the Google Authenticator and similar TOTP
* clients.
*
* NOTE: A lot of the logic from this class has been borrowed from this class:
* https://www.idontplaydarts.com/wp-content/uploads/2011/07/ga.php_.txt
*
* @author Chris Cornutt <ccornutt@phpdeveloper.org>
* @package GAuth
* @license MIT
*
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines https://www.simplemachines.org
* @copyright 2020 Simple Machines and individual contributors
* @license https://www.simplemachines.org/about/smf/license.php BSD
*
* @version 2.1 RC2
*/
/**
* Class Auth
*
* @package TOTP
*/
class Auth
{
/**
* @var array Internal lookup table
*/
private $lookup = array();
/**
* @var string Initialization key
*/
private $initKey = null;
/**
* @var integer Seconds between key refreshes
*/
private $refreshSeconds = 30;
/**
* @var integer The length of codes to generate
*/
private $codeLength = 6;
/**
* @var integer Range plus/minus for "window of opportunity" on allowed codes
*/
private $range = 2;
/**
* Initialize the object and set up the lookup table
* Optionally the Initialization key
*
* @param string $initKey Initialization key
*/
public function __construct($initKey = null)
{
$this->buildLookup();
if ($initKey !== null)
{
$this->setInitKey($initKey);
}
}
/**
* Build the base32 lookup table
*/
public function buildLookup()
{
$lookup = array_combine(
array_merge(range('A', 'Z'), range(2, 7)),
range(0, 31)
);
$this->setLookup($lookup);
}
/**
* Get the current "range" value
*
* @return integer Range value
*/
public function getRange()
{
return $this->range;
}
/**
* Set the "range" value
*
* @param integer $range Range value
* @return \TOTP\Auth instance
*/
public function setRange($range)
{
if (!is_numeric($range))
{
throw new \InvalidArgumentException('Invalid window range');
}
$this->range = $range;
return $this;
}
/**
* Set the initialization key for the object
*
* @param string $key Initialization key
* @throws \InvalidArgumentException If hash is not valid base32
* @return \TOTP\Auth instance
*/
public function setInitKey($key)
{
if (preg_match('/^[' . implode('', array_keys($this->getLookup())) . ']+$/', $key) == false)
{
throw new \InvalidArgumentException('Invalid base32 hash!');
}
$this->initKey = $key;
return $this;
}
/**
* Get the current Initialization key
*
* @return string Initialization key
*/
public function getInitKey()
{
return $this->initKey;
}
/**
* Set the contents of the internal lookup table
*
* @param array $lookup Lookup data set
* @throws \InvalidArgumentException If lookup given is not an array
* @return \TOTP\Auth instance
*/
public function setLookup($lookup)
{
if (!is_array($lookup))
{
throw new \InvalidArgumentException('Lookup value must be an array');
}
$this->lookup = $lookup;
return $this;
}
/**
* Get the current lookup data set
*
* @return array Lookup data
*/
public function getLookup()
{
return $this->lookup;
}
/**
* Get the number of seconds for code refresh currently set
*
* @return integer Refresh in seconds
*/
public function getRefresh()
{
return $this->refreshSeconds;
}
/**
* Set the number of seconds to refresh codes
*
* @param integer $seconds Seconds to refresh
* @throws \InvalidArgumentException If seconds value is not numeric
* @return \TOTP\Auth instance
*/
public function setRefresh($seconds)
{
if (!is_numeric($seconds))
{
throw new \InvalidArgumentException('Seconds must be numeric');
}
$this->refreshSeconds = $seconds;
return $this;
}
/**
* Get the current length for generated codes
*
* @return integer Code length
*/
public function getCodeLength()
{
return $this->codeLength;
}
/**
* Set the length of the generated codes
*
* @param integer $length Code length
* @return \TOTP\Auth instance
*/
public function setCodeLength($length)
{
$this->codeLength = $length;
return $this;
}
/**
* Validate the given code
*
* @param string $code Code entered by user
* @param string $initKey Initialization key
* @param string $timestamp Timestamp for calculation
* @param integer $range Seconds before/after to validate hash against
* @throws \InvalidArgumentException If incorrect code length
* @return boolean Pass/fail of validation
*/
public function validateCode($code, $initKey = null, $timestamp = null, $range = null)
{
if (strlen($code) !== $this->getCodeLength())
{
throw new \InvalidArgumentException('Incorrect code length');
}
$range = ($range == null) ? $this->getRange() : $range;
$timestamp = ($timestamp == null) ? $this->generateTimestamp() : $timestamp;
$initKey = ($initKey == null) ? $this->getInitKey() : $initKey;
$binary = $this->base32_decode($initKey);
for ($time = ($timestamp - $range); $time <= ($timestamp + $range); $time++)
{
if ($this->generateOneTime($binary, $time) == $code)
{
return true;
}
}
return false;
}
/**
* Generate a one-time code
*
* @param string $initKey Initialization key [optional]
* @param string $timestamp Timestamp for calculation [optional]
* @return string Generated code/hash
*/
public function generateOneTime($initKey = null, $timestamp = null)
{
$initKey = ($initKey == null) ? $this->getInitKey() : $initKey;
$timestamp = ($timestamp == null) ? $this->generateTimestamp() : $timestamp;
$hash = hash_hmac(
'sha1',
pack('N*', 0) . pack('N*', $timestamp),
$initKey,
true
);
return str_pad($this->truncateHash($hash), $this->getCodeLength(), '0', STR_PAD_LEFT);
}
/**
* Generate a code/hash
* Useful for making Initialization codes
*
* @param integer $length Length for the generated code
* @return string Generated code
*/
public function generateCode($length = 16)
{
global $smcFunc;
$lookup = implode('', array_keys($this->getLookup()));
$code = '';
for ($i = 0; $i < $length; $i++)
{
$code .= $lookup[$smcFunc['random_int'](0, strlen($lookup) - 1)];
}
return $code;
}
/**
* Generate the timestamp for the calculation
*
* @return integer Timestamp
*/
public function generateTimestamp()
{
return floor(microtime(true) / $this->getRefresh());
}
/**
* Truncate the given hash down to just what we need
*
* @param string $hash Hash to truncate
* @return string Truncated hash value
*/
public function truncateHash($hash)
{
$offset = ord($hash[19]) & 0xf;
return (
((ord($hash[$offset + 0]) & 0x7f) << 24) |
((ord($hash[$offset + 1]) & 0xff) << 16) |
((ord($hash[$offset + 2]) & 0xff) << 8) |
(ord($hash[$offset + 3]) & 0xff)
) % pow(10, $this->getCodeLength());
}
/**
* Base32 decoding function
*
* @param string $hash The base32-encoded hash
* @throws \InvalidArgumentException When hash is not valid
* @return string Binary value of hash
*/
public function base32_decode($hash)
{
$lookup = $this->getLookup();
if (preg_match('/^[' . implode('', array_keys($lookup)) . ']+$/', $hash) == false)
{
throw new \InvalidArgumentException('Invalid base32 hash!');
}
$hash = strtoupper($hash);
$buffer = 0;
$length = 0;
$binary = '';
for ($i = 0; $i < strlen($hash); $i++)
{
$buffer = $buffer << 5;
$buffer += $lookup[$hash[$i]];
$length += 5;
if ($length >= 8)
{
$length -= 8;
$binary .= chr(($buffer & (0xFF << $length)) >> $length);
}
}
return $binary;
}
/**
* Returns a URL to QR code for embedding the QR code
*
* @param string $name The name
* @param string $code The generated code
* @return string The URL to the QR code
*/
public function getQrCodeUrl($name, $code)
{
$url = 'otpauth://totp/' . urlencode($name) . '?secret=' . $code;
return $url;
}
}
?>