googleAuthenticator.class.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. <?php
  2. /**
  3. * Classe googleAuthenticator
  4. *
  5. * Cette classe fournit des méthodes pour générer et vérifier des codes de validation
  6. * basés sur l'algorithme TOTP (Time-based One-Time Password).
  7. */
  8. class googleAuthenticator
  9. {
  10. /**
  11. * Longueur par défaut des codes générés.
  12. *
  13. * @var int
  14. */
  15. static protected $_codeLength = 6;
  16. /**
  17. * Génère un secret pour l'authentification.
  18. *
  19. * @param int $secretLength Longueur du secret (entre 16 et 128).
  20. * @return string Retourne le secret généré.
  21. * @throws Exception Si la longueur du secret est invalide ou si une source aléatoire sécurisée est indisponible.
  22. */
  23. static public function createSecret($secretLength = 16)
  24. {
  25. $validChars = self::_getBase32LookupTable();
  26. // Valid secret lengths are 80 to 640 bits
  27. if ($secretLength < 16 || $secretLength > 128) {
  28. throw new Exception('Bad secret length');
  29. }
  30. $secret = '';
  31. $rnd = false;
  32. if (function_exists('random_bytes')) {
  33. $rnd = random_bytes($secretLength);
  34. } elseif (function_exists('openssl_random_pseudo_bytes')) {
  35. $rnd = openssl_random_pseudo_bytes($secretLength, $cryptoStrong);
  36. if (!$cryptoStrong) {
  37. $rnd = false;
  38. }
  39. }
  40. if ($rnd !== false) {
  41. for ($i = 0; $i < $secretLength; ++$i) {
  42. $secret .= $validChars[ord($rnd[$i]) & 31];
  43. }
  44. } else {
  45. throw new Exception('No source of secure random');
  46. }
  47. return $secret;
  48. }
  49. /**
  50. * Génère un code TOTP basé sur un secret et une tranche de temps.
  51. *
  52. * @param string $secret Secret utilisé pour générer le code.
  53. * @param int|null $timeSlice Tranche de temps (par défaut, tranche actuelle).
  54. * @return string Retourne le code généré.
  55. */
  56. static public function getCode($secret, $timeSlice = null)
  57. {
  58. if ($timeSlice === null) {
  59. $timeSlice = floor(time() / 30);
  60. }
  61. $secretkey = self::_base32Decode($secret);
  62. // Pack time into binary string
  63. $time = chr(0).chr(0).chr(0).chr(0).pack('N*', $timeSlice);
  64. // Hash it with users secret key
  65. $hm = hash_hmac('SHA1', $time, $secretkey, true);
  66. // Use last nipple of result as index/offset
  67. $offset = ord(substr($hm, -1)) & 0x0F;
  68. // grab 4 bytes of the result
  69. $hashpart = substr($hm, $offset, 4);
  70. // Unpak binary value
  71. $value = unpack('N', $hashpart);
  72. $value = $value[1];
  73. // Only 32 bits
  74. $value = $value & 0x7FFFFFFF;
  75. $modulo = pow(10, self::$_codeLength);
  76. return str_pad($value % $modulo, self::$_codeLength, '0', STR_PAD_LEFT);
  77. }
  78. /**
  79. * Génère une URL pour configurer Google Authenticator.
  80. *
  81. * @param string $name Nom du compte ou de l'utilisateur.
  82. * @param string $secret Secret associé au compte.
  83. * @return string Retourne l'URL générée.
  84. */
  85. static public function getGoogleUrl($name, $secret)
  86. {
  87. $urlencoded = 'otpauth://totp/'.$name.'?secret='.$secret;
  88. return $urlencoded;
  89. }
  90. /**
  91. * Vérifie si un code TOTP est valide pour un secret donné.
  92. *
  93. * @param string $secret Secret utilisé pour générer le code.
  94. * @param string $code Code à vérifier.
  95. * @param int $discrepancy Tolérance en tranches de temps (par défaut 1).
  96. * @param int|null $currentTimeSlice Tranche de temps actuelle (facultatif).
  97. * @return bool Retourne TRUE si le code est valide, FALSE sinon.
  98. */
  99. static public function verifyCode($secret, $code, $discrepancy = 1, $currentTimeSlice = null)
  100. {
  101. if ($currentTimeSlice === null) {
  102. $currentTimeSlice = floor(time() / 30);
  103. }
  104. if (strlen($code) != 6) {
  105. return false;
  106. }
  107. for ($i = -$discrepancy; $i <= $discrepancy; ++$i) {
  108. $calculatedCode = self::getCode($secret, $currentTimeSlice + $i);
  109. if (self::timingSafeEquals($calculatedCode, $code)) {
  110. return true;
  111. }
  112. }
  113. return false;
  114. }
  115. /**
  116. * Définit la longueur des codes générés.
  117. *
  118. * @param int $length Longueur des codes.
  119. * @return int Retourne la nouvelle longueur définie.
  120. */
  121. static public function setCodeLength($length)
  122. {
  123. return self::$_codeLength = $length;
  124. }
  125. /**
  126. * Décode une chaîne encodée en Base32.
  127. *
  128. * @param string $secret Chaîne encodée en Base32.
  129. * @return string Retourne la chaîne décodée.
  130. */
  131. static protected function _base32Decode($secret)
  132. {
  133. if (empty($secret)) {
  134. return '';
  135. }
  136. $base32chars = self::_getBase32LookupTable();
  137. $base32charsFlipped = array_flip($base32chars);
  138. $paddingCharCount = substr_count($secret, $base32chars[32]);
  139. $allowedValues = array(6, 4, 3, 1, 0);
  140. if (!in_array($paddingCharCount, $allowedValues)) {
  141. return false;
  142. }
  143. for ($i = 0; $i < 4; ++$i) {
  144. if ($paddingCharCount == $allowedValues[$i] &&
  145. substr($secret, -($allowedValues[$i])) != str_repeat($base32chars[32], $allowedValues[$i])) {
  146. return false;
  147. }
  148. }
  149. $secret = str_replace('=', '', $secret);
  150. $secret = str_split($secret);
  151. $binaryString = '';
  152. for ($i = 0; $i < count($secret); $i = $i + 8) {
  153. $x = '';
  154. if (!in_array($secret[$i], $base32chars)) {
  155. return false;
  156. }
  157. for ($j = 0; $j < 8; ++$j) {
  158. $x .= str_pad(base_convert(@$base32charsFlipped[@$secret[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT);
  159. }
  160. $eightBits = str_split($x, 8);
  161. for ($z = 0; $z < count($eightBits); ++$z) {
  162. $binaryString .= (($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48) ? $y : '';
  163. }
  164. }
  165. return $binaryString;
  166. }
  167. /**
  168. * Retourne la table de correspondance pour l'encodage Base32.
  169. *
  170. * @return array Retourne un tableau des caractères Base32.
  171. */
  172. static protected function _getBase32LookupTable()
  173. {
  174. return array(
  175. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', // 7
  176. 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 15
  177. 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 23
  178. 'Y', 'Z', '2', '3', '4', '5', '6', '7', // 31
  179. '=', // padding char
  180. );
  181. }
  182. /**
  183. * Compare deux chaînes de manière sécurisée contre les attaques temporelles.
  184. *
  185. * @param string $safeString Chaîne sécurisée.
  186. * @param string $userString Chaîne utilisateur.
  187. * @return bool Retourne TRUE si les chaînes sont identiques, FALSE sinon.
  188. */
  189. static private function timingSafeEquals($safeString, $userString)
  190. {
  191. if (function_exists('hash_equals')) {
  192. return hash_equals($safeString, $userString);
  193. }
  194. $safeLen = strlen($safeString);
  195. $userLen = strlen($userString);
  196. if ($userLen != $safeLen) {
  197. return false;
  198. }
  199. $result = 0;
  200. for ($i = 0; $i < $userLen; ++$i) {
  201. $result |= (ord($safeString[$i]) ^ ord($userString[$i]));
  202. }
  203. // They are only identical strings if $result is exactly 0...
  204. return $result === 0;
  205. }
  206. }