-
Notifications
You must be signed in to change notification settings - Fork 3
/
login_functions.php
3335 lines (3115 loc) · 142 KB
/
login_functions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
use Base32\Base32;
require_once dirname(__FILE__).'/../core/core.php';
class UserFunctions extends DBHelper
{
public function __construct($username = null, $lookup_column = null, $db_params = null)
{
/***
* @param string $username -> the user to be instanced with
* @param string $lookup_column -> the column to look them up in.
* Ignored if $username is null, defaults to $user_column
* @param array $db_params -> Optional override database parameters.
* The required keys are:
* (string)"user" for SQL username,
* (string)"database" as the SQL database,
* and (string)"password" for SQL password,
* with optional keys
* (string)"url" (defaults to "localhost")
* and (array)"cols" of type "column_name"=>"type".
***/
global $user_data_storage,$profile_picture_storage,$site_security_token,$service_email,$minimum_password_length,$password_threshold_length,$db_cols,$default_user_table,$default_user_database,$password_column,$cookie_ver_column,$user_column,$totp_column,$totp_steps,$temporary_storage,$needs_manual_authentication,$totp_rescue,$ip_record,$default_user_database,$default_sql_user,$default_sql_password,$sql_url,$default_user_table,$baseurl,$twilio_sid,$twilio_token,$twilio_number,$site_name,$link_column,$app_column, $allowedEmailDomains, $allowedEmailTLDs;
# Set up the parameters in CONFIG.php
$config_path = dirname(__FILE__).'/../CONFIG.php';
require_once $config_path;
if (!empty($db_params)) {
if (!is_array($db_params)) {
throw(new Exception("Invalid argument type for \$db_params"));
}
if (sizeof($db_params) != 4 || sizeof($db_params) != 3) {
throw(new Exception('Bad database initialization parameters.'));
}
$must_have = array('user','database','password');
if (array_key_exists('url', $db_params)) {
$sql_url = $db_params['url'];
}
if (array_key_exists('cols', $db_params)) {
$db_cols = $db_params['cols'];
}
foreach ($must_have as $key) {
if (!array_key_exists($key, $db_params)) {
throw(new Exception('Bad database initialization parameters.'));
}
switch ($key) {
case 'user':
$default_sql_user = $db_params[$key];
break;
case 'database':
$default_user_database = $db_params[$key];
break;
case 'password':
$default_sql_password = $db_params[$key];
break;
default:
throw(new Exception("Unknown key '$key' in database initialization parameters."));
}
}
}
try {
# Configure the database
$this->setSQLUser($default_sql_user);
$this->setDB($default_user_database);
$this->setSQLPW($default_sql_password);
$this->setSQLURL($sql_url);
$this->setCols($db_cols);
$this->setTable($default_user_table);
} catch (Exception $e) {
# More complete message
$message = 'Could not initialize database setup ['.$e->getMessage().'] in <'.$e->getTraceAsString().'> (using '.$config_path.')';
throw(new Exception($message));
}
# Check it
$details = $this->testSettings(null, true);
if (!$details['status'] && $details != true) {
# There's a database problem
throw(new Exception('Database configuration problem - '.json_encode($details)));
}
if (!empty($user_data_storage)) {
$user_data_storage .= substr($user_data_storage, -1) == '/' ? '' : '/';
$this->data_path = $user_data_storage;
} else {
$this->data_path = 'userdata/';
}
if (!empty($profile_picture_storage)) {
$profile_picture_storage .= substr($profile_picture_storage, -1) == '/' ? '' : '/';
$this->picture_path = $profile_picture_storage;
} else {
$this->picture_path = $this->data_path.'profilepics/';
}
$this->siteKey = $site_security_token;
$this->supportEmail = $service_email;
$this->minPasswordLength = $minimum_password_length;
$this->thresholdLength = $password_threshold_length;
$this->pwColumn = $password_column;
$this->pwcol = $password_column;
$this->cookieColumn = $cookie_ver_column;
$this->userColumn = $user_column;
$this->usercol = $user_column;
$this->linkColumn = $link_column;
$this->tmpColumn = $temporary_storage;
$this->totpColumn = $totp_column;
$this->totpBackup = $totp_rescue;
$this->totpSteps = $totp_steps;
$this->needsAuth = $needs_manual_authentication;
$this->ipColumn = $ip_record;
$this->twilio_sid = $twilio_sid;
$this->twilio_token = $twilio_token;
$this->twilio_number = $twilio_number;
$this->site = $site_name;
$this->appKeyColumn = $app_column;
$this->userlink = null;
$this->allowedTLDs = $allowedEmailTLDs;
$this->allowedDomains = $allowedEmailDomains;
$proto = 'http';
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
$proto .= 's';
}
if (empty($baseurl)) {
$baseurl = $proto.'://';
$baseurl .= $_SERVER['HTTP_HOST'];
}
# Get the domain and tld
$base_long = str_replace('http://', '', strtolower($baseurl));
$base_long = str_replace('https://', '', strtolower($base_long));
$base_arr = explode('/', $base_long);
$base = $base_arr[0];
$url_parts = explode('.', $base);
$tld = array_pop($url_parts);
if ($url_parts[0] == 'www') {
array_shift($url_parts);
}
$domain = implode('.', $url_parts);
$shorturl = $domain.'.'.$tld;
$this->domain = $domain;
$this->shortUrl = $shorturl;
$this->qualDomain = $proto.'://'.$shorturl.'/';
# Let's be nice and try to set up a user
try {
if (!empty($username)) {
# We're initiating a specified user
$key = empty($lookup_column) ? $this->userColumn : $lookup_column;
$this->getUser(array($key => $username));
} else {
$this->getUser();
}
} catch (Exception $e) {
# If we tried on our own, let's do nothing; if it was user specified, re-throw it
if (!empty($username)) {
$key = empty($lookup_column) ? $this->userColumn : $lookup_column;
$us = array($key => $username);
throw(new Exception("Problem setting '$username' as ".print_r($us, true).': '.$e->getMessage()));
}
}
}
/***
* Helper functions
***/
private function getSiteKey()
{
return $this->siteKey;
}
public function getSiteName()
{
return $this->site;
}
public function getDomain()
{
return $this->domain;
}
public function getQualifiedDomain()
{
return $this->qualDomain;
}
public function getShortUrl()
{
return $this->shortUrl;
}
private function getMinPasswordLength()
{
if (!is_numeric($this->minPasswordLength)) {
$this->minPasswordLength = 8;
}
$length = intval($this->minPasswordLength);
return $length;
}
private function getThresholdLength()
{
return $this->thresholdLength;
}
private function getSupportEmail()
{
return $this->supportEmail;
}
public function needsManualAuth()
{
return $this->needsAuth === true;
}
private function getMailObject()
{
require_once dirname(__FILE__).'/../PHPMailer/PHPMailerAutoload.php';
require_once dirname(__FILE__).'/../CONFIG.php';
global $is_smtp,$mail_host,$mail_user,$mail_password,$is_pop3;
$mail = new PHPMailer();
if ($is_smtp) {
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->Host = $mail_host;
$mail->Username = $mail_user;
$mail->Password = $mail_password;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
}
if ($is_pop3) {
$mail->isPOP3();
} # Need to expand this
$mail->From = 'blackhole@'.$this->getShortUrl();
$mail->FromName = $this->getDomain().' Mailer Bot';
$mail->isHTML(true);
return $mail;
}
private function getSecret($is_test = false)
{
$userdata = $this->getUser();
if ($is_test) {
return empty($userdata[$this->tmpColumn]) ? false : $userdata[$this->tmpColumn];
}
return empty($userdata[$this->totpColumn]) ? false : $userdata[$this->totpColumn];
}
private function setTempSecret($secret = '')
{
$userdata = $this->getUser();
$l = $this->openDB();
$query = 'UPDATE `'.$this->getTable().'` SET `'.$this->tmpColumn."`='$secret' WHERE `".$this->userColumn."`='".$this->getUsername()."'";
$r = mysqli_query($l, $query);
if ($r === false) {
return array('status' => false,'error' => mysqli_error($l));
}
return array('status' => true);
}
public function has2FA()
{
$userdata = $this->getUser();
return !empty($userdata[$this->totpColumn]);
}
public function getUser($user_id = null)
{
/***
* Get the user, and assign one if it hasn't been assigned already
*
* @param string|array $user_id Either a column/value pair or an ID for the default column
* @return array of the user result column
***/
if (empty($this->user) || !empty($user_id)) {
$this->setUser($user_id);
} elseif (empty($this->user)) {
# Try a cookie
$cookielink = $this->domain.'_link';
$altcookielink = str_replace('.', '_', $this->domain).'_link';
$ucookielink = empty($_COOKIE[$cookielink]) ? $altcookielink : $cookielink;
$this->setUser($ucookielink);
}
$userdata = $this->user;
$userdata['img'] = $this->getUserPicture();
if (!array($userdata)) {
if (empty($userdata)) {
# Couldn't get the user in any automated way
$error = 'Unable to retrieve user';
} else {
# The user was bad
$error = 'Bad user provided - ';
if (is_string($userdata)) {
$error .= $userdata;
} elseif (is_array($userdata)) {
$error .= current($userdata).' of type '.key($userdata);
} else {
$error .= 'unrecognized type';
}
}
throw(new Exception($error));
}
if (@array_key_exists($this->userColumn, $userdata)) {
$this->username = $userdata[$this->userColumn];
}
if (@array_key_exists($this->linkColumn, $userdata)) {
$this->userlink = $userdata[$this->linkColumn];
}
return $userdata;
}
private function setUser($user_id = null)
{
/***
* Set the user for this object. Always overwrites current user.
* Only intended to be called by getUser()
*
* @param string|array $user_id Either a column/value pair or an ID for the default column
***/
$ouid = $user_id;
$cookielink = $this->domain.'_link';
$altcookielink = str_replace('.', '_', $this->domain).'_link';
$ucookielink = empty($_COOKIE[$cookielink]) ? $altcookielink : $cookielink;
if (!empty($user_id) && is_array($user_id) && sizeof($user_id) == 1) {
# Specified as a column/value pair
$col = key($user_id);
$user_id = current($user_id);
} elseif (!empty($user_id) && !is_array($user_id)) {
# Just a id with the default column
$col = $this->userColumn;
} elseif (!empty($_COOKIE[$ucookielink])) {
# See if we can get this from the cookies
$user_id = $_COOKIE[$ucookielink];
$col = $this->linkColumn;
}
# Do we have an ID to work with?
if (empty($user_id) || empty($col)) {
# We couldn't get it from direct assignment or cookies
throw(new Exception("Unable to set user for '".$col."' => '".$user_id."', and unable to read cookies. {".print_r($ouid, true).'}'));
}
# Inputs are sanitized in lookupItem
$result = $this->lookupItem($user_id, $col);
if ($result !== false && !is_array($result)) {
$userdata = mysqli_fetch_assoc($result);
if (is_array($userdata)) {
$this->user = $userdata;
}
}
if (!is_array($this->user)) {
# Bad query - let getUser() handle it
$this->user = null;
}
}
public function getUsername()
{
return $this->username;
}
public function getHardlink()
{
$link = $this->userlink;
# Has this been defined yet?
// if (empty($link)) {
// try {
// $this->getUser();
// $link = $this->userlink;
// } catch(Exception $e) {
// $link = null;
// }
// }
return $link;
}
protected function getNameTag($tag = "name")
{
$userdata = $this->getUser();
if (!is_array($userdata)) {
return false;
}
$nameXml = $userdata["name"];
$xml = new Xml();
$xml->setXml($nameXml);
return $xml->getTagContents($tag);
}
public function getName()
{
return $this->getNameTag("name");
}
public function getFirstName()
{
return $this->getNameTag("fname");
}
public function getLastName()
{
return $this->getNameTag("lname");
}
public function getProfile()
{
/***
* Returns the public_profile of the userdata
***/
# Are profiles configured?
if (!$this->columnExists("public_profile")) {
return false;
}
$userdata = $this->getUser();
$profile = $userdata["public_profile"];
$jProfile = json_decode($profile, true);
return is_array($jProfile) ? $jProfile : false;
}
private function getUserWhere()
{
return " WHERE `".$this->linkColumn."`='".$this->getHardlink()."'";
}
public static function isValidEmail($email, $maxLength = 100)
{
$preg = "/[a-z0-9!#$%&'*+=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[a-z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)\b/";
return preg_match($preg, $email) == 1 && strlen($email) <= $maxLength;
}
public function getPhone()
{
$userdata = $this->getUser();
return self::cleanPhone($userdata['phone']);
}
public function hasPhone()
{
$userdata = $this->getUser();
return self::isValidPhone($userdata['phone']);
}
private function getDigest()
{
$allowed_digest = array(
'md5',
'sha1',
'sha256',
'sha512',
);
if (!in_array($this->totpdigest, $allowed_digest)) {
return 'sha1';
}
return $this->totpdigest;
}
public function setTwilioSID($sid)
{
$this->twilio_sid = $sid;
}
public function getTwilioSID()
{
return $this->twilio_sid;
}
public function setTwilioToken($token)
{
$this->$twilio_token = $token;
}
public function getTwilioToken()
{
return $this->twilio_token;
}
public function setTwilioNumber($number)
{
# Validate it
if (!self::isValidPhone($number)) {
throw(new Exception('Invalid phone number'));
}
}
public function getTwilioNumber()
{
return $this->twilio_number;
}
public function canSMS($strict = true, $throw = true)
{
/***
* Return if the user can get an SMS
* @param bool $strict if true, throw an exception for bad setup,
* and false if unverified; otherwise, false for
* bad setup, and true if the number is OK (regardless of verification)
* @return bool
***/
$twilioSID = $this->getTwilioSID();
$twilioToken = $this->getTwilioToken();
$twilio_status = !empty($twilioSID) && !empty($twilioToken);
if (!$twilio_status && $strict === true) {
if ($throw) {
throw(new Exception("Twilio has not been configured. Be sure that \$twilio_sid, \$twilio_token, and \$twilio_number are specified in config.php, or call setTwilioSID(), setTwilioToken(), and setTwilioNumber() first."));
}
return false;
} elseif (!$twilio_status) {
return false;
}
$userdata = $this->getUser();
if ($strict) {
if (!self::isValidPhone($this->getPhone())) {
if ($throw) {
throw(new Exception('Illegal phone number.'));
}
return false;
}
}
# If we're strict, the user only can SMS when the phone number is verified.
# Otherwise, we just return the status of the phone number itself.
$verified = $strict ? $userdata['phone_verified'] == true : self::isValidPhone($this->getPhone());
return $verified;
}
private static function cleanPhone($number)
{
/***
* @param string $number
* @return int $number
***/
# Common things that may show up in a phone number
$number = preg_replace('/[^0-9]/', '', $number);
# Remove the country code for the US
if (substr($number, 0, 1) == '1') {
$number = substr($number, 1);
}
return $number;
}
private static function isValidPhone($number)
{
$number = self::cleanPhone($number);
return strlen($number) == 10;
}
public static function microtime_float()
{
list($usec, $sec) = explode(' ', microtime());
return ((float) $usec + (float) $sec);
}
public static function strbool($bool)
{
// returns the string of a boolean as 'true' or 'false'.
if (is_string($bool)) {
$bool = boolstr($bool);
} // if a string is passed, convert it to a bool
if (is_bool($bool)) {
return $bool ? 'true' : 'false';
} else {
return 'non_bool';
}
}
public static function doLoadOTP()
{
require_once dirname(__FILE__).'/../base32/src/Base32/Base32.php';
require_once dirname(__FILE__).'/../totp/lib/OTPHP/OTPInterface.php';
require_once dirname(__FILE__).'/../totp/lib/OTPHP/OTP.php';
require_once dirname(__FILE__).'/../totp/lib/OTPHP/TOTPInterface.php';
require_once dirname(__FILE__).'/../totp/lib/OTPHP/TOTP.php';
}
public function checkTOTP($provided)
{
/***
* Check the TOTP code provided by the user.
* In all but exceptional circumstances, this should be the
* function used.
*
* @param int $provided Provided TOTP passcode
* @return bool
***/
return $this->verifyTOTP($provided);
}
private function verifyTOTP($provided, $is_test = false)
{
/***
* Check the TOTP code provided by the user
*
* @param int $provided Provided OTP passcode
* @param bool $is_test if it's a test run, check the temporary rather than real column.
* @return bool
***/
self::doLoadOTP();
$secret = $this->getSecret($is_test);
if ($secret === false) {
return false;
}
try {
$totp = new OTPHP\TOTP($secret);
$totp->setDigest($this->getDigest());
if ($totp->verify($provided)) {
return true;
}
if (!is_numeric($this->totpSteps)) {
throw(new Exception('Bad TOTP step count'));
}
$i = 1;
while ($i <= $this->totpSteps) {
$test = array();
$test[] = $totp->now();
$test[] = $totp->at(time() + 30 * $i);
$test[] = $totp->at(time() - 30 * $i);
++$i;
# Check on every iteration. It'll usually be faster.
if (in_array($provided, $test)) {
return true;
}
}
return false;
} catch (Exception $e) {
throw(new Exception('Bad parameters provided to verifyOTP :: '.$e->getMessage()));
}
}
public function makeTOTP($provider = null)
{
/***
* Assign a user a multifactor authentication code
*
* @param string $provider The provider giving 2FA.
* @return array with the status in the key "status", errors in "error" and "human_error",
* username in "username", and provisioning data in "uri"
***/
if (empty($this->username)) {
$this->getUser();
# We MUST have this properly assigned
if (empty($this->username)) {
return array('status' => false,'error' => 'Unable to get user.');
}
}
if ($this->getSecret() !== false) {
return array('status' => false,'error' => '2FA has already been enabled for this user.','human_error' => "You've already enabled 2-factor authentication.",'username' => $this->username);
}
try {
if (!class_exists('Stronghash')) {
require_once dirname(__FILE__).'/../core/stronghash/php-stronghash.php';
}
$salt = Stronghash::createSalt();
require_once dirname(__FILE__).'/../base32/src/Base32/Base32.php';
$secret = Base32::encode($salt);
## The resulting provisioning URI should now be sent to the user
## Flag should be set server-side indicating the change id pending
$l = $this->openDB();
$query = 'UPDATE `'.$this->getTable().'` SET `'.$this->tmpColumn."`='$secret' WHERE `".$this->userColumn."`='".$this->username."'";
$r = mysqli_query($l, $query);
if ($r === false) {
return array('status' => false,'human_error' => 'Database error','error' => mysqli_error($l));
}
# The data was saved correctly
# Let's create the provisioning stuff!
self::doLoadOTP();
$totp = new OTPHP\TOTP($secret);
$totp->setDigest($this->getDigest());
$totp->setLabel($this->username);
$totp->setIssuer($provider);
$uri = $totp->getProvisioningURI($label, $provider);
# iPhones don't actually accept the full, valid URI
$unsafe_uri = urldecode($uri);
$uri_args = explode('?', $unsafe_uri);
$iphone_uri = $uri_args[0].'?';
$iphone_args = array();
$iphone_safe_args = array('secret','issuer');
foreach (explode('&', $uri_args[1]) as $paramval) {
$pv = explode('=', $paramval);
$param = $pv[0];
$val = $pv[1];
if (in_array($param, $iphone_safe_args)) {
$iphone_args[] = $param.'='.$val;
}
}
$iphone_uri .= implode('&', $iphone_args);
/* $iphone32 = str_replace("=","",$secret_part[1]); */
/* $iphone_uri = $secret_part[0]."secret=".$iphone32; #still no good */
$retarr = self::generateQR($iphone_uri);
# Let's get a human-readable secret
$human_secret0 = str_replace('=', '', $secret);
$i = 0;
$human_secret = '';
foreach (str_split($human_secret0) as $char) {
$human_secret .= $char;
++$i;
if ($i == 4) {
$human_secret .= ' ';
$i = 0;
}
}
$retarr['secret'] = $secret;
$retarr['human_secret'] = $human_secret;
$retarr['username'] = $this->username;
return $retarr;
} catch (Exception $e) {
return array('status' => false,'human_error' => 'Unexpected error in makeTOTP','error' => $e->getMessage(),'username' => $this->username,'provider' => $provider,'label' => $totp->getLabel(),'uri' => $uri,'secret' => $secret);
}
}
public function saveTOTP($code)
{
/***
* Read the tentative secret and make it real
*
* @params int $code Provided TOTP code at prompt
* @return array
***/
if ($this->verifyTOTP($code, true)) {
# If it's good, make the secret "real" in the $this->totpColumn
$userdata = $this->getUser();
$secret = $userdata[$this->tmpColumn];
$query = 'UPDATE `'.$this->getTable().'` SET `'.$this->totpColumn."`='$secret', `".$this->tmpColumn."`='' WHERE `".$this->userColumn."`='".$this->username."'";
if (!class_exists('Stronghash')) {
require_once dirname(__FILE__).'/../core/stronghash/php-stronghash.php';
}
$backup = Stronghash::createSalt();
$backup_store = hash('sha512', $backup);
$query2 = 'UPDATE `'.$this->getTable().'` SET `'.$this->totpBackup."`='$backup_store' WHERE `".$this->userColumn."`='".$this->username."'";
$l = $this->openDB();
mysqli_query($l, 'BEGIN');
$r = mysqli_query($l, $query);
if ($r === false) {
$e = mysqli_error($l);
mysqli_query($l, 'ROLLBACK');
return array('status' => false,'error' => $e,'human_error' => 'Could not save secret','username' => $this->username);
}
$r = mysqli_query($l, $query2);
if ($r === false) {
$e = mysqli_error($l);
mysqli_query($l, 'ROLLBACK');
return array('status' => false,'error' => $e,'human_error' => 'Could not create backup code','username' => $this->username);
}
mysqli_query($l, 'COMMIT');
# Let the user know
return array('status' => true,'username' => $this->username,'backup' => $backup);
} else {
# The code is wrong, feed back to the user
return array('status' => false,'error' => '0','human_error' => 'Invalid code.');
}
}
public function removeTOTP($username, $password, $code)
{
/***
* Remove two factor authentication
*
* @param string $username
* @param string $password
* @param string $code Either the Authenticator code, or previously generated backup code.
* @return bool|array true if success, array if failure
***/
$l = $this->openDB();
$verify = $this->lookupUser($username, $password);
# Verify will always be false; but let's see if "error" is also false.
if ($verify['totp'] !== true) {
# Either the user doesn't have it, or the credentials are bad
if ($verify[0] === true) {
# Credentials are fine
return array('status' => false,'error' => 'Invalid operation','human_error' => "You don't have two-factor authentication turned on");
} else {
return array('status' => false,'error' => 'Bad credentials','result' => $verify,'human_error' => 'Sorry, bad username or password.');
}
}
$this->getUser();
# Check code for length, if it's long it's the backup
if (strlen($code) > 6) {
# Check against $this->totpBackup
$query = 'SELECT `'.$this->totpBackup.'` FROM `'.$this->getTable().'` WHERE `'.$this->userColumn."`='".$this->username."'";
$r = mysqli_query($l, $query);
if ($r === false) {
return array('status' => false,'error' => mysqli_error($l),'human_error' => 'Database error');
}
$row = mysqli_fetch_row($r);
$hash = hash('sha512', $code);
if ($hash !== $row[0]) {
return array('status' => false,'error' => 'Bad backup code','human_error' => 'The backup code you entered was invalid. Please try again.');
}
} else {
# Verify the code
if (!$this->verifyTOTP($code)) {
return array('status' => false,'error' => 'Bad TOTP code','human_error' => 'The code you entered was invalid. Please try again.');
}
}
# Unset backup and totpcol
$query = 'UPDATE `'.$this->getTable().'` SET `'.$this->totpColumn."`='', `".$this->tmpColumn."`='', `".$this->totpBackup."`='' WHERE `".$this->userColumn."`='".$this->getUsername()."'";
mysqli_query($l, 'BEGIN');
$r = mysqli_query($l, $query);
if ($r === false) {
$e = mysqli_error($l);
mysqli_query($l, 'ROLLBACK');
return array('status' => false,'error' => $e,'human_error' => 'Could not unset two-factor authentication','username' => $this->getUsername());
}
$r = mysqli_query($l, 'COMMIT');
if ($r === false) {
return array('status' => false,'error' => mysqli_error($l),'human_error' => 'Server error verifying removal. Please try again.');
}
return array('status' => true,'query' => $query,'username' => $this->getUsername());
}
public function sendTOTPText()
{
/***
* Send a text message to the destination number with the TOTP code
***/
# Get the current TOTP value for the user
# Send the text through Twilio
# Return the status and updated message
if ($this->has2FA()) {
try {
self::doLoadOTP();
$totp = new OTPHP\TOTP($this->getSecret());
$totp->setDigest($this->getDigest());
$message = 'Your authentication code for '.$this->getSiteName().' is: '.$totp->now().' . It is valid for 30 seconds.';
$this->textUser($message);
return true;
} catch (Exception $e) {
return false;
}
} else {
throw(new Exception('User does not have TOTP enabled to send a text!'));
}
}
public static function generateQR($uri, $data_path = null, $identifier_path = null)
{
/***
* Generate a QR code from a string
*
* @param string $uri
* @param string $data_path The path to the write directory
* @param string $identifier_path An optional subdirectory for paths; makes loops easier
* @returns array with the main results in "svg" and "raw" keys, with a Google fallback in the "url" key
***/
try {
require_once dirname(__FILE__).'/../qr/qrlib.php';
if (!class_exists('Stronghash')) {
require_once dirname(__FILE__).'/../core/stronghash/php-stronghash.php';
}
$salt = Stronghash::createSalt();
$persistent = !empty($data_path);
if (!$persistent) {
$tmp_dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
if (!file_exists($tmp_dir)) {
if (!mkdir($tmp_dir)) {
# Could not write to temporary path
throw(new Exception("Could not write to '$tmp_dir'"));
}
}
$web_dir = 'temp/';
$filename = $tmp_dir.sha1($salt).'.png';
} else {
# Persistent file
$file = $sha1($salt.$uri);
if (substr($data_path, -1) != '/') {
$data_path .= DIRECTORY_SEPARATOR;
}
$full_path = empty($identifier_path) ? $data_path : $data_path.$identifier_path.DIRECTORY_SEPARATOR;
if (!file_exists($full_path)) {
if (!mkdir($full_path)) {
# Could not write to the storage path
throw(new Exception("Could not write to '$full_path'"));
}
}
$filename = $full_path.$file.'.png';
}
$svg = QRcode::svg($uri, false, QR_ECLEVEL_H, 8, 1);
if (function_exists('ImageCreate')) {
QRcode::png($uri, $filename, QR_ECLEVEL_H, 8, 1);
}
$raw = base64_encode(file_get_contents($filename));
$raw = 'data:image/png;base64,'.$raw;
if (!$persistent) {
unlink($filename);
}
# As a final option, get a URL fallback
# https://developers.google.com/chart/infographics/docs/qr_codes?csw=1
$url = 'https://chart.googleapis.com/chart?cht=qr&chs=500x500&chld=H&chl='.$uri;
return array('status' => true,'uri' => $uri,'svg' => $svg,'raw' => $raw,'url' => $url);
} catch (Exception $e) {
return array('status' => false,'human_error' => 'Unable to generate QR code','error' => $e->getMessage(),'uri' => $uri,'identifier' => $identifier,'persistent' => $persistent);
}
}
/***
* Primary functions
***/
public function createUser($username, $pw_in, $name, $dname, $phone = null)
{
/***
* Create a new user
*
* @param string $username A valid email address
* @param string pw_in The input password. This function will hash it.
* @param array $name An array of form array(firstName,lastName)
* @param string $dname The display name of the user.
* @return array {"status"=>bool,"error"=>message,"message"=>user message,[userdata,cookies,auth_result]}
***/
if (strlen($pw_in) > 8192) {
return array('status' => false,'error' => 'Passwords must be less than 8192 characters in length.');
}
// Send email for validation
$ou = $username;
/***
* Weaker, but use if you have problems with the sanitize() function.
$l=$this->openDB();
$user=mysqli_real_escape_string($l,$username);
***/
$user = $this->sanitize($username);
$preg = "/[a-z0-9!#$%&'*+=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[a-z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)\b/";
if (!self::isValidEmail($username)) {
return array('status' => false,'error' => 'Your email is not a valid email address. Please try again.');
} else {
$username = $user;
} # synonymize
if (strlen(implode(' ', $name)) > 200 || strlen($dname) > 100) {
return array('status' => false,'error' => 'Your name must be less than 100 characters.');
}
$result = $this->lookupItem($user, $this->userColumn);
if ($result !== false) {
$data = mysqli_fetch_assoc($result);
if ($data[$this->userColumn] == $username) {
return array('status' => false, 'error' => 'Duplicate username', 'human_error' => 'Your email is already registered. Please try again. Did you forget your password?', 'app_error_code' => 123);
}
}
if (strlen($pw_in) < $this->getMinPasswordLength()) {
return array('status' => false,'error' => 'Your password is too short. Please try again.');
}
# Complexity checks here, if not relegated to JS ...
if (!class_exists('Stronghash')) {
require_once dirname(__FILE__).'/../core/stronghash/php-stronghash.php';
}
$hash = new Stronghash();
$creation = self::microtime_float();
$pw1 = $hash->hasher($pw_in);
$pw_store = json_encode($pw1);
$algo = $pw1['algo'];
$salt = $pw1['salt'];
if (!empty($pw1['rounds'])) {
$rounds = '<rounds>'.$pw1['rounds'].'</rounds>';
}
$data_init = "<xml><algo>$algo</algo>$rounds</xml>";
$name = $this->sanitize($name);
$dname = $this->sanitize($dname);
$iv = $this->getIV();
# only encrypt if requested, then put in secdata
$ne = self::encryptThis($salt.$pw, implode(' ', $name), $iv);
$sdata_init = '<xml><name>'.$ne.'</name></xml>';
$names = '<xml><name>'.$this->sanitize(implode(' ', $name)).'</name><fname>'.$this->sanitize($name[0]).'</fname><lname>'.$name[1].'</lname><dname>'.$this->sanitize($dname).'</dname></xml>';
$hardlink = sha1($salt.$creation);
$store = array();
foreach ($this->getCols() as $key => $type) {
switch ($key) {
case $this->userColumn:
$store[$key] = $user;
break;
case $this->pwColumn:
$store[$key] = $pw_store; # Generated
break;
case 'salt':
$store[$key] = $salt; # Generated
case 'creation':
$store[$key] = $creation; # Generated
break;
case 'name':
$store[$key] = $names; # Generated