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