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
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
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
27 * The way we should really be doing things is to have an array that encapsulates "normal" data (or a class?)
28 * and then just manipulate it, then use a checkin function to push the data base into the db...
30 class GoogleAuthenticator {
32 // first we init google authenticator by passing it a filename
33 // for its sqlite database.
34 // $getDataFunction expects 1 argument which defines what data it wants
35 // and can be "userlist" or "usertoken:username"
36 // $putDataFunciton expects 2 arguments, $1 is data type, $2 is the data
37 // $1 can be "changetoken:username", "removetoken:username", $2 is the token
38 // data in some encoded form
39 // tokenDATA will be like HOTP;KEY;CID where CID is the current counter value
40 // why encode like this? i cant think of a good reason tbh, i should probably just
41 // use php's arry encoder functions
42 function __construct($getDataFunction, $putDataFunction) {
43 $this->putDataFunction = $putDataFunction;
44 $this->getDataFunction = $getDataFunction;
47 abstract function getData($username);
48 abstract function putData($username, $data);
49 abstract function getUsers();
51 // a function to create an empty data structure
52 function createEmptyData() {
53 $data["tokenkey"] = ""; // the token key
54 $data["tokentype"] = ""; // the token type
55 $data["tokentimer"] = ""; // the token timer (For totp) and not supported by ga yet
56 $data["tokencounter"] = ""; // the token counter for hotp
57 $data["tokenalgorithm"] = ""; // the token algorithm (not supported by ga yet)
62 // an internal funciton to get
63 function internalGetData($username) {
64 $data = getData($username);
65 $deco = unserialize(base64_decode($data));
68 $deco = createEmptyData();
75 function internalPutData($username, $data) {
76 $enco = base64_encode(serialize($data));
78 return putData($username, $enco);
82 // set the token type the user it going to use.
83 // this defaults to HOTP - we only do 30s token
84 // so lets not be able to set that yet
85 function setupTokenType($username, $tokentype) {
86 if($tokentype!="HOTP" and $tokentype!="TOTP") {
87 $errorText = "Invalid Token Type";
91 $data = getData($username);
92 $data["tokentype"] = $tokentype;
93 $func = $this->putDataFunction;
94 $func("settokentype", $put);
100 // create "user" with insert
101 function setUser($username, $key = "", $ttype="HOTP") {
102 if($key == "") $key = $this->createBase32Key();
103 $hkey = $this->helperb322hex($key);
105 $token["username"] = $username;
106 $token["tokenkey"] = $hkey;
107 $token["tokentype"] = $ttype;
109 $func = $this->putDataFunction;
110 $func("setusertoken", $token);
116 // sets the key for a user - this is assuming you dont want
117 // to use one created by the application. returns false
118 // if the key is invalid or the user doesn't exist.
119 function setUserKey($username, $key) {
120 // consider scrapping this
125 function userExists($username) {
126 // need to think about this
131 function deleteUser($username) {
132 $func = $this->putDataFunction;
133 $func("deleteusertoken", $username);
136 // user has input their user name and some code, authenticate
138 function authenticateUser($username, $code) {
140 $func = $this->getDataFunction;
141 $tokendata = $func("gettoken", $username);
143 // TODO: check return value
144 $ttype = $tokendata["tokentype"];
145 $tlid = $tokendata["tokencounter"];
146 $tkey = $tokendata["tokenkey"];
151 for($i=$st; $i<$en; $i++) {
152 $stest = $this->oath_hotp($tkey, $i);
153 //error_log("code: $code, $stest, $tkey, $tid");
154 if($code == $stest) {
155 $tokenset["username"] = $username;
156 $tokenset["tokencounter"] = $i;
158 $func = $this->putDataFunction;
159 $func("settokencounter", $tokenset);
167 $t_ear = $t_now - 45;
168 $t_lat = $t_now + 60;
169 $t_st = ((int)($t_ear/30));
170 $t_en = ((int)($t_lat/30));
171 //error_log("kmac: $t_now, $t_ear, $t_lat, $t_st, $t_en");
172 for($i=$t_st; $i<=$t_en; $i++) {
173 $stest = $this->oath_hotp($tkey, $i);
174 //error_log("code: $code, $stest, $tkey\n");
175 if($code == $stest) {
181 echo "how the frig did i end up here?";
188 // this function allows a user to resync their key. If too
189 // many codes are called, we only check up to 20 codes in the future
190 // so if the user is at 21, they'll always fail.
191 function resyncCode($username, $code1, $code2) {
192 // 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
193 // for HOTP tokens we start at x and go to x+20
195 // for TOTP we go +/-1min TODO = remember that +/- 1min should
196 // be changed based on stepping if we change the expiration time
199 // $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)');
201 $func = $this->getDataFunction;
202 $tokendata = $func("gettoken", $username);
204 // TODO: check return value
205 $ttype = $tokendata["tokentype"];
206 $tlid = $tokendata["tokencounter"];
207 $tkey = $tokendata["tokenkey"];
213 for($i=$st; $i<$en; $i++) {
214 $stest = $this->oath_hotp($tkey, $i);
215 //echo "code: $code, $stest, $tkey\n";
216 if($code1 == $stest) {
217 $stest2 = $this->oath_hotp($tkey, $i+1);
218 if($code2 == $stest2) {
219 $tokenset["username"] = $username;
220 $tokenset["tokencounter"] = $i+1;
222 $func = $this->putDataFunction;
223 $func("settokencounter", $tokenset);
233 echo "how the frig did i end up here?";
240 // gets the error text associated with the last error
241 function getErrorText() {
242 return $this->errorText;
245 // create a url compatibile with google authenticator.
246 function createURL($user, $key,$toktype = "HOTP") {
247 // oddity in the google authenticator... hotp needs to be lowercase.
248 $toktype = strtolower($toktype);
249 if($toktype == "hotp") {
250 $url = "otpauth://$toktype/$user?secret=$key&counter=1";
252 $url = "otpauth://$toktype/$user?secret=$key";
254 //echo "url: $url\n";
258 // creeates a base 32 key (random)
259 function createBase32Key() {
260 $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
262 for($i=0; $i<16; $i++) {
263 $offset = rand(0,strlen($alphabet)-1);
264 //echo "$i off is $offset\n";
265 $key .= $alphabet[$offset];
272 function helperb322hex($b32) {
273 $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
278 for($i = 0; $i < strlen($b32); $i++) {
279 $in = strrpos($alphabet, $b32[$i]);
280 $b = str_pad(base_convert($in, 10, 2), 5, "0", STR_PAD_LEFT);
285 $ar = str_split($out,20);
287 //echo "$dous, $b\n";
291 foreach($ar as $val) {
292 $rv = str_pad(base_convert($val, 2, 16), 5, "0", STR_PAD_LEFT);
293 //echo "rv: $rv from $val\n";
302 function helperhex2b32($hex) {
303 $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
305 $ar = str_split($hex, 5);
308 foreach($ar as $var) {
309 $bc = base_convert($var, 16, 2);
310 $bin = str_pad($bc, 20, "0", STR_PAD_LEFT);
312 //echo "$bc was, $var is, $bin are\n";
316 $ar2 = str_split($out, 5);
317 foreach($ar2 as $var2) {
318 $bc = base_convert($var2, 2, 10);
319 $out2 .= $alphabet[$bc];
325 function oath_hotp($key, $counter)
327 $key = pack("H*", $key);
328 $cur_counter = array(0,0,0,0,0,0,0,0);
331 $cur_counter[$i] = pack ('C*', $counter);
332 $counter = $counter >> 8;
334 $bin_counter = implode($cur_counter);
336 if (strlen ($bin_counter) < 8)
338 $bin_counter = str_repeat (chr(0), 8 - strlen ($bin_counter)) . $bin_counter;
342 $hash = hash_hmac ('sha1', $bin_counter, $key);
343 return str_pad($this->oath_truncate($hash), 6, "0", STR_PAD_LEFT);
346 function oath_truncate($hash, $length = 6)
349 foreach(str_split($hash,2) as $hex)
351 $hmac_result[]=hexdec($hex);
355 $offset = $hmac_result[19] & 0xf;
357 // Algorithm from RFC
360 (($hmac_result[$offset+0] & 0x7f) << 24 ) |
361 (($hmac_result[$offset+1] & 0xff) << 16 ) |
362 (($hmac_result[$offset+2] & 0xff) << 8 ) |
363 ($hmac_result[$offset+3] & 0xff)
368 // some private data bits.
369 private $getDatafunction;
370 private $putDatafunction;