3 abstract class GoogleAuthenticator {
5 function __construct($totpskew=1, $hotpskew=10, $hotphuntvalue=200000) {
6 // the hotpskew is how many tokens forward we look to find the input
8 $this->hotpSkew = $hotpskew;
10 // the totpskew value is how many tokens either side of the current
11 // token we should check, based on a time skew.
12 $this->totpSkew = $totpskew;
14 // the hotphuntvalue is what we use to resync tokens.
15 // when a user resyncs, we search from 0 to $hutphutvalue to find
16 // the two token codes the user has entered - 200000 seems like overkill
17 // really as i cant imagine any token out there would ever make it
18 // past 200000 token code requests.
19 $this->hotpHuntValue = $hotphuntvalue;
22 // pure abstract functions that need to be overloaded when
23 // creating a sub class
24 abstract function getData($username);
25 abstract function putData($username, $data);
26 abstract function getUsers();
28 // a function to create an empty data structure, filled with some defaults
29 function createEmptyData() {
30 $data["tokenkey"] = ""; // the token key
31 $data["tokentype"] = "HOTP"; // the token type
32 $data["tokentimer"] = 30; // the token timer (For totp) and not supported by ga yet
33 $data["tokencounter"] = 1; // the token counter for hotp
34 $data["tokenalgorithm"] = "SHA1"; // the token algorithm (not supported by ga yet)
35 $data["user"] = ""; // a place for implementors to store their own data
40 // an internal funciton to get data from the overloaded functions
41 // and turn them into php arrays.
42 function internalGetData($username) {
43 $data = $this->getData($username);
44 $deco = unserialize(base64_decode($data));
47 $deco = $this->createEmptyData();
53 // the function used inside the class to put the data into the
54 // datastore using the overloaded data saving class
55 function internalPutData($username, $data) {
56 if($data == "") $enco = "";
57 else $enco = base64_encode(serialize($data));
59 return $this->putData($username, $enco);
63 // set the token type the user it going to use.
64 // this defaults to HOTP - we only do 30s token
65 // so lets not be able to set that yet
66 function setTokenType($username, $tokentype) {
67 $tokentype = strtoupper($tokentype);
68 if($tokentype!="HOTP" && $tokentype!="TOTP") {
69 $errorText = "Invalid Token Type";
73 $data = $this->internalGetData($username);
74 $data["tokentype"] = $tokentype;
75 return $this->internalPutData($username, $data);
80 // create "user" with insert
81 function setUser($username, $ttype="HOTP", $key = "", $hexkey="") {
82 $ttype = strtoupper($ttype);
83 if($ttype != "HOTP" && $ttype !="TOTP") return false;
84 if($key == "") $key = $this->createBase32Key();
85 $hkey = $this->helperb322hex($key);
86 if($hexkey != "") $hkey = $hexkey;
88 $token = $this->internalGetData($username);
89 $token["tokenkey"] = $hkey;
90 $token["tokentype"] = $ttype;
92 if(!$this->internalPutData($username, $token)) {
98 // a function to determine if the user has an actual token
99 function hasToken($username) {
100 $token = $this->internalGetData($username);
101 // TODO: change this to a pattern match for an actual key
102 if(!isset($token["tokenkey"])) return false;
103 if($token["tokenkey"] == "") return false;
108 // sets the key for a user - this is assuming you dont want
109 // to use one created by the application. returns false
110 // if the key is invalid or the user doesn't exist.
111 function setUserKey($username, $key) {
112 // consider scrapping this
113 $token = $this->internalGetData($username);
114 $token["tokenkey"] = $key;
115 $this->internalPutData($username, $token);
117 // TODO error checking
123 function deleteUser($username) {
124 // oh, we need to figure out how to do thi?
125 $this->internalPutData($username, "");
128 // user has input their user name and some code, authenticate
130 function authenticateUser($username, $code) {
132 if(preg_match("/[0-9][0-9][0-9][0-9][0-9][0-9]/",$code)<1) return false;
133 //error_log("begin auth user");
134 $tokendata = $this->internalGetData($username);
135 //$asdf = print_r($tokendata, true);
136 //error_log("dat is $asdf");
138 if($tokendata["tokenkey"] == "") {
139 $errorText = "No Assigned Token";
143 // TODO: check return value
144 $ttype = $tokendata["tokentype"];
145 $tlid = $tokendata["tokencounter"];
146 $tkey = $tokendata["tokenkey"];
148 //$asdf = print_r($tokendata, true);
149 //error_log("dat is $asdf");
152 error_log("in hotp");
154 $en = $tlid+$this->hotpSkew;
155 for($i=$st; $i<$en; $i++) {
156 $stest = $this->oath_hotp($tkey, $i);
157 //error_log("testing code: $code, $stest, $tkey, $tid");
158 if($code == $stest) {
159 $tokendata["tokencounter"] = $i;
160 $this->internalPutData($username, $tokendata);
167 error_log("in totp");
169 $t_ear = $t_now - ($this->totpSkew*$tokendata["tokentimer"]);
170 $t_lat = $t_now + ($this->totpSkew*$tokendata["tokentimer"]);
171 $t_st = ((int)($t_ear/$tokendata["tokentimer"]));
172 $t_en = ((int)($t_lat/$tokendata["tokentimer"]));
173 //error_log("kmac: $t_now, $t_ear, $t_lat, $t_st, $t_en");
174 for($i=$t_st; $i<=$t_en; $i++) {
175 $stest = $this->oath_hotp($tkey, $i);
176 error_log("testing code: $code, $stest, $tkey\n");
177 if($code == $stest) {
190 // this function allows a user to resync their key. If too
191 // many codes are called, we only check up to 20 codes in the future
192 // so if the user is at 21, they'll always fail.
193 function resyncCode($username, $code1, $code2) {
194 // here we'll go from 0 all the way thru to 200k.. if we cant find the code, so be it, they'll need a new one
195 // for HOTP tokens we start at x and go to x+20
197 // for TOTP we go +/-1min TODO = remember that +/- 1min should
198 // be changed based on stepping if we change the expiration time
201 // $this->dbConnector->query('CREATE TABLE "tokens" ("token_id" INTEGER PRIMARY KEY AUTOINCREMENT,"token_key" TEXT NOT NULL, "token_type" TEXT NOT NULL, "token_lastid" INTEGER NOT NULL)');
202 $tokendata = $this->internalGetData($username);
204 // TODO: check return value
205 $ttype = $tokendata["tokentype"];
206 $tlid = $tokendata["tokencounter"];
207 $tkey = $tokendata["tokenkey"];
210 $this->errorText = "No Assigned Token";
217 $en = $this->hotpHuntValue;
218 for($i=$st; $i<$en; $i++) {
219 $stest = $this->oath_hotp($tkey, $i);
220 //echo "code: $code, $stest, $tkey\n";
221 if($code1 == $stest) {
222 $stest2 = $this->oath_hotp($tkey, $i+1);
223 if($code2 == $stest2) {
224 $tokendata["tokencounter"] = $i+1;
225 $this->internalPutData($username, $tokendata);
236 echo "how the frig did i end up here?";
242 // gets the error text associated with the last error
243 function getErrorText() {
244 return $this->errorText;
247 // create a url compatibile with google authenticator.
248 function createURL($user) {
249 // oddity in the google authenticator... hotp needs to be lowercase.
250 $data = $this->internalGetData($user);
251 $toktype = $data["tokentype"];
252 $key = $this->helperhex2b32($data["tokenkey"]);
254 // token counter should be one more then current token value, otherwise
256 $counter = $data["tokencounter"]+1;
257 $toktype = strtolower($toktype);
258 if($toktype == "hotp") {
259 $url = "otpauth://$toktype/$user?secret=$key&counter=$counter";
261 $url = "otpauth://$toktype/$user?secret=$key";
263 //echo "url: $url\n";
267 // creeates a base 32 key (random)
268 function createBase32Key() {
269 $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
271 for($i=0; $i<16; $i++) {
272 $offset = rand(0,strlen($alphabet)-1);
273 //echo "$i off is $offset\n";
274 $key .= $alphabet[$offset];
281 function getKey($username) {
282 $data = $this->internalGetData($username);
283 $key = $data["tokenkey"];
289 function getTokenType($username) {
290 $data = $this->internalGetData($username);
291 $toktype = $data["tokentype"];
297 // TODO: lots of error checking goes in here
298 function helperb322hex($b32) {
299 $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
304 for($i = 0; $i < strlen($b32); $i++) {
305 $in = strrpos($alphabet, $b32[$i]);
306 $b = str_pad(base_convert($in, 10, 2), 5, "0", STR_PAD_LEFT);
311 $ar = str_split($out,20);
313 //echo "$dous, $b\n";
317 foreach($ar as $val) {
318 $rv = str_pad(base_convert($val, 2, 16), 5, "0", STR_PAD_LEFT);
319 //echo "rv: $rv from $val\n";
328 // TODO: lots of error checking goes in here
329 function helperhex2b32($hex) {
330 $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
332 $ar = str_split($hex, 5);
335 foreach($ar as $var) {
336 $bc = base_convert($var, 16, 2);
337 $bin = str_pad($bc, 20, "0", STR_PAD_LEFT);
339 //echo "$bc was, $var is, $bin are\n";
343 $ar2 = str_split($out, 5);
344 foreach($ar2 as $var2) {
345 $bc = base_convert($var2, 2, 10);
346 $out2 .= $alphabet[$bc];
352 // i've put alot of faith in the code from the
353 // php site's examples for the hash_hmac algorithm
354 // i assume its mostly correct but i should do
355 // some testing to verify this is actually the case
356 function oath_hotp($key, $counter)
358 $key = pack("H*", $key);
359 $cur_counter = array(0,0,0,0,0,0,0,0);
362 $cur_counter[$i] = pack ('C*', $counter);
363 $counter = $counter >> 8;
365 $bin_counter = implode($cur_counter);
367 if (strlen ($bin_counter) < 8)
369 $bin_counter = str_repeat (chr(0), 8 - strlen ($bin_counter)) . $bin_counter;
373 $hash = hash_hmac ('sha1', $bin_counter, $key);
374 return str_pad($this->oath_truncate($hash), 6, "0", STR_PAD_LEFT);
378 function oath_truncate($hash, $length = 6)
381 foreach(str_split($hash,2) as $hex)
383 $hmac_result[]=hexdec($hex);
387 $offset = $hmac_result[19] & 0xf;
389 // Algorithm from RFC
392 (($hmac_result[$offset+0] & 0x7f) << 24 ) |
393 (($hmac_result[$offset+1] & 0xff) << 16 ) |
394 (($hmac_result[$offset+2] & 0xff) << 8 ) |
395 ($hmac_result[$offset+3] & 0xff)
400 // some private data bits.
401 private $getDatafunction;
402 private $putDatafunction;
409 private $hotpHuntValue;
416 * 3: input code was invalid (user input an invalid code - must be 6 numerical digits)
417 * 4: user doesnt exist?