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