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 5.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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 = array();
  10. private static $_supportedalgos = array('sha1', 'sha256', 'sha512', 'md5');
  11. function __construct($issuer = null, $digits = 6, $period = 60, $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. /**
  24. * Create a new secret
  25. */
  26. public function createSecret($bits = 80) {
  27. $secret = '';
  28. $bytes = ceil($bits / 5); //We use 5 bits of each byte (since we have a 32-character 'alphabet' / BASE32)
  29. $rnd = random_bytes($bytes);
  30. for ($i = 0; $i < $bytes; $i++)
  31. $secret .= self::$_base32[ord($rnd[$i]) & 31]; //Mask out left 3 bits for 0-31 values
  32. return $secret;
  33. }
  34. /**
  35. * Calculate the code with given secret and point in time
  36. */
  37. public function getCode($secret, $time = null) {
  38. $secretkey = $this->base32Decode($secret);
  39. $timestamp = "\0\0\0\0" . pack('N*', $this->getTimeSlice($this->getTime($time))); // Pack time into binary string
  40. $hashhmac = hash_hmac($this->algorithm, $timestamp, $secretkey, true); // Hash it with users secret key
  41. $hashpart = substr($hashhmac, ord(substr($hashhmac, -1)) & 0x0F, 4); // Use last nibble of result as index/offset and grab 4 bytes of the result
  42. $value = unpack('N', $hashpart); // Unpack binary value
  43. $value = $value[1] & 0x7FFFFFFF; // Drop MSB, keep only 31 bits
  44. return str_pad($value % pow(10, $this->digits), $this->digits, '0', STR_PAD_LEFT);
  45. }
  46. /**
  47. * Check if the code is correct. This will accept codes starting from ($discrepancy * $period) sec ago to ($discrepancy * period) sec from now
  48. */
  49. public function verifyCode($secret, $code, $discrepancy = 1, $time = null) {
  50. $result = false;
  51. $timetamp = $this->getTime($time);
  52. // To keep safe from timing-attachs we iterate *all* possible codes even though we already may have verified a code is correct
  53. for ($i = -$discrepancy; $i <= $discrepancy; $i++)
  54. $result |= $this->codeEquals($this->getCode($secret, $timetamp + ($i * $this->period)), $code);
  55. return (bool)$result;
  56. }
  57. /**
  58. * Timing-attack safe comparison of 2 codes (see http://blog.ircmaxell.com/2014/11/its-all-about-time.html)
  59. */
  60. private function codeEquals($safe, $user) {
  61. if (function_exists('hash_equals')) {
  62. return hash_equals($safe, $user);
  63. } else {
  64. // In general, it's not possible to prevent length leaks. So it's OK to leak the length. The important part is that
  65. // we don't leak information about the difference of the two strings.
  66. if (strlen($safe)===strlen($user)) {
  67. $result = 0;
  68. for ($i = 0; $i < strlen($safe); $i++)
  69. $result |= (ord($safe[$i]) ^ ord($user[$i]));
  70. return $result === 0;
  71. }
  72. }
  73. return false;
  74. }
  75. /**
  76. * Get data-uri of QRCode
  77. */
  78. public function getQRCodeImageAsDataUri($label, $secret, $size = 300) {
  79. if (exec('which qrencode')) {
  80. $QRCodeImage = shell_exec("qrencode -s ".(int)($size/40)." -m 3 -o - '".$this->getQRText($label, $secret)."'");
  81. } else {
  82. $curlhandle = curl_init();
  83. curl_setopt_array($curlhandle, array(
  84. CURLOPT_URL => 'https://chart.googleapis.com/chart?cht=qr&chs='.$size.'x'.$size.'&chld=L|1&chl='.rawurlencode($this->getQRText($label, $secret)),
  85. CURLOPT_RETURNTRANSFER => true,
  86. CURLOPT_CONNECTTIMEOUT => 10,
  87. CURLOPT_DNS_CACHE_TIMEOUT => 10,
  88. CURLOPT_TIMEOUT => 10,
  89. CURLOPT_SSL_VERIFYPEER => false,
  90. CURLOPT_USERAGENT => 'TwoFactorAuth'
  91. ));
  92. $QRCodeImage = curl_exec($curlhandle);
  93. curl_close($curlhandle);
  94. }
  95. return 'data:image/png;base64,'.base64_encode($QRCodeImage);
  96. }
  97. private function getTime($time) {
  98. return ($time === null) ? time() : $time;
  99. }
  100. private function getTimeSlice($time = null, $offset = 0) {
  101. return (int)floor($time / $this->period) + ($offset * $this->period);
  102. }
  103. /**
  104. * Builds a string to be encoded in a QR code
  105. */
  106. public function getQRText($label, $secret) {
  107. return 'otpauth://totp/' . rawurlencode($label)
  108. . '?secret=' . rawurlencode($secret)
  109. . '&issuer=' . rawurlencode($this->issuer)
  110. . '&period=' . intval($this->period)
  111. . '&algorithm=' . rawurlencode(strtoupper($this->algorithm))
  112. . '&digits=' . intval($this->digits);
  113. }
  114. private function base32Decode($value) {
  115. if (strlen($value)==0) { return ''; }
  116. $buffer = '';
  117. foreach (str_split($value) as $char) {
  118. if ($char !== '=') {
  119. $buffer .= str_pad(decbin(self::$_base32lookup[$char]), 5, 0, STR_PAD_LEFT);
  120. }
  121. }
  122. $length = strlen($buffer);
  123. $blocks = trim(chunk_split(substr($buffer, 0, $length - ($length % 8)), 8, ' '));
  124. $output = '';
  125. foreach (explode(' ', $blocks) as $block)
  126. $output .= chr(bindec(str_pad($block, 8, 0, STR_PAD_RIGHT)));
  127. return $output;
  128. }
  129. }