1<?php 2 3namespace dokuwiki\plugin\twofactor; 4 5/** 6 * PHP Class for handling Google Authenticator 2-factor authentication. 7 * 8 * Namespaced for twofactor DokuWiki Plugin 9 * 10 * @author Michael Kliewe 11 * @copyright 2012 Michael Kliewe 12 * @license http://www.opensource.org/licenses/bsd-license.php BSD License 13 * 14 * @link http://www.phpgangsta.de/ 15 * @link https://github.com/PHPGangsta/GoogleAuthenticator 16 */ 17class GoogleAuthenticator 18{ 19 protected $_codeLength = 6; 20 21 /** 22 * Create new secret. 23 * 16 characters, randomly chosen from the allowed base32 characters. 24 * 25 * @param int $secretLength 26 * 27 * @return string 28 * @throws \Exception 29 */ 30 public function createSecret($secretLength = 16) 31 { 32 $validChars = $this->_getBase32LookupTable(); 33 34 // Valid secret lengths are 80 to 640 bits 35 if ($secretLength < 16 || $secretLength > 128) { 36 throw new \Exception('Bad secret length'); 37 } 38 $secret = ''; 39 $rnd = false; 40 if (function_exists('random_bytes')) { 41 $rnd = random_bytes($secretLength); 42 } elseif (function_exists('mcrypt_create_iv')) { 43 $rnd = mcrypt_create_iv($secretLength, MCRYPT_DEV_URANDOM); 44 } elseif (function_exists('openssl_random_pseudo_bytes')) { 45 $rnd = openssl_random_pseudo_bytes($secretLength, $cryptoStrong); 46 if (!$cryptoStrong) { 47 $rnd = false; 48 } 49 } 50 if ($rnd !== false) { 51 for ($i = 0; $i < $secretLength; ++$i) { 52 $secret .= $validChars[ord($rnd[$i]) & 31]; 53 } 54 } else { 55 throw new \Exception('No source of secure random'); 56 } 57 58 return $secret; 59 } 60 61 /** 62 * Calculate the code, with given secret and point in time. 63 * 64 * @param string $secret 65 * @param int|null $timeSlice 66 * 67 * @return string 68 */ 69 public function getCode($secret, $timeSlice = null) 70 { 71 if ($timeSlice === null) { 72 $timeSlice = floor(time() / 30); 73 } 74 75 $secretkey = $this->_base32Decode($secret); 76 77 // Pack time into binary string 78 $time = chr(0).chr(0).chr(0).chr(0).pack('N*', $timeSlice); 79 // Hash it with users secret key 80 $hm = hash_hmac('SHA1', $time, $secretkey, true); 81 // Use last nipple of result as index/offset 82 $offset = ord(substr($hm, -1)) & 0x0F; 83 // grab 4 bytes of the result 84 $hashpart = substr($hm, $offset, 4); 85 86 // Unpak binary value 87 $value = unpack('N', $hashpart); 88 $value = $value[1]; 89 // Only 32 bits 90 $value = $value & 0x7FFFFFFF; 91 92 $modulo = pow(10, $this->_codeLength); 93 94 return str_pad($value % $modulo, $this->_codeLength, '0', STR_PAD_LEFT); 95 } 96 97 /** 98 * Get QR-Code URL for image, from google charts. 99 * 100 * @param string $name 101 * @param string $secret 102 * @param string $title 103 * @param array $params 104 * 105 * @return string 106 */ 107 public function getQRCodeGoogleUrl($name, $secret, $title = null, $params = array()) 108 { 109 $width = !empty($params['width']) && (int) $params['width'] > 0 ? (int) $params['width'] : 200; 110 $height = !empty($params['height']) && (int) $params['height'] > 0 ? (int) $params['height'] : 200; 111 $level = !empty($params['level']) && array_search($params['level'], array('L', 'M', 'Q', 'H')) !== false ? $params['level'] : 'M'; 112 113 $urlencoded = urlencode('otpauth://totp/'.$name.'?secret='.$secret.''); 114 if (isset($title)) { 115 $urlencoded .= urlencode('&issuer='.urlencode($title)); 116 } 117 118 return "https://api.qrserver.com/v1/create-qr-code/?data=$urlencoded&size=${width}x${height}&ecc=$level"; 119 } 120 121 /** 122 * Check if the code is correct. This will accept codes starting from $discrepancy*30sec ago to $discrepancy*30sec from now. 123 * 124 * @param string $secret 125 * @param string $code 126 * @param int $discrepancy This is the allowed time drift in 30 second units (8 means 4 minutes before or after) 127 * @param int|null $currentTimeSlice time slice if we want use other that time() 128 * 129 * @return bool 130 */ 131 public function verifyCode($secret, $code, $discrepancy = 1, $currentTimeSlice = null) 132 { 133 if ($currentTimeSlice === null) { 134 $currentTimeSlice = floor(time() / 30); 135 } 136 137 if (strlen($code) != 6) { 138 return false; 139 } 140 141 for ($i = -$discrepancy; $i <= $discrepancy; ++$i) { 142 $calculatedCode = $this->getCode($secret, $currentTimeSlice + $i); 143 if ($this->timingSafeEquals($calculatedCode, $code)) { 144 return true; 145 } 146 } 147 148 return false; 149 } 150 151 /** 152 * Set the code length, should be >=6. 153 * 154 * @param int $length 155 * 156 * @return GoogleAuthenticator 157 */ 158 public function setCodeLength($length) 159 { 160 $this->_codeLength = $length; 161 162 return $this; 163 } 164 165 /** 166 * Helper class to decode base32. 167 * 168 * @param $secret 169 * 170 * @return bool|string 171 */ 172 protected function _base32Decode($secret) 173 { 174 if (empty($secret)) { 175 return ''; 176 } 177 178 $base32chars = $this->_getBase32LookupTable(); 179 $base32charsFlipped = array_flip($base32chars); 180 181 $paddingCharCount = substr_count($secret, $base32chars[32]); 182 $allowedValues = array(6, 4, 3, 1, 0); 183 if (!in_array($paddingCharCount, $allowedValues)) { 184 return false; 185 } 186 for ($i = 0; $i < 4; ++$i) { 187 if ($paddingCharCount == $allowedValues[$i] && 188 substr($secret, -($allowedValues[$i])) != str_repeat($base32chars[32], $allowedValues[$i])) { 189 return false; 190 } 191 } 192 $secret = str_replace('=', '', $secret); 193 $secret = str_split($secret); 194 $binaryString = ''; 195 for ($i = 0; $i < count($secret); $i = $i + 8) { 196 $x = ''; 197 if (!in_array($secret[$i], $base32chars)) { 198 return false; 199 } 200 for ($j = 0; $j < 8; ++$j) { 201 $x .= str_pad(base_convert(@$base32charsFlipped[@$secret[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT); 202 } 203 $eightBits = str_split($x, 8); 204 for ($z = 0; $z < count($eightBits); ++$z) { 205 $binaryString .= (($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48) ? $y : ''; 206 } 207 } 208 209 return $binaryString; 210 } 211 212 /** 213 * Get array with all 32 characters for decoding from/encoding to base32. 214 * 215 * @return array 216 */ 217 protected function _getBase32LookupTable() 218 { 219 return array( 220 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', // 7 221 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 15 222 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 23 223 'Y', 'Z', '2', '3', '4', '5', '6', '7', // 31 224 '=', // padding char 225 ); 226 } 227 228 /** 229 * A timing safe equals comparison 230 * more info here: http://blog.ircmaxell.com/2014/11/its-all-about-time.html. 231 * 232 * @param string $safeString The internal (safe) value to be checked 233 * @param string $userString The user submitted (unsafe) value 234 * 235 * @return bool True if the two strings are identical 236 */ 237 private function timingSafeEquals($safeString, $userString) 238 { 239 if (function_exists('hash_equals')) { 240 return hash_equals($safeString, $userString); 241 } 242 $safeLen = strlen($safeString); 243 $userLen = strlen($userString); 244 245 if ($userLen != $safeLen) { 246 return false; 247 } 248 249 $result = 0; 250 251 for ($i = 0; $i < $userLen; ++$i) { 252 $result |= (ord($safeString[$i]) ^ ord($userString[$i])); 253 } 254 255 // They are only identical strings if $result is exactly 0... 256 return $result === 0; 257 } 258} 259