Created a provisioning example
[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, $ttype="HOTP", $key = "") {
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                 return true;
80         }
81         
82         
83         // sets the key for a user - this is assuming you dont want
84         // to use one created by the application. returns false
85         // if the key is invalid or the user doesn't exist.
86         function setUserKey($username, $key) {
87                 // consider scrapping this
88                 $token = $this->internalGetData($username);
89                 $token["tokenkey"] = $key;
90                 $this->internalPutData($username, $token);              
91         }
92         
93         
94         // self explanitory?
95         function deleteUser($username) {
96                 // oh, we need to figure out how to do thi?
97                 $data = $this->internalGetData($username);
98                 $data["tokenkey"] = "";
99                 $this->internalPutData($username);              
100         }
101         
102         // user has input their user name and some code, authenticate
103         // it
104         function authenticateUser($username, $code) {
105
106                 if(preg_match("/[0-9][0-9][0-9][0-9][0-9][0-9]/",$code)<1) return false;
107                 error_log("begin auth user");
108                 $tokendata = $this->internalGetData($username);
109                 $asdf = print_r($tokendata, true);
110                 error_log("dat is $asdf");
111                 
112                 if($tokendata["tokenkey"] == "") {
113                         $errorText = "No Assigned Token";
114                         return false;
115                 }
116                 
117                 // TODO: check return value
118                 $ttype = $tokendata["tokentype"];
119                 $tlid = $tokendata["tokencounter"];
120                 $tkey = $tokendata["tokenkey"];
121                 
122                 $asdf = print_r($tokendata, true);
123                 error_log("dat is $asdf");
124                 switch($ttype) {
125                         case "HOTP":
126                                 $st = $tlid;
127                                 $en = $tlid+20;
128                                 for($i=$st; $i<$en; $i++) {
129                                         $stest = $this->oath_hotp($tkey, $i);
130                                         //error_log("code: $code, $stest, $tkey, $tid");
131                                         if($code == $stest) {
132                                                 $tokendata["tokencounter"] = $i;
133                                                 $this->internalPutData($username, $tokendata);
134                                                 return true;
135                                         }
136                                 }
137                                 return false;
138                                 break;
139                         case "TOTP":
140                                 $t_now = time();
141                                 $t_ear = $t_now - 45;
142                                 $t_lat = $t_now + 60;
143                                 $t_st = ((int)($t_ear/30));
144                                 $t_en = ((int)($t_lat/30));
145                                 //error_log("kmac: $t_now, $t_ear, $t_lat, $t_st, $t_en");
146                                 for($i=$t_st; $i<=$t_en; $i++) {
147                                         $stest = $this->oath_hotp($tkey, $i);
148                                         //error_log("code: $code, $stest, $tkey\n");
149                                         if($code == $stest) {
150                                                 return true;
151                                         }
152                                 }
153                                 break;
154                         default:
155                                 echo "how the frig did i end up here?";
156                 }
157                 
158                 return false;
159
160         }
161         
162         // this function allows a user to resync their key. If too
163         // many codes are called, we only check up to 20 codes in the future
164         // so if the user is at 21, they'll always fail. 
165         function resyncCode($username, $code1, $code2) {
166                 // 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
167                 // for HOTP tokens we start at x and go to x+20
168                 
169                 // for TOTP we go +/-1min TODO = remember that +/- 1min should
170                 // be changed based on stepping if we change the expiration time
171                 // for keys
172                 
173                 //              $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)');
174                 $tokendata = internalGetData($username);
175                 
176                 // TODO: check return value
177                 $ttype = $tokendata["tokentype"];
178                 $tlid = $tokendata["tokencounter"];
179                 $tkey = $tokendata["tokenkey"];
180                 
181                 if($tkey == "") {
182                         $this->errorText = "No Assigned Token";
183                         return false;
184                 }
185                 
186                 switch($ttype) {
187                         case "HOTP":
188                                 $st = 0;
189                                 $en = 200000;
190                                 for($i=$st; $i<$en; $i++) {
191                                         $stest = $this->oath_hotp($tkey, $i);
192                                         //echo "code: $code, $stest, $tkey\n";
193                                         if($code1 == $stest) {
194                                                 $stest2 = $this->oath_hotp($tkey, $i+1);
195                                                 if($code2 == $stest2) {
196                                                         $tokendata["tokencounter"] = $i+1;
197                                                         internalPutData($username, $tokendata);                                         
198                                                         return true;
199                                                 }
200                                         }
201                                 }
202                                 return false;
203                                 break;
204                         case "TOTP":
205                                 break;
206                         default:
207                                 echo "how the frig did i end up here?";
208                 }
209                 
210                 return false;
211         }
212         
213         // gets the error text associated with the last error
214         function getErrorText() {
215                 return $this->errorText;
216         }
217         
218         // create a url compatibile with google authenticator.
219         function createURL($user) {
220                 // oddity in the google authenticator... hotp needs to be lowercase.
221                 $data = $this->internalGetData($user);
222                 $toktype = $data["tokentype"];
223                 $key = $this->helperhex2b32($data["tokenkey"]);
224                 $toktype = strtolower($toktype);
225                 if($toktype == "hotp") {
226                         $url = "otpauth://$toktype/$user?secret=$key&counter=1";
227                 } else {
228                         $url = "otpauth://$toktype/$user?secret=$key";
229                 }
230                 //echo "url: $url\n";
231                 return $url;
232         }
233         
234         // creeates a base 32 key (random)
235         function createBase32Key() {
236                 $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
237                 $key = "";
238                 for($i=0; $i<16; $i++) {
239                         $offset = rand(0,strlen($alphabet)-1);
240                         //echo "$i off is $offset\n";
241                         $key .= $alphabet[$offset];
242                 }
243                 
244                 return $key;
245         }
246         
247         // returns a hex key
248         function getKey($username) {
249                 $data = $this->internalGetData($username);
250                 $key = $data["tokenkey"];
251                 
252                 return $key;
253         }
254                 
255         // get key type
256         function getTokenType($username) {
257                 $data = $this->internalGetData($username);
258                 $toktype = $data["tokentype"];
259                 
260                 return $toktype;
261         }
262         
263         
264         function helperb322hex($b32) {
265         $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
266
267         $out = "";
268         $dous = "";
269
270         for($i = 0; $i < strlen($b32); $i++) {
271                 $in = strrpos($alphabet, $b32[$i]);
272                 $b = str_pad(base_convert($in, 10, 2), 5, "0", STR_PAD_LEFT);
273             $out .= $b;
274             $dous .= $b.".";
275         }
276
277         $ar = str_split($out,20);
278
279         //echo "$dous, $b\n";
280
281         //print_r($ar);
282         $out2 = "";
283         foreach($ar as $val) {
284                 $rv = str_pad(base_convert($val, 2, 16), 5, "0", STR_PAD_LEFT);
285                 //echo "rv: $rv from $val\n";
286                 $out2 .= $rv;
287
288         }
289         //echo "$out2\n";
290
291         return $out2;
292         }
293         
294         function helperhex2b32($hex) {
295         $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
296
297         $ar = str_split($hex, 5);
298
299         $out = "";
300         foreach($ar as $var) {
301                 $bc = base_convert($var, 16, 2);
302                 $bin = str_pad($bc, 20, "0", STR_PAD_LEFT);
303                 $out .= $bin;
304                 //echo "$bc was, $var is, $bin are\n";
305         }
306
307         $out2 = "";
308         $ar2 = str_split($out, 5);
309         foreach($ar2 as $var2) {
310                 $bc = base_convert($var2, 2, 10);
311                 $out2 .= $alphabet[$bc];
312         }
313
314         return $out2;
315         }
316         
317         function oath_hotp($key, $counter)
318         {
319                 $key = pack("H*", $key);
320             $cur_counter = array(0,0,0,0,0,0,0,0);
321             for($i=7;$i>=0;$i--)
322             {
323                 $cur_counter[$i] = pack ('C*', $counter);
324                 $counter = $counter >> 8;
325             }
326             $bin_counter = implode($cur_counter);
327             // Pad to 8 chars
328             if (strlen ($bin_counter) < 8)
329             {
330                 $bin_counter = str_repeat (chr(0), 8 - strlen ($bin_counter)) . $bin_counter;
331             }
332         
333             // HMAC
334             $hash = hash_hmac ('sha1', $bin_counter, $key);
335             return str_pad($this->oath_truncate($hash), 6, "0", STR_PAD_LEFT);
336         }
337         
338         function oath_truncate($hash, $length = 6)
339         {
340             // Convert to dec
341             foreach(str_split($hash,2) as $hex)
342             {
343                 $hmac_result[]=hexdec($hex);
344             }
345         
346             // Find offset
347             $offset = $hmac_result[19] & 0xf;
348         
349             // Algorithm from RFC
350             return
351             (
352                 (($hmac_result[$offset+0] & 0x7f) << 24 ) |
353                 (($hmac_result[$offset+1] & 0xff) << 16 ) |
354                 (($hmac_result[$offset+2] & 0xff) << 8 ) |
355                 ($hmac_result[$offset+3] & 0xff)
356             ) % pow(10,$length);
357         }
358         
359         
360         // some private data bits.
361         private $getDatafunction;
362         private $putDatafunction;
363         private $errorText;
364         private $errorCode;
365         
366         /*
367          * error codes
368          * 1: Auth Failed
369          * 2: No Key
370          * 3: input code was invalid (user input an invalid code - must be 6 numerical digits)
371          * 4: user doesnt exist?
372          * 5: key invalid
373          */
374 }
375 ?>