3 abstract class GoogleAuthenticator {
5 function __construct($totpskew=1, $hotpskew=10, $hotphuntvalue=200000) {
6 // the hotpskew is how many tokens forward we look to find the input
8 $this->hotpSkew = $hotpskew;
10 // the totpskew value is how many tokens either side of the current
11 // token we should check, based on a time skew.
12 $this->totpSkew = $totpskew;
14 // the hotphuntvalue is what we use to resync tokens.
15 // when a user resyncs, we search from 0 to $hutphutvalue to find
16 // the two token codes the user has entered - 200000 seems like overkill
17 // really as i cant imagine any token out there would ever make it
18 // past 200000 token code requests.
19 $this->hotpHuntValue = $hotphuntvalue;
22 // pure abstract functions that need to be overloaded when
23 // creating a sub class
24 abstract function getData($username);
25 abstract function putData($username, $data);
26 abstract function getUsers();
28 // a function to create an empty data structure, filled with some defaults
29 function createEmptyData() {
30 $data["tokenkey"] = ""; // the token key
31 $data["tokentype"] = "HOTP"; // the token type
32 $data["tokentimer"] = 30; // the token timer (For totp) and not supported by ga yet
33 $data["tokencounter"] = 1; // the token counter for hotp
34 $data["tokenalgorithm"] = "SHA1"; // the token algorithm (not supported by ga yet)
35 $data["user"] = ""; // a place for implementors to store their own data
40 // custom data field manipulation bits
41 function setCustomData($username, $data) {
42 $data = $this->internalGetData($username);
44 $this->internalPutData($username, $data);
47 function getCustomData($username) {
48 $data = $this->internalGetData($username);
49 $custom = $data["user"];
54 // an internal funciton to get data from the overloaded functions
55 // and turn them into php arrays.
56 function internalGetData($username) {
57 $data = $this->getData($username);
58 $deco = unserialize(base64_decode($data));
61 $deco = $this->createEmptyData();
67 // the function used inside the class to put the data into the
68 // datastore using the overloaded data saving class
69 function internalPutData($username, $data) {
70 if($data == "") $enco = "";
71 else $enco = base64_encode(serialize($data));
73 return $this->putData($username, $enco);
77 // set the token type the user it going to use.
78 // this defaults to HOTP - we only do 30s token
79 // so lets not be able to set that yet
80 function setTokenType($username, $tokentype) {
81 $tokentype = strtoupper($tokentype);
82 if($tokentype!="HOTP" && $tokentype!="TOTP") {
83 $errorText = "Invalid Token Type";
87 $data = $this->internalGetData($username);
88 $data["tokentype"] = $tokentype;
89 return $this->internalPutData($username, $data);
94 // create "user" with insert
95 function setUser($username, $ttype="HOTP", $key = "", $hexkey="") {
96 $ttype = strtoupper($ttype);
97 if($ttype != "HOTP" && $ttype !="TOTP") return false;
98 if($key == "") $key = $this->createBase32Key();
99 $hkey = $this->helperb322hex($key);
100 if($hexkey != "") $hkey = $hexkey;
102 $token = $this->internalGetData($username);
103 $token["tokenkey"] = $hkey;
104 $token["tokentype"] = $ttype;
106 if(!$this->internalPutData($username, $token)) {
112 // a function to determine if the user has an actual token
113 function hasToken($username) {
114 $token = $this->internalGetData($username);
115 // TODO: change this to a pattern match for an actual key
116 if(!isset($token["tokenkey"])) return false;
117 if($token["tokenkey"] == "") return false;
122 // sets the key for a user - this is assuming you dont want
123 // to use one created by the application. returns false
124 // if the key is invalid or the user doesn't exist.
125 function setUserKey($username, $key) {
126 // consider scrapping this
127 $token = $this->internalGetData($username);
128 $token["tokenkey"] = $key;
129 $this->internalPutData($username, $token);
131 // TODO error checking
137 function deleteUser($username) {
138 // oh, we need to figure out how to do thi?
139 $this->internalPutData($username, "");
144 // user has input their user name and some code, authenticate
146 function authenticateUser($username, $code) {
148 if(preg_match("/[0-9][0-9][0-9][0-9][0-9][0-9]/",$code)<1) return false;
149 //error_log("begin auth user");
150 $tokendata = $this->internalGetData($username);
151 //$asdf = print_r($tokendata, true);
152 //error_log("dat is $asdf");
154 if($tokendata["tokenkey"] == "") {
155 $errorText = "No Assigned Token";
159 // TODO: check return value
160 $ttype = $tokendata["tokentype"];
161 $tlid = $tokendata["tokencounter"];
162 $tkey = $tokendata["tokenkey"];
164 //$asdf = print_r($tokendata, true);
165 //error_log("dat is $asdf");
168 error_log("in hotp");
170 $en = $tlid+$this->hotpSkew;
171 for($i=$st; $i<$en; $i++) {
172 $stest = $this->oath_hotp($tkey, $i);
173 //error_log("testing code: $code, $stest, $tkey, $tid");
174 if($code == $stest) {
175 $tokendata["tokencounter"] = $i;
176 $this->internalPutData($username, $tokendata);
183 error_log("in totp");
185 $t_ear = $t_now - ($this->totpSkew*$tokendata["tokentimer"]);
186 $t_lat = $t_now + ($this->totpSkew*$tokendata["tokentimer"]);
187 $t_st = ((int)($t_ear/$tokendata["tokentimer"]));
188 $t_en = ((int)($t_lat/$tokendata["tokentimer"]));
189 //error_log("kmac: $t_now, $t_ear, $t_lat, $t_st, $t_en");
190 for($i=$t_st; $i<=$t_en; $i++) {
191 $stest = $this->oath_hotp($tkey, $i);
192 error_log("testing code: $code, $stest, $tkey\n");
193 if($code == $stest) {
206 // this function allows a user to resync their key. If too
207 // many codes are called, we only check up to 20 codes in the future
208 // so if the user is at 21, they'll always fail.
209 function resyncCode($username, $code1, $code2) {
210 // 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
211 // for HOTP tokens we start at x and go to x+20
213 // for TOTP we go +/-1min TODO = remember that +/- 1min should
214 // be changed based on stepping if we change the expiration time
217 // $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)');
218 $tokendata = $this->internalGetData($username);
220 // TODO: check return value
221 $ttype = $tokendata["tokentype"];
222 $tlid = $tokendata["tokencounter"];
223 $tkey = $tokendata["tokenkey"];
226 $this->errorText = "No Assigned Token";
233 $en = $this->hotpHuntValue;
234 for($i=$st; $i<$en; $i++) {
235 $stest = $this->oath_hotp($tkey, $i);
236 //echo "code: $code, $stest, $tkey\n";
237 if($code1 == $stest) {
238 $stest2 = $this->oath_hotp($tkey, $i+1);
239 if($code2 == $stest2) {
240 $tokendata["tokencounter"] = $i+1;
241 $this->internalPutData($username, $tokendata);
252 echo "how the frig did i end up here?";
258 // gets the error text associated with the last error
259 function getErrorText() {
260 return $this->errorText;
263 // create a url compatibile with google authenticator.
264 function createURL($user) {
265 // oddity in the google authenticator... hotp needs to be lowercase.
266 $data = $this->internalGetData($user);
267 $toktype = $data["tokentype"];
268 $key = $this->helperhex2b32($data["tokenkey"]);
270 // token counter should be one more then current token value, otherwise
272 $counter = $data["tokencounter"]+1;
273 $toktype = strtolower($toktype);
274 if($toktype == "hotp") {
275 $url = "otpauth://$toktype/$user?secret=$key&counter=$counter";
277 $url = "otpauth://$toktype/$user?secret=$key";
279 //echo "url: $url\n";
283 // creeates a base 32 key (random)
284 function createBase32Key() {
285 $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
287 for($i=0; $i<16; $i++) {
288 $offset = rand(0,strlen($alphabet)-1);
289 //echo "$i off is $offset\n";
290 $key .= $alphabet[$offset];
297 function getKey($username) {
298 $data = $this->internalGetData($username);
299 $key = $data["tokenkey"];
305 function getTokenType($username) {
306 $data = $this->internalGetData($username);
307 $toktype = $data["tokentype"];
313 // TODO: lots of error checking goes in here
314 function helperb322hex($b32) {
315 $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
320 for($i = 0; $i < strlen($b32); $i++) {
321 $in = strrpos($alphabet, $b32[$i]);
322 $b = str_pad(base_convert($in, 10, 2), 5, "0", STR_PAD_LEFT);
327 $ar = str_split($out,20);
329 //echo "$dous, $b\n";
333 foreach($ar as $val) {
334 $rv = str_pad(base_convert($val, 2, 16), 5, "0", STR_PAD_LEFT);
335 //echo "rv: $rv from $val\n";
344 // TODO: lots of error checking goes in here
345 function helperhex2b32($hex) {
346 $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
348 $ar = str_split($hex, 5);
351 foreach($ar as $var) {
352 $bc = base_convert($var, 16, 2);
353 $bin = str_pad($bc, 20, "0", STR_PAD_LEFT);
355 //echo "$bc was, $var is, $bin are\n";
359 $ar2 = str_split($out, 5);
360 foreach($ar2 as $var2) {
361 $bc = base_convert($var2, 2, 10);
362 $out2 .= $alphabet[$bc];
368 // i've put alot of faith in the code from the
369 // php site's examples for the hash_hmac algorithm
370 // i assume its mostly correct but i should do
371 // some testing to verify this is actually the case
372 function oath_hotp($key, $counter)
374 $key = pack("H*", $key);
375 $cur_counter = array(0,0,0,0,0,0,0,0);
378 $cur_counter[$i] = pack ('C*', $counter);
379 $counter = $counter >> 8;
381 $bin_counter = implode($cur_counter);
383 if (strlen ($bin_counter) < 8)
385 $bin_counter = str_repeat (chr(0), 8 - strlen ($bin_counter)) . $bin_counter;
389 $hash = hash_hmac ('sha1', $bin_counter, $key);
390 return str_pad($this->oath_truncate($hash), 6, "0", STR_PAD_LEFT);
394 function oath_truncate($hash, $length = 6)
397 foreach(str_split($hash,2) as $hex)
399 $hmac_result[]=hexdec($hex);
403 $offset = $hmac_result[19] & 0xf;
405 // Algorithm from RFC
408 (($hmac_result[$offset+0] & 0x7f) << 24 ) |
409 (($hmac_result[$offset+1] & 0xff) << 16 ) |
410 (($hmac_result[$offset+2] & 0xff) << 8 ) |
411 ($hmac_result[$offset+3] & 0xff)
416 // some private data bits.
417 private $getDatafunction;
418 private $putDatafunction;
425 private $hotpHuntValue;
432 * 3: input code was invalid (user input an invalid code - must be 6 numerical digits)
433 * 4: user doesnt exist?