fixed a minor thing with the hotp skew
[ga4php.git] / lib / ga4php.php
1 <?php
2
3 abstract class GoogleAuthenticator {
4         
5         function __construct($totpskew=1, $hotpskew=10, $hotphuntvalue=200000) {
6                 // the hotpskew is how many tokens forward we look to find the input
7                 // code the user used
8                 $this->hotpSkew = $hotpskew;
9                 
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;
13                 
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;
20         }
21         
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();
27         
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
36                 
37                 return $data;
38         }
39         
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));
45                 
46                 if(!$deco) {
47                         $deco = $this->createEmptyData();
48                 }
49                 
50                 return $deco;
51         }
52         
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));
58                 
59                 return $this->putData($username, $enco);
60         }
61         
62
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";
70                         return false;
71                 }
72                 
73                 $data = $this->internalGetData($username);
74                 $data["tokentype"] = $tokentype;
75                 return $this->internalPutData($username, $data);
76                 
77         }
78         
79         
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;
87                 
88                 $token = $this->internalGetData($username);
89                 $token["tokenkey"] = $hkey;
90                 $token["tokentype"] = $ttype;
91                 
92                 if(!$this->internalPutData($username, $token)) {
93                         return false;
94                 }               
95                 return $key;
96         }
97         
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;
104                 return true;
105         }
106         
107         
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);              
116         }
117         
118         
119         // self explanitory?
120         function deleteUser($username) {
121                 // oh, we need to figure out how to do thi?
122                 $this->internalPutData($username, "");          
123         }
124         
125         // user has input their user name and some code, authenticate
126         // it
127         function authenticateUser($username, $code) {
128
129                 if(preg_match("/[0-9][0-9][0-9][0-9][0-9][0-9]/",$code)<1) return false;
130                 //error_log("begin auth user");
131                 $tokendata = $this->internalGetData($username);
132                 //$asdf = print_r($tokendata, true);
133                 //error_log("dat is $asdf");
134                 
135                 if($tokendata["tokenkey"] == "") {
136                         $errorText = "No Assigned Token";
137                         return false;
138                 }
139                 
140                 // TODO: check return value
141                 $ttype = $tokendata["tokentype"];
142                 $tlid = $tokendata["tokencounter"];
143                 $tkey = $tokendata["tokenkey"];
144                 
145                 //$asdf = print_r($tokendata, true);
146                 //error_log("dat is $asdf");
147                 switch($ttype) {
148                         case "HOTP":
149                                 error_log("in hotp");
150                                 $st = $tlid+1;
151                                 $en = $tlid+$this->hotpSkew;
152                                 for($i=$st; $i<$en; $i++) {
153                                         $stest = $this->oath_hotp($tkey, $i);
154                                         error_log("testing code: $code, $stest, $tkey, $tid");
155                                         if($code == $stest) {
156                                                 $tokendata["tokencounter"] = $i;
157                                                 $this->internalPutData($username, $tokendata);
158                                                 return true;
159                                         }
160                                 }
161                                 return false;
162                                 break;
163                         case "TOTP":
164                                 error_log("in totp");
165                                 $t_now = time();
166                                 $t_ear = $t_now - ($this->totpSkew*$tokendata["tokentimer"]);
167                                 $t_lat = $t_now + ($this->totpSkew*$tokendata["tokentimer"]);
168                                 $t_st = ((int)($t_ear/$tokendata["tokentimer"]));
169                                 $t_en = ((int)($t_lat/$tokendata["tokentimer"]));
170                                 //error_log("kmac: $t_now, $t_ear, $t_lat, $t_st, $t_en");
171                                 for($i=$t_st; $i<=$t_en; $i++) {
172                                         $stest = $this->oath_hotp($tkey, $i);
173                                         error_log("testing code: $code, $stest, $tkey\n");
174                                         if($code == $stest) {
175                                                 return true;
176                                         }
177                                 }
178                                 break;
179                         default:
180                                 return false;
181                 }
182                 
183                 return false;
184
185         }
186         
187         // this function allows a user to resync their key. If too
188         // many codes are called, we only check up to 20 codes in the future
189         // so if the user is at 21, they'll always fail. 
190         function resyncCode($username, $code1, $code2) {
191                 // 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
192                 // for HOTP tokens we start at x and go to x+20
193                 
194                 // for TOTP we go +/-1min TODO = remember that +/- 1min should
195                 // be changed based on stepping if we change the expiration time
196                 // for keys
197                 
198                 //              $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)');
199                 $tokendata = internalGetData($username);
200                 
201                 // TODO: check return value
202                 $ttype = $tokendata["tokentype"];
203                 $tlid = $tokendata["tokencounter"];
204                 $tkey = $tokendata["tokenkey"];
205                 
206                 if($tkey == "") {
207                         $this->errorText = "No Assigned Token";
208                         return false;
209                 }
210                 
211                 switch($ttype) {
212                         case "HOTP":
213                                 $st = 0;
214                                 $en = $this->hotpHuntValue;
215                                 for($i=$st; $i<$en; $i++) {
216                                         $stest = $this->oath_hotp($tkey, $i);
217                                         //echo "code: $code, $stest, $tkey\n";
218                                         if($code1 == $stest) {
219                                                 $stest2 = $this->oath_hotp($tkey, $i+1);
220                                                 if($code2 == $stest2) {
221                                                         $tokendata["tokencounter"] = $i+1;
222                                                         internalPutData($username, $tokendata);                                         
223                                                         return true;
224                                                 }
225                                         }
226                                 }
227                                 return false;
228                                 break;
229                         case "TOTP":
230                                 // ignore it?
231                                 break;
232                         default:
233                                 echo "how the frig did i end up here?";
234                 }
235                 
236                 return false;
237         }
238         
239         // gets the error text associated with the last error
240         function getErrorText() {
241                 return $this->errorText;
242         }
243         
244         // create a url compatibile with google authenticator.
245         function createURL($user) {
246                 // oddity in the google authenticator... hotp needs to be lowercase.
247                 $data = $this->internalGetData($user);
248                 $toktype = $data["tokentype"];
249                 $key = $this->helperhex2b32($data["tokenkey"]);
250                 $counter = $data["tokencounter"];
251                 $toktype = strtolower($toktype);
252                 if($toktype == "hotp") {
253                         $url = "otpauth://$toktype/$user?secret=$key&counter=$counter";
254                 } else {
255                         $url = "otpauth://$toktype/$user?secret=$key";
256                 }
257                 //echo "url: $url\n";
258                 return $url;
259         }
260         
261         // creeates a base 32 key (random)
262         function createBase32Key() {
263                 $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
264                 $key = "";
265                 for($i=0; $i<16; $i++) {
266                         $offset = rand(0,strlen($alphabet)-1);
267                         //echo "$i off is $offset\n";
268                         $key .= $alphabet[$offset];
269                 }
270                 
271                 return $key;
272         }
273         
274         // returns a hex key
275         function getKey($username) {
276                 $data = $this->internalGetData($username);
277                 $key = $data["tokenkey"];
278                 
279                 return $key;
280         }
281                 
282         // get key type
283         function getTokenType($username) {
284                 $data = $this->internalGetData($username);
285                 $toktype = $data["tokentype"];
286                 
287                 return $toktype;
288         }
289         
290         
291         // TODO: lots of error checking goes in here
292         function helperb322hex($b32) {
293         $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
294
295         $out = "";
296         $dous = "";
297
298         for($i = 0; $i < strlen($b32); $i++) {
299                 $in = strrpos($alphabet, $b32[$i]);
300                 $b = str_pad(base_convert($in, 10, 2), 5, "0", STR_PAD_LEFT);
301             $out .= $b;
302             $dous .= $b.".";
303         }
304
305         $ar = str_split($out,20);
306
307         //echo "$dous, $b\n";
308
309         //print_r($ar);
310         $out2 = "";
311         foreach($ar as $val) {
312                 $rv = str_pad(base_convert($val, 2, 16), 5, "0", STR_PAD_LEFT);
313                 //echo "rv: $rv from $val\n";
314                 $out2 .= $rv;
315
316         }
317         //echo "$out2\n";
318
319         return $out2;
320         }
321         
322         // TODO: lots of error checking goes in here
323         function helperhex2b32($hex) {
324         $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
325
326         $ar = str_split($hex, 5);
327
328         $out = "";
329         foreach($ar as $var) {
330                 $bc = base_convert($var, 16, 2);
331                 $bin = str_pad($bc, 20, "0", STR_PAD_LEFT);
332                 $out .= $bin;
333                 //echo "$bc was, $var is, $bin are\n";
334         }
335
336         $out2 = "";
337         $ar2 = str_split($out, 5);
338         foreach($ar2 as $var2) {
339                 $bc = base_convert($var2, 2, 10);
340                 $out2 .= $alphabet[$bc];
341         }
342
343         return $out2;
344         }
345         
346         // i've put alot of faith in the code from the
347         // php site's examples for the hash_hmac algorithm
348         // i assume its mostly correct but i should do
349         // some testing to verify this is actually the case
350         function oath_hotp($key, $counter)
351         {
352                 $key = pack("H*", $key);
353             $cur_counter = array(0,0,0,0,0,0,0,0);
354             for($i=7;$i>=0;$i--)
355             {
356                 $cur_counter[$i] = pack ('C*', $counter);
357                 $counter = $counter >> 8;
358             }
359             $bin_counter = implode($cur_counter);
360             // Pad to 8 chars
361             if (strlen ($bin_counter) < 8)
362             {
363                 $bin_counter = str_repeat (chr(0), 8 - strlen ($bin_counter)) . $bin_counter;
364             }
365         
366             // HMAC
367             $hash = hash_hmac ('sha1', $bin_counter, $key);
368             return str_pad($this->oath_truncate($hash), 6, "0", STR_PAD_LEFT);
369         }
370         
371         
372         function oath_truncate($hash, $length = 6)
373         {
374             // Convert to dec
375             foreach(str_split($hash,2) as $hex)
376             {
377                 $hmac_result[]=hexdec($hex);
378             }
379         
380             // Find offset
381             $offset = $hmac_result[19] & 0xf;
382         
383             // Algorithm from RFC
384             return
385             (
386                 (($hmac_result[$offset+0] & 0x7f) << 24 ) |
387                 (($hmac_result[$offset+1] & 0xff) << 16 ) |
388                 (($hmac_result[$offset+2] & 0xff) << 8 ) |
389                 ($hmac_result[$offset+3] & 0xff)
390             ) % pow(10,$length);
391         }
392         
393         
394         // some private data bits.
395         private $getDatafunction;
396         private $putDatafunction;
397         private $errorText;
398         private $errorCode;
399         
400         private $hotpSkew;
401         private $totpSkew;
402         
403         private $hotpHuntValue;
404         
405         
406         /*
407          * error codes
408          * 1: Auth Failed
409          * 2: No Key
410          * 3: input code was invalid (user input an invalid code - must be 6 numerical digits)
411          * 4: user doesnt exist?
412          * 5: key invalid
413          */
414 }
415 ?>