just thinking out loud in the main lib.php
[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         // this could get ugly for large databases.. we'll worry about that if it ever happens.
48         function getUserList() {
49                 $func = $this->getDataFunction;
50                 return $func("userlist", "");
51         }
52         
53         // set the token type the user it going to use.
54         // this defaults to HOTP - we only do 30s token
55         // so lets not be able to set that yet
56         function setupTokenType($username, $tokentype) {
57                 if($tokentype!="HOTP" and $tokentype!="TOTP") {
58                         $errorText = "Invalid Token Type";
59                         return false;
60                 }
61                 
62                 $put["username"] = $username;
63                 $put["tokentype"] = $tokentype;
64                 $func = $this->putDataFunction;
65                 $func("settokentype", $put);
66                 
67                 return true;    
68         }
69         
70         
71         // create "user" with insert
72         function setUser($username, $key = "", $ttype="HOTP") {
73                 if($key == "") $key = $this->createBase32Key();
74                 $hkey = $this->helperb322hex($key);
75                 
76                 $token["username"] = $username;
77                 $token["tokenkey"] = $hkey;
78                 $token["tokentype"] = $ttype;
79                 
80                 $func = $this->putDataFunction;
81                 $func("setusertoken", $token);
82                 
83                 return $key;
84         }
85         
86         
87         // sets the key for a user - this is assuming you dont want
88         // to use one created by the application. returns false
89         // if the key is invalid or the user doesn't exist.
90         function setUserKey($username, $key) {
91                 // consider scrapping this
92         }
93         
94         
95         // have user?
96         function userExists($username) {
97                 // need to think about this
98         }
99         
100         
101         // self explanitory?
102         function deleteUser($username) {
103                 $func = $this->putDataFunction;
104                 $func("deleteusertoken", $username);
105         }
106         
107         // user has input their user name and some code, authenticate
108         // it
109         function authenticateUser($username, $code) {
110                 
111                 $func = $this->getDataFunction;
112                 $tokendata = $func("gettoken", $username);
113                 
114                 // TODO: check return value
115                 $ttype = $tokendata["tokentype"];
116                 $tlid = $tokendata["tokencounter"];
117                 $tkey = $tokendata["tokenkey"];
118                 switch($ttype) {
119                         case "HOTP":
120                                 $st = $tlid;
121                                 $en = $tlid+20;
122                                 for($i=$st; $i<$en; $i++) {
123                                         $stest = $this->oath_hotp($tkey, $i);
124                                         //error_log("code: $code, $stest, $tkey, $tid");
125                                         if($code == $stest) {
126                                                 $tokenset["username"] = $username;
127                                                 $tokenset["tokencounter"] = $i;
128                                                 
129                                                 $func = $this->putDataFunction;
130                                                 $func("settokencounter", $tokenset);
131                                                 return true;
132                                         }
133                                 }
134                                 return false;
135                                 break;
136                         case "TOTP":
137                                 $t_now = time();
138                                 $t_ear = $t_now - 45;
139                                 $t_lat = $t_now + 60;
140                                 $t_st = ((int)($t_ear/30));
141                                 $t_en = ((int)($t_lat/30));
142                                 //error_log("kmac: $t_now, $t_ear, $t_lat, $t_st, $t_en");
143                                 for($i=$t_st; $i<=$t_en; $i++) {
144                                         $stest = $this->oath_hotp($tkey, $i);
145                                         //error_log("code: $code, $stest, $tkey\n");
146                                         if($code == $stest) {
147                                                 return true;
148                                         }
149                                 }
150                                 break;
151                         default:
152                                 echo "how the frig did i end up here?";
153                 }
154                 
155                 return false;
156
157         }
158         
159         // this function allows a user to resync their key. If too
160         // many codes are called, we only check up to 20 codes in the future
161         // so if the user is at 21, they'll always fail. 
162         function resyncCode($username, $code1, $code2) {
163                 // 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
164                 // for HOTP tokens we start at x and go to x+20
165                 
166                 // for TOTP we go +/-1min TODO = remember that +/- 1min should
167                 // be changed based on stepping if we change the expiration time
168                 // for keys
169                 
170                 //              $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)');
171                 
172                 $func = $this->getDataFunction;
173                 $tokendata = $func("gettoken", $username);
174                 
175                 // TODO: check return value
176                 $ttype = $tokendata["tokentype"];
177                 $tlid = $tokendata["tokencounter"];
178                 $tkey = $tokendata["tokenkey"];
179                 
180                 switch($ttype) {
181                         case "HOTP":
182                                 $st = 0;
183                                 $en = 200000;
184                                 for($i=$st; $i<$en; $i++) {
185                                         $stest = $this->oath_hotp($tkey, $i);
186                                         //echo "code: $code, $stest, $tkey\n";
187                                         if($code1 == $stest) {
188                                                 $stest2 = $this->oath_hotp($tkey, $i+1);
189                                                 if($code2 == $stest2) {
190                                                         $tokenset["username"] = $username;
191                                                         $tokenset["tokencounter"] = $i+1;
192                                                 
193                                                         $func = $this->putDataFunction;
194                                                         $func("settokencounter", $tokenset);
195                                                         return true;
196                                                 }
197                                         }
198                                 }
199                                 return false;
200                                 break;
201                         case "TOTP":
202                                 break;
203                         default:
204                                 echo "how the frig did i end up here?";
205                 }
206                 
207                 return false;
208                 
209         }
210         
211         // gets the error text associated with the last error
212         function getErrorText() {
213                 return $this->errorText;
214         }
215         
216         // create a url compatibile with google authenticator.
217         function createURL($user, $key,$toktype = "HOTP") {
218                 // oddity in the google authenticator... hotp needs to be lowercase.
219                 $toktype = strtolower($toktype);
220                 if($toktype == "hotp") {
221                         $url = "otpauth://$toktype/$user?secret=$key&counter=1";
222                 } else {
223                         $url = "otpauth://$toktype/$user?secret=$key";
224                 }
225                 //echo "url: $url\n";
226                 return $url;
227         }
228         
229         // creeates a base 32 key (random)
230         function createBase32Key() {
231                 $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
232                 $key = "";
233                 for($i=0; $i<16; $i++) {
234                         $offset = rand(0,strlen($alphabet)-1);
235                         //echo "$i off is $offset\n";
236                         $key .= $alphabet[$offset];
237                 }
238                 
239                 return $key;
240         }
241                 
242         
243         function helperb322hex($b32) {
244         $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
245
246         $out = "";
247         $dous = "";
248
249         for($i = 0; $i < strlen($b32); $i++) {
250                 $in = strrpos($alphabet, $b32[$i]);
251                 $b = str_pad(base_convert($in, 10, 2), 5, "0", STR_PAD_LEFT);
252             $out .= $b;
253             $dous .= $b.".";
254         }
255
256         $ar = str_split($out,20);
257
258         //echo "$dous, $b\n";
259
260         //print_r($ar);
261         $out2 = "";
262         foreach($ar as $val) {
263                 $rv = str_pad(base_convert($val, 2, 16), 5, "0", STR_PAD_LEFT);
264                 //echo "rv: $rv from $val\n";
265                 $out2 .= $rv;
266
267         }
268         //echo "$out2\n";
269
270         return $out2;
271         }
272         
273         function helperhex2b32($hex) {
274         $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
275
276         $ar = str_split($hex, 5);
277
278         $out = "";
279         foreach($ar as $var) {
280                 $bc = base_convert($var, 16, 2);
281                 $bin = str_pad($bc, 20, "0", STR_PAD_LEFT);
282                 $out .= $bin;
283                 //echo "$bc was, $var is, $bin are\n";
284         }
285
286         $out2 = "";
287         $ar2 = str_split($out, 5);
288         foreach($ar2 as $var2) {
289                 $bc = base_convert($var2, 2, 10);
290                 $out2 .= $alphabet[$bc];
291         }
292
293         return $out2;
294         }
295         
296         function oath_hotp($key, $counter)
297         {
298                 $key = pack("H*", $key);
299             $cur_counter = array(0,0,0,0,0,0,0,0);
300             for($i=7;$i>=0;$i--)
301             {
302                 $cur_counter[$i] = pack ('C*', $counter);
303                 $counter = $counter >> 8;
304             }
305             $bin_counter = implode($cur_counter);
306             // Pad to 8 chars
307             if (strlen ($bin_counter) < 8)
308             {
309                 $bin_counter = str_repeat (chr(0), 8 - strlen ($bin_counter)) . $bin_counter;
310             }
311         
312             // HMAC
313             $hash = hash_hmac ('sha1', $bin_counter, $key);
314             return str_pad($this->oath_truncate($hash), 6, "0", STR_PAD_LEFT);
315         }
316         
317         function oath_truncate($hash, $length = 6)
318         {
319             // Convert to dec
320             foreach(str_split($hash,2) as $hex)
321             {
322                 $hmac_result[]=hexdec($hex);
323             }
324         
325             // Find offset
326             $offset = $hmac_result[19] & 0xf;
327         
328             // Algorithm from RFC
329             return
330             (
331                 (($hmac_result[$offset+0] & 0x7f) << 24 ) |
332                 (($hmac_result[$offset+1] & 0xff) << 16 ) |
333                 (($hmac_result[$offset+2] & 0xff) << 8 ) |
334                 ($hmac_result[$offset+3] & 0xff)
335             ) % pow(10,$length);
336         }
337         
338         
339         // some private data bits.
340         private $getDatafunction;
341         private $putDatafunction;
342         private $errorText;
343 }
344 ?>