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