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