BioTorrents.de’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.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. <?php
  2. class TwoFactorAuth
  3. {
  4. private $algorithm;
  5. private $period;
  6. private $digits;
  7. private $issuer;
  8. private static $_base32dict = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=';
  9. private static $_base32;
  10. private static $_base32lookup = [];
  11. private static $_supportedalgos = array('sha1', 'sha256', 'sha512', 'md5');
  12. public function __construct($issuer = null, $digits = 6, $period = 30, $algorithm = 'sha1')
  13. {
  14. $this->issuer = $issuer;
  15. $this->digits = $digits;
  16. $this->period = $period;
  17. $algorithm = strtolower(trim($algorithm));
  18. if (!in_array($algorithm, self::$_supportedalgos)) {
  19. $algorithm = 'sha1';
  20. }
  21. $this->algorithm = $algorithm;
  22. self::$_base32 = str_split(self::$_base32dict);
  23. self::$_base32lookup = array_flip(self::$_base32);
  24. }
  25. public function createSecret($bits = 210)
  26. {
  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. }
  33. return $secret;
  34. }
  35. // Calculate the code with given secret and point in time
  36. public function getCode($secret, $time = null)
  37. {
  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. // Check if the code is correct. This will accept codes starting from now +/- ($discrepancy * period) seconds
  47. public function verifyCode($secret, $code, $discrepancy = 1, $time = null)
  48. {
  49. $result = false;
  50. $timetamp = $this->getTime($time);
  51. // Always iterate all possible codes to prevent timing-attacks
  52. for ($i = -$discrepancy; $i <= $discrepancy; $i++) {
  53. $result |= hash_equals($this->getCode($secret, $timetamp + ($i * $this->period)), $code);
  54. }
  55. return (bool)$result;
  56. }
  57. // Get data-uri of QRCode
  58. public function getQRCodeImageAsDataUri($label, $secret, $size = 300)
  59. {
  60. if (exec('which qrencode')) {
  61. $QRCodeImage = shell_exec("qrencode -s ".(int)($size/40)." -m 3 -o - '".$this->getQRText($label, $secret)."'");
  62. } else {
  63. $curlhandle = curl_init();
  64. curl_setopt_array($curlhandle, array(
  65. CURLOPT_URL => 'https://chart.googleapis.com/chart?cht=qr&chs='.$size.'x'.$size.'&chld=L|1&chl='.rawurlencode($this->getQRText($label, $secret)),
  66. CURLOPT_RETURNTRANSFER => true,
  67. CURLOPT_CONNECTTIMEOUT => 10,
  68. CURLOPT_DNS_CACHE_TIMEOUT => 10,
  69. CURLOPT_TIMEOUT => 10,
  70. CURLOPT_SSL_VERIFYPEER => false,
  71. CURLOPT_USERAGENT => 'TwoFactorAuth'
  72. ));
  73. $QRCodeImage = curl_exec($curlhandle);
  74. curl_close($curlhandle);
  75. }
  76. return 'data:image/png;base64,'.base64_encode($QRCodeImage);
  77. }
  78. private function getTime($time)
  79. {
  80. return ($time === null) ? time() : $time;
  81. }
  82. private function getTimeSlice($time = null, $offset = 0)
  83. {
  84. return (int)floor($time / $this->period) + ($offset * $this->period);
  85. }
  86. // Builds a string to be encoded in a QR code
  87. public function getQRText($label, $secret)
  88. {
  89. $QRText = 'otpauth://totp/'.rawurlencode($label).'?secret='.rawurlencode($secret);
  90. $QRText .= ($this->issuer) ? '&issuer='.rawurlencode($this->issuer) : '';
  91. $QRText .= ($this->period != 30) ? '&period='.intval($this->period) : '';
  92. $QRText .= ($this->algorithm != 'sha1') ? '&algorithm='.rawurlencode(strtoupper($this->algorithm)) : '';
  93. $QRText .= ($this->digits != 6) ? '&digits='.intval($this->digits) : '';
  94. return $QRText;
  95. }
  96. private function base32Decode($value)
  97. {
  98. if (strlen($value)==0) {
  99. return '';
  100. }
  101. $buffer = '';
  102. foreach (str_split($value) as $char) {
  103. if ($char !== '=') {
  104. $buffer .= str_pad(decbin(self::$_base32lookup[$char]), 5, 0, STR_PAD_LEFT);
  105. }
  106. }
  107. $length = strlen($buffer);
  108. $blocks = trim(chunk_split(substr($buffer, 0, $length - ($length % 8)), 8, ' '));
  109. $output = '';
  110. foreach (explode(' ', $blocks) as $block) {
  111. $output .= chr(bindec(str_pad($block, 8, 0, STR_PAD_RIGHT)));
  112. }
  113. return $output;
  114. }
  115. }