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