Oppaitime's version of Gazelle
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

twofa.class.php 4.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. <?php
  2. class TwoFactorAuth {
  3. private $algorithm;
  4. private $period;
  5. private $digits;
  6. private $issuer;
  7. private static $_base32dict = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=';
  8. private static $_base32;
  9. private static $_base32lookup = [];
  10. private static $_supportedalgos = array('sha1', 'sha256', 'sha512', 'md5');
  11. function __construct($issuer = null, $digits = 6, $period = 30, $algorithm = 'sha1') {
  12. $this->issuer = $issuer;
  13. $this->digits = $digits;
  14. $this->period = $period;
  15. $algorithm = strtolower(trim($algorithm));
  16. if (!in_array($algorithm, self::$_supportedalgos)){
  17. $algorithm = 'sha1';
  18. }
  19. $this->algorithm = $algorithm;
  20. self::$_base32 = str_split(self::$_base32dict);
  21. self::$_base32lookup = array_flip(self::$_base32);
  22. }
  23. public function createSecret($bits = 210) {
  24. $secret = '';
  25. $bytes = ceil($bits / 5); //We use 5 bits of each byte (since we have a 32-character 'alphabet' / BASE32)
  26. $rnd = random_bytes($bytes);
  27. for ($i = 0; $i < $bytes; $i++) {
  28. $secret .= self::$_base32[ord($rnd[$i]) & 31]; //Mask out left 3 bits for 0-31 values
  29. }
  30. return $secret;
  31. }
  32. // Calculate the code with given secret and point in time
  33. public function getCode($secret, $time = null) {
  34. $secretkey = $this->base32Decode($secret);
  35. $timestamp = "\0\0\0\0" . pack('N*', $this->getTimeSlice($this->getTime($time))); // Pack time into binary string
  36. $hashhmac = hash_hmac($this->algorithm, $timestamp, $secretkey, true); // Hash it with users secret key
  37. $hashpart = substr($hashhmac, ord(substr($hashhmac, -1)) & 0x0F, 4); // Use last nibble of result as index/offset and grab 4 bytes of the result
  38. $value = unpack('N', $hashpart); // Unpack binary value
  39. $value = $value[1] & 0x7FFFFFFF; // Drop MSB, keep only 31 bits
  40. return str_pad($value % pow(10, $this->digits), $this->digits, '0', STR_PAD_LEFT);
  41. }
  42. // Check if the code is correct. This will accept codes starting from now +/- ($discrepancy * period) seconds
  43. public function verifyCode($secret, $code, $discrepancy = 1, $time = null) {
  44. $result = false;
  45. $timetamp = $this->getTime($time);
  46. // Always iterate all possible codes to prevent timing-attacks
  47. for ($i = -$discrepancy; $i <= $discrepancy; $i++) {
  48. $result |= hash_equals($this->getCode($secret, $timetamp + ($i * $this->period)), $code);
  49. }
  50. return (bool)$result;
  51. }
  52. // Get data-uri of QRCode
  53. public function getQRCodeImageAsDataUri($label, $secret, $size = 300) {
  54. if (exec('which qrencode')) {
  55. $QRCodeImage = shell_exec("qrencode -s ".(int)($size/40)." -m 3 -o - '".$this->getQRText($label, $secret)."'");
  56. } else {
  57. $curlhandle = curl_init();
  58. curl_setopt_array($curlhandle, array(
  59. CURLOPT_URL => 'https://chart.googleapis.com/chart?cht=qr&chs='.$size.'x'.$size.'&chld=L|1&chl='.rawurlencode($this->getQRText($label, $secret)),
  60. CURLOPT_RETURNTRANSFER => true,
  61. CURLOPT_CONNECTTIMEOUT => 10,
  62. CURLOPT_DNS_CACHE_TIMEOUT => 10,
  63. CURLOPT_TIMEOUT => 10,
  64. CURLOPT_SSL_VERIFYPEER => false,
  65. CURLOPT_USERAGENT => 'TwoFactorAuth'
  66. ));
  67. $QRCodeImage = curl_exec($curlhandle);
  68. curl_close($curlhandle);
  69. }
  70. return 'data:image/png;base64,'.base64_encode($QRCodeImage);
  71. }
  72. private function getTime($time) {
  73. return ($time === null) ? time() : $time;
  74. }
  75. private function getTimeSlice($time = null, $offset = 0) {
  76. return (int)floor($time / $this->period) + ($offset * $this->period);
  77. }
  78. // Builds a string to be encoded in a QR code
  79. public function getQRText($label, $secret) {
  80. $QRText = 'otpauth://totp/'.rawurlencode($label).'?secret='.rawurlencode($secret);
  81. $QRText .= ($this->issuer) ? '&issuer='.rawurlencode($this->issuer) : '';
  82. $QRText .= ($this->period != 30) ? '&period='.intval($this->period) : '';
  83. $QRText .= ($this->algorithm != 'sha1') ? '&algorithm='.rawurlencode(strtoupper($this->algorithm)) : '';
  84. $QRText .= ($this->digits != 6) ? '&digits='.intval($this->digits) : '';
  85. return $QRText;
  86. }
  87. private function base32Decode($value) {
  88. if (strlen($value)==0) { return ''; }
  89. $buffer = '';
  90. foreach (str_split($value) as $char) {
  91. if ($char !== '=') {
  92. $buffer .= str_pad(decbin(self::$_base32lookup[$char]), 5, 0, STR_PAD_LEFT);
  93. }
  94. }
  95. $length = strlen($buffer);
  96. $blocks = trim(chunk_split(substr($buffer, 0, $length - ($length % 8)), 8, ' '));
  97. $output = '';
  98. foreach (explode(' ', $blocks) as $block) {
  99. $output .= chr(bindec(str_pad($block, 8, 0, STR_PAD_RIGHT)));
  100. }
  101. return $output;
  102. }
  103. }