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