moved the main class to an abstract super
[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 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 = getData($username);
43                 $deco = unserialize(base64_decode($data));
44                 
45                 if(!$deco) {
46                         $deco = createEmptyData();
47                 }
48                 
49                 return $deco;
50         }
51         
52
53         function internalPutData($username, $data) {
54                 $enco = base64_encode(serialize($data));
55                 
56                 return 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 = internalGetData($username);
70                 $data["tokentype"] = $tokentype;
71                 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 = internalGetData($username);
83                 $token["tokenkey"] = $hkey;
84                 $token["tokentype"] = $ttype;
85                 
86                 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 = internalGetData($username);
97                 $token["tokenkey"] = $key;
98                 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 = internalGetData($username);
112                 $data["tokenkey"] = "";
113                 internalPutData($username);             
114         }
115         
116         // user has input their user name and some code, authenticate
117         // it
118         function authenticateUser($username, $code) {
119
120                 $tokendata = internalGetData($username);
121                 
122                 if($tokendata["tokenkey"] == "") {
123                         $errorText = "No Assigned Token";
124                         return false;
125                 }
126                 
127                 // TODO: check return value
128                 $ttype = $tokendata["tokentype"];
129                 $tlid = $tokendata["tokencounter"];
130                 $tkey = $tokendata["tokenkey"];
131                 switch($ttype) {
132                         case "HOTP":
133                                 $st = $tlid;
134                                 $en = $tlid+20;
135                                 for($i=$st; $i<$en; $i++) {
136                                         $stest = $this->oath_hotp($tkey, $i);
137                                         //error_log("code: $code, $stest, $tkey, $tid");
138                                         if($code == $stest) {
139                                                 $tokendata["tokencounter"] = $i;
140                                                 internalPutData($username, $tokendata);
141                                                 return true;
142                                         }
143                                 }
144                                 return false;
145                                 break;
146                         case "TOTP":
147                                 $t_now = time();
148                                 $t_ear = $t_now - 45;
149                                 $t_lat = $t_now + 60;
150                                 $t_st = ((int)($t_ear/30));
151                                 $t_en = ((int)($t_lat/30));
152                                 //error_log("kmac: $t_now, $t_ear, $t_lat, $t_st, $t_en");
153                                 for($i=$t_st; $i<=$t_en; $i++) {
154                                         $stest = $this->oath_hotp($tkey, $i);
155                                         //error_log("code: $code, $stest, $tkey\n");
156                                         if($code == $stest) {
157                                                 return true;
158                                         }
159                                 }
160                                 break;
161                         default:
162                                 echo "how the frig did i end up here?";
163                 }
164                 
165                 return false;
166
167         }
168         
169         // this function allows a user to resync their key. If too
170         // many codes are called, we only check up to 20 codes in the future
171         // so if the user is at 21, they'll always fail. 
172         function resyncCode($username, $code1, $code2) {
173                 // 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
174                 // for HOTP tokens we start at x and go to x+20
175                 
176                 // for TOTP we go +/-1min TODO = remember that +/- 1min should
177                 // be changed based on stepping if we change the expiration time
178                 // for keys
179                 
180                 //              $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)');
181                 $tokendata = internalGetData($username);
182                 
183                 // TODO: check return value
184                 $ttype = $tokendata["tokentype"];
185                 $tlid = $tokendata["tokencounter"];
186                 $tkey = $tokendata["tokenkey"];
187                 
188                 if($tkey == "") {
189                         $this->errorText = "No Assigned Token";
190                         return false;
191                 }
192                 
193                 switch($ttype) {
194                         case "HOTP":
195                                 $st = 0;
196                                 $en = 200000;
197                                 for($i=$st; $i<$en; $i++) {
198                                         $stest = $this->oath_hotp($tkey, $i);
199                                         //echo "code: $code, $stest, $tkey\n";
200                                         if($code1 == $stest) {
201                                                 $stest2 = $this->oath_hotp($tkey, $i+1);
202                                                 if($code2 == $stest2) {
203                                                         $tokendata["tokencounter"] = $i+1;
204                                                         internalPutData($username, $tokendata);                                         
205                                                         return true;
206                                                 }
207                                         }
208                                 }
209                                 return false;
210                                 break;
211                         case "TOTP":
212                                 break;
213                         default:
214                                 echo "how the frig did i end up here?";
215                 }
216                 
217                 return false;
218         }
219         
220         // gets the error text associated with the last error
221         function getErrorText() {
222                 return $this->errorText;
223         }
224         
225         // create a url compatibile with google authenticator.
226         function createURL($user, $key,$toktype = "HOTP") {
227                 // oddity in the google authenticator... hotp needs to be lowercase.
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         
252         function helperb322hex($b32) {
253         $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
254
255         $out = "";
256         $dous = "";
257
258         for($i = 0; $i < strlen($b32); $i++) {
259                 $in = strrpos($alphabet, $b32[$i]);
260                 $b = str_pad(base_convert($in, 10, 2), 5, "0", STR_PAD_LEFT);
261             $out .= $b;
262             $dous .= $b.".";
263         }
264
265         $ar = str_split($out,20);
266
267         //echo "$dous, $b\n";
268
269         //print_r($ar);
270         $out2 = "";
271         foreach($ar as $val) {
272                 $rv = str_pad(base_convert($val, 2, 16), 5, "0", STR_PAD_LEFT);
273                 //echo "rv: $rv from $val\n";
274                 $out2 .= $rv;
275
276         }
277         //echo "$out2\n";
278
279         return $out2;
280         }
281         
282         function helperhex2b32($hex) {
283         $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
284
285         $ar = str_split($hex, 5);
286
287         $out = "";
288         foreach($ar as $var) {
289                 $bc = base_convert($var, 16, 2);
290                 $bin = str_pad($bc, 20, "0", STR_PAD_LEFT);
291                 $out .= $bin;
292                 //echo "$bc was, $var is, $bin are\n";
293         }
294
295         $out2 = "";
296         $ar2 = str_split($out, 5);
297         foreach($ar2 as $var2) {
298                 $bc = base_convert($var2, 2, 10);
299                 $out2 .= $alphabet[$bc];
300         }
301
302         return $out2;
303         }
304         
305         function oath_hotp($key, $counter)
306         {
307                 $key = pack("H*", $key);
308             $cur_counter = array(0,0,0,0,0,0,0,0);
309             for($i=7;$i>=0;$i--)
310             {
311                 $cur_counter[$i] = pack ('C*', $counter);
312                 $counter = $counter >> 8;
313             }
314             $bin_counter = implode($cur_counter);
315             // Pad to 8 chars
316             if (strlen ($bin_counter) < 8)
317             {
318                 $bin_counter = str_repeat (chr(0), 8 - strlen ($bin_counter)) . $bin_counter;
319             }
320         
321             // HMAC
322             $hash = hash_hmac ('sha1', $bin_counter, $key);
323             return str_pad($this->oath_truncate($hash), 6, "0", STR_PAD_LEFT);
324         }
325         
326         function oath_truncate($hash, $length = 6)
327         {
328             // Convert to dec
329             foreach(str_split($hash,2) as $hex)
330             {
331                 $hmac_result[]=hexdec($hex);
332             }
333         
334             // Find offset
335             $offset = $hmac_result[19] & 0xf;
336         
337             // Algorithm from RFC
338             return
339             (
340                 (($hmac_result[$offset+0] & 0x7f) << 24 ) |
341                 (($hmac_result[$offset+1] & 0xff) << 16 ) |
342                 (($hmac_result[$offset+2] & 0xff) << 8 ) |
343                 ($hmac_result[$offset+3] & 0xff)
344             ) % pow(10,$length);
345         }
346         
347         
348         // some private data bits.
349         private $getDatafunction;
350         private $putDatafunction;
351         private $errorText;
352 }
353 ?>