set token types
[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                 // TODO error checking
118                 return true;
119         }
120         
121         
122         // self explanitory?
123         function deleteUser($username) {
124                 // oh, we need to figure out how to do thi?
125                 $this->internalPutData($username, "");          
126         }
127         
128         // user has input their user name and some code, authenticate
129         // it
130         function authenticateUser($username, $code) {
131
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");
137                 
138                 if($tokendata["tokenkey"] == "") {
139                         $errorText = "No Assigned Token";
140                         return false;
141                 }
142                 
143                 // TODO: check return value
144                 $ttype = $tokendata["tokentype"];
145                 $tlid = $tokendata["tokencounter"];
146                 $tkey = $tokendata["tokenkey"];
147                 
148                 //$asdf = print_r($tokendata, true);
149                 //error_log("dat is $asdf");
150                 switch($ttype) {
151                         case "HOTP":
152                                 error_log("in hotp");
153                                 $st = $tlid+1;
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);
161                                                 return true;
162                                         }
163                                 }
164                                 return false;
165                                 break;
166                         case "TOTP":
167                                 error_log("in totp");
168                                 $t_now = time();
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) {
178                                                 return true;
179                                         }
180                                 }
181                                 break;
182                         default:
183                                 return false;
184                 }
185                 
186                 return false;
187
188         }
189         
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
196                 
197                 // for TOTP we go +/-1min TODO = remember that +/- 1min should
198                 // be changed based on stepping if we change the expiration time
199                 // for keys
200                 
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);
203                 
204                 // TODO: check return value
205                 $ttype = $tokendata["tokentype"];
206                 $tlid = $tokendata["tokencounter"];
207                 $tkey = $tokendata["tokenkey"];
208                 
209                 if($tkey == "") {
210                         $this->errorText = "No Assigned Token";
211                         return false;
212                 }
213                 
214                 switch($ttype) {
215                         case "HOTP":
216                                 $st = 0;
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);                                          
226                                                         return true;
227                                                 }
228                                         }
229                                 }
230                                 return false;
231                                 break;
232                         case "TOTP":
233                                 // ignore it?
234                                 break;
235                         default:
236                                 echo "how the frig did i end up here?";
237                 }
238                 
239                 return false;
240         }
241         
242         // gets the error text associated with the last error
243         function getErrorText() {
244                 return $this->errorText;
245         }
246         
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"]);
253
254                 // token counter should be one more then current token value, otherwise
255                 // it gets confused
256                 $counter = $data["tokencounter"]+1;
257                 $toktype = strtolower($toktype);
258                 if($toktype == "hotp") {
259                         $url = "otpauth://$toktype/$user?secret=$key&counter=$counter";
260                 } else {
261                         $url = "otpauth://$toktype/$user?secret=$key";
262                 }
263                 //echo "url: $url\n";
264                 return $url;
265         }
266         
267         // creeates a base 32 key (random)
268         function createBase32Key() {
269                 $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
270                 $key = "";
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];
275                 }
276                 
277                 return $key;
278         }
279         
280         // returns a hex key
281         function getKey($username) {
282                 $data = $this->internalGetData($username);
283                 $key = $data["tokenkey"];
284                 
285                 return $key;
286         }
287                 
288         // get key type
289         function getTokenType($username) {
290                 $data = $this->internalGetData($username);
291                 $toktype = $data["tokentype"];
292                 
293                 return $toktype;
294         }
295         
296         
297         // TODO: lots of error checking goes in here
298         function helperb322hex($b32) {
299         $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
300
301         $out = "";
302         $dous = "";
303
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);
307             $out .= $b;
308             $dous .= $b.".";
309         }
310
311         $ar = str_split($out,20);
312
313         //echo "$dous, $b\n";
314
315         //print_r($ar);
316         $out2 = "";
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";
320                 $out2 .= $rv;
321
322         }
323         //echo "$out2\n";
324
325         return $out2;
326         }
327         
328         // TODO: lots of error checking goes in here
329         function helperhex2b32($hex) {
330         $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
331
332         $ar = str_split($hex, 5);
333
334         $out = "";
335         foreach($ar as $var) {
336                 $bc = base_convert($var, 16, 2);
337                 $bin = str_pad($bc, 20, "0", STR_PAD_LEFT);
338                 $out .= $bin;
339                 //echo "$bc was, $var is, $bin are\n";
340         }
341
342         $out2 = "";
343         $ar2 = str_split($out, 5);
344         foreach($ar2 as $var2) {
345                 $bc = base_convert($var2, 2, 10);
346                 $out2 .= $alphabet[$bc];
347         }
348
349         return $out2;
350         }
351         
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)
357         {
358                 $key = pack("H*", $key);
359             $cur_counter = array(0,0,0,0,0,0,0,0);
360             for($i=7;$i>=0;$i--)
361             {
362                 $cur_counter[$i] = pack ('C*', $counter);
363                 $counter = $counter >> 8;
364             }
365             $bin_counter = implode($cur_counter);
366             // Pad to 8 chars
367             if (strlen ($bin_counter) < 8)
368             {
369                 $bin_counter = str_repeat (chr(0), 8 - strlen ($bin_counter)) . $bin_counter;
370             }
371         
372             // HMAC
373             $hash = hash_hmac ('sha1', $bin_counter, $key);
374             return str_pad($this->oath_truncate($hash), 6, "0", STR_PAD_LEFT);
375         }
376         
377         
378         function oath_truncate($hash, $length = 6)
379         {
380             // Convert to dec
381             foreach(str_split($hash,2) as $hex)
382             {
383                 $hmac_result[]=hexdec($hex);
384             }
385         
386             // Find offset
387             $offset = $hmac_result[19] & 0xf;
388         
389             // Algorithm from RFC
390             return
391             (
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)
396             ) % pow(10,$length);
397         }
398         
399         
400         // some private data bits.
401         private $getDatafunction;
402         private $putDatafunction;
403         private $errorText;
404         private $errorCode;
405         
406         private $hotpSkew;
407         private $totpSkew;
408         
409         private $hotpHuntValue;
410         
411         
412         /*
413          * error codes
414          * 1: Auth Failed
415          * 2: No Key
416          * 3: input code was invalid (user input an invalid code - must be 6 numerical digits)
417          * 4: user doesnt exist?
418          * 5: key invalid
419          */
420 }
421 ?>