BioTorrents.de’s version of Gazelle
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.php 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. <?php
  2. #declare(strict_types=1);
  3. $ENV = ENV::go();
  4. /*-- todo ---------------------------//
  5. Add the JavaScript validation into the display page using the class
  6. //-----------------------------------*/
  7. // Allow users to reset their password while logged in
  8. if (!empty($LoggedUser['ID']) && $_REQUEST['act'] !== 'recover') {
  9. header('Location: index.php');
  10. error();
  11. }
  12. if ($ENV->BLOCK_OPERA_MINI && isset($_SERVER['HTTP_X_OPERAMINI_PHONE'])) {
  13. error('Opera Mini is banned. Please use another browser.');
  14. }
  15. // Check if IP is banned
  16. if (Tools::site_ban_ip($_SERVER['REMOTE_ADDR'])) {
  17. error('Your IP address has been banned.');
  18. }
  19. # Initialize
  20. require_once SERVER_ROOT.'/classes/twofa.class.php';
  21. require_once SERVER_ROOT.'/classes/u2f.class.php';
  22. require_once SERVER_ROOT.'/classes/validate.class.php';
  23. $Validate = new Validate;
  24. $TwoFA = new TwoFactorAuth($ENV->SITE_NAME);
  25. $U2F = new u2f\U2F('https://'.SITE_DOMAIN);
  26. if (array_key_exists('action', $_GET) && $_GET['action'] === 'disabled') {
  27. require('disabled.php');
  28. error();
  29. }
  30. if (isset($_REQUEST['act']) && $_REQUEST['act'] === 'recover') {
  31. // Recover password
  32. if (!empty($_REQUEST['key'])) {
  33. // User has entered a new password, use step 2
  34. $DB->query("
  35. SELECT
  36. m.`ID`,
  37. m.`Email`,
  38. i.`ResetExpires`
  39. FROM `users_main` AS m
  40. INNER JOIN `users_info` AS i ON i.`UserID` = m.`ID`
  41. WHERE i.`ResetKey` = ?
  42. AND i.`ResetKey` != ''", $_REQUEST['key']);
  43. list($UserID, $Email, $Country, $Expires) = $DB->next_record();
  44. if (!apcu_exists('DBKEY')) {
  45. error('Database not fully decrypted. Please wait for staff to fix this and try again later.');
  46. }
  47. $Email = Crypto::decrypt($Email);
  48. if ($UserID && strtotime($Expires) > time()) {
  49. // If the user has requested a password change, and his key has not expired
  50. $Validate->SetFields('password', '1', 'regex', 'You entered an invalid password. Any password at least 15 characters long is accepted, but a strong password is 8 characters or longer, contains at least 1 lowercase and uppercase letter, contains at least a number or symbol', array('regex' => '/(?=^.{6,}$).*$/'));
  51. $Validate->SetFields('verifypassword', '1', 'compare', 'Your passwords did not match.', array('comparefield' => 'password'));
  52. if (!empty($_REQUEST['password'])) {
  53. // If the user entered a password.
  54. // If not, $PassWasReset !== 1, success message hidden.
  55. $Err = $Validate->ValidateForm($_REQUEST);
  56. if ($Err == '') {
  57. // Form validates without error, set new secret and password.
  58. $DB->query(
  59. "
  60. UPDATE
  61. `users_main` AS m,
  62. `users_info` AS i
  63. SET
  64. m.`PassHash` = ?,
  65. i.`ResetKey` = '',
  66. m.`LastLogin` = NOW(),
  67. i.`ResetExpires` = NULL
  68. WHERE m.`ID` = ?
  69. AND i.`UserID` = m.`ID`",
  70. Users::make_sec_hash($_REQUEST['password']),
  71. $UserID
  72. );
  73. $DB->query("
  74. INSERT INTO `users_history_passwords`
  75. (`UserID`, `ChangerIP`, `ChangeTime`)
  76. VALUES
  77. (?, ?, NOW())", $UserID, Crypto::encrypt($_SERVER['REMOTE_ADDR']));
  78. $PassWasReset = true;
  79. $LoggedUser['ID'] = $UserID; // Set $LoggedUser['ID'] for logout_all_sessions() to work
  80. logout_all_sessions();
  81. }
  82. }
  83. // Either a form asking for them to enter the password
  84. // Or a success message if $PassWasReset is 1
  85. require('recover_step2.php');
  86. } else {
  87. // Either his key has expired, or he hasn't requested a pass change at all
  88. if (strtotime($Expires) < time() && $UserID) {
  89. // If his key has expired, clear all the reset information
  90. $DB->query("
  91. UPDATE users_info
  92. SET ResetKey = '',
  93. ResetExpires = NULL
  94. WHERE UserID = ?", $UserID);
  95. $_SESSION['reseterr'] = 'The link you were given has expired.'; // Error message to display on form
  96. }
  97. // Show him the first form (enter email address)
  98. header('Location: login.php?act=recover');
  99. }
  100. } // End step 2
  101. // User has not clicked the link in his email, use step 1
  102. else {
  103. # Check for DBKEY before handling user inputs
  104. if (!apcu_exists('DBKEY')) {
  105. $Err = 'Database not fully decrypted. Please wait for staff to fix this and try again';
  106. }
  107. if (!empty($_REQUEST['email'])) {
  108. // User has entered email and submitted form
  109. $Validate->SetFields('email', '1', 'email', 'You entered an invalid email address');
  110. $Err = $Validate->ValidateForm($_REQUEST);
  111. if (!$Err) {
  112. // Form validates correctly
  113. $DB->query("
  114. SELECT
  115. `Email`
  116. FROM
  117. `users_main`
  118. ");
  119. /**
  120. * Note that if any user has a blank email field,
  121. * the comparison will fail and the script will 500!
  122. */
  123. while (list($EncEmail) = $DB->next_record()) {
  124. if (trim(
  125. strtolower($_REQUEST['email'])
  126. ) === strtolower(Crypto::decrypt($EncEmail))) {
  127. break; // $EncEmail is now the encrypted form of the given email from the database
  128. }
  129. }
  130. $DB->query("
  131. SELECT
  132. `ID`,
  133. `Username`,
  134. `Email`
  135. FROM
  136. `users_main`
  137. WHERE
  138. `Email` = '$EncEmail'
  139. ");
  140. list($UserID, $Username, $Email) = $DB->next_record();
  141. $Email = Crypto::decrypt($Email);
  142. if ($UserID) {
  143. // Email exists in the database
  144. // Set ResetKey, send out email, and set $Sent to 1 to show success page
  145. Users::reset_password($UserID, $Username, $Email);
  146. $Sent = 1; // If $Sent is 1, recover_step1.php displays a success message
  147. //Log out all of the users current sessions
  148. $Cache->delete_value("user_info_$UserID");
  149. $Cache->delete_value("user_info_heavy_$UserID");
  150. $Cache->delete_value("user_stats_$UserID");
  151. $Cache->delete_value("enabled_$UserID");
  152. $DB->query("
  153. SELECT
  154. `SessionID`
  155. FROM
  156. `users_sessions`
  157. WHERE
  158. `UserID` = '$UserID'
  159. ");
  160. while (list($SessionID) = $DB->next_record()) {
  161. $Cache->delete_value("session_$UserID"."_$SessionID");
  162. }
  163. $DB->query("
  164. UPDATE
  165. `users_sessions`
  166. SET
  167. `Active` = 0
  168. WHERE
  169. `UserID` = '$UserID'
  170. AND `Active` = 1
  171. ");
  172. } else {
  173. $Err = 'There is no user with that email address.';
  174. }
  175. }
  176. } elseif (!empty($_SESSION['reseterr'])) {
  177. // User has not entered email address, and there is an error set in session data
  178. // This is typically because their key has expired.
  179. // Stick the error into $Err so recover_step1.php can take care of it
  180. $Err = $_SESSION['reseterr'];
  181. unset($_SESSION['reseterr']);
  182. }
  183. // Either a form for the user's email address, or a success message
  184. require('recover_step1.php');
  185. }
  186. } // End password recovery
  187. elseif (isset($_REQUEST['act']) && $_REQUEST['act'] === 'newlocation') {
  188. if (isset($_REQUEST['key'])) {
  189. if ($ASNCache = $Cache->get_value('new_location_'.$_REQUEST['key'])) {
  190. $Cache->cache_value('new_location_'.$ASNCache['UserID'].'_'.$ASNCache['ASN'], true);
  191. require('newlocation.php');
  192. error();
  193. } else {
  194. error(403);
  195. }
  196. } else {
  197. error(403);
  198. }
  199. } // End new location
  200. // Normal login
  201. else {
  202. $Validate->SetFields('username', true, 'regex', 'You did not enter a valid username', array('regex' => USERNAME_REGEX));
  203. $Validate->SetFields('password', '1', 'string', 'You entered an invalid password', array('minlength' => '15', 'maxlength' => '307200'));
  204. list($Attempts, $Banned) = $Cache->get_value('login_attempts_'.db_string($_SERVER['REMOTE_ADDR']));
  205. // Function to log a user's login attempt
  206. function log_attempt()
  207. {
  208. global $Cache, $Attempts;
  209. $Attempts = ($Attempts ?? 0) + 1;
  210. $Cache->cache_value('login_attempts_'.db_string($_SERVER['REMOTE_ADDR']), array($Attempts, ($Attempts > 5)), 60*60*$Attempts);
  211. $AllAttempts = $Cache->get_value('login_attempts');
  212. $AllAttempts[$_SERVER['REMOTE_ADDR']] = time()+(60*60*$Attempts);
  213. foreach ($AllAttempts as $IP => $Time) {
  214. if ($Time < time()) {
  215. unset($AllAttempts[$IP]);
  216. }
  217. }
  218. $Cache->cache_value('login_attempts', $AllAttempts, 0);
  219. }
  220. // If user has submitted form
  221. if (isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['password']) && !empty($_POST['password'])) {
  222. if ($Banned) {
  223. header("Location: login.php");
  224. error();
  225. }
  226. $Err = $Validate->ValidateForm($_POST);
  227. if (!$Err) {
  228. // Passes preliminary validation (username and password "look right")
  229. $DB->query("
  230. SELECT
  231. ID,
  232. PermissionID,
  233. CustomPermissions,
  234. PassHash,
  235. TwoFactor,
  236. Enabled
  237. FROM users_main
  238. WHERE Username = ?
  239. AND Username != ''", $_POST['username']);
  240. list($UserID, $PermissionID, $CustomPermissions, $PassHash, $TwoFactor, $Enabled) = $DB->next_record(MYSQLI_NUM, array(2));
  241. if (!$Banned) {
  242. if ($UserID && Users::check_password($_POST['password'], $PassHash)) {
  243. // Update hash if better algorithm available
  244. if (password_needs_rehash($PassHash, PASSWORD_DEFAULT)) {
  245. $DB->query("
  246. UPDATE users_main
  247. SET PassHash = ?
  248. WHERE Username = ?", make_sec_hash($_POST['password']), $_POST['username']);
  249. }
  250. if (empty($TwoFactor) || $TwoFA->verifyCode($TwoFactor, $_POST['twofa'])) {
  251. # todo: Make sure the type is (int)
  252. if ($Enabled === '1') {
  253. // Check if the current login attempt is from a location previously logged in from
  254. if (apcu_exists('DBKEY')) {
  255. $DB->query("
  256. SELECT
  257. `IP`
  258. FROM
  259. `users_history_ips`
  260. WHERE
  261. `UserID` = '$UserID'
  262. ");
  263. $IPs = $DB->to_array(false, MYSQLI_NUM);
  264. $QueryParts = [];
  265. foreach ($IPs as $i => $IP) {
  266. $IPs[$i] = Crypto::decrypt($IP[0]);
  267. }
  268. $IPs = array_unique($IPs);
  269. if (count($IPs) > 0) { // Always allow first login
  270. foreach ($IPs as $IP) {
  271. $QueryParts[] = "(StartIP<=INET6_ATON('$IP') AND EndIP>=INET6_ATON('$IP'))";
  272. }
  273. $DB->query('SELECT ASN FROM geoip_asn WHERE '.implode(' OR ', $QueryParts));
  274. $PastASNs = array_column($DB->to_array(false, MYSQLI_NUM), 0);
  275. $DB->query("SELECT ASN FROM geoip_asn WHERE StartIP<=INET6_ATON('$_SERVER[REMOTE_ADDR]') AND EndIP>=INET6_ATON('$_SERVER[REMOTE_ADDR]')");
  276. list($CurrentASN) = $DB->next_record();
  277. // If FEATURE_ENFORCE_LOCATIONS is enabled, require users to confirm new logins
  278. if (!in_array($CurrentASN, $PastASNs) && $ENV->FEATURE_ENFORCE_LOCATIONS) {
  279. // Never logged in from this location before
  280. if ($Cache->get_value('new_location_'.$UserID.'_'.$CurrentASN) !== true) {
  281. $DB->query("
  282. SELECT
  283. `UserName`,
  284. `Email`
  285. FROM
  286. `users_main`
  287. WHERE
  288. `ID` = '$UserID'
  289. ");
  290. list($Username, $Email) = $DB->next_record();
  291. Users::auth_location($UserID, $Username, $CurrentASN, Crypto::decrypt($Email));
  292. require('newlocation.php');
  293. error();
  294. }
  295. }
  296. }
  297. }
  298. $U2FRegs = [];
  299. $DB->query("
  300. SELECT KeyHandle, PublicKey, Certificate, Counter, Valid
  301. FROM u2f
  302. WHERE UserID = ?", $UserID);
  303. // Needs to be an array of objects, so we can't use to_array()
  304. while (list($KeyHandle, $PublicKey, $Certificate, $Counter, $Valid) = $DB->next_record()) {
  305. $U2FRegs[] = (object)['keyHandle'=>$KeyHandle, 'publicKey'=>$PublicKey, 'certificate'=>$Certificate, 'counter'=>$Counter, 'valid'=>$Valid];
  306. }
  307. if (sizeof($U2FRegs) > 0) {
  308. // U2F is enabled for this account
  309. if (isset($_POST['u2f-request']) && isset($_POST['u2f-response'])) {
  310. // Data from the U2F login page is present. Verify it.
  311. try {
  312. $U2FReg = $U2F->doAuthenticate(json_decode($_POST['u2f-request']), $U2FRegs, json_decode($_POST['u2f-response']));
  313. if ($U2FReg->valid != '1') {
  314. error('Token disabled.');
  315. }
  316. $DB->query(
  317. "UPDATE u2f
  318. SET Counter = ?
  319. WHERE KeyHandle = ?
  320. AND UserID = ?",
  321. $U2FReg->counter,
  322. $U2FReg->keyHandle,
  323. $UserID
  324. );
  325. } catch (Exception $e) {
  326. $U2FErr = 'U2F key invalid. Error: '.($e->getMessage());
  327. if ($e->getMessage() == 'Token disabled.') {
  328. $U2FErr = 'This token was disabled due to suspected cloning. Contact staff for assistance';
  329. }
  330. if ($e->getMessage() == 'Counter too low.') {
  331. $BadHandle = json_decode($_POST['u2f-response'], true)['keyHandle'];
  332. $DB->query("UPDATE u2f
  333. SET Valid = '0'
  334. WHERE KeyHandle = ?
  335. AND UserID = ?", $BadHandle, $UserID);
  336. $U2FErr = 'U2F counter too low. This token has been disabled due to suspected cloning. Contact staff for assistance';
  337. }
  338. }
  339. } else {
  340. // Data from the U2F login page is not present. Go there
  341. require('u2f.php');
  342. error();
  343. }
  344. }
  345. if (sizeof($U2FRegs) == 0 || !isset($U2FErr)) {
  346. $SessionID = Users::make_secret(64);
  347. setcookie('session', $SessionID, (time()+60*60*24*365), '/', '', true, true);
  348. setcookie('userid', $UserID, (time()+60*60*24*365), '/', '', true, true);
  349. // Because we <3 our staff
  350. $Permissions = Permissions::get_permissions($PermissionID);
  351. $CustomPermissions = unserialize($CustomPermissions);
  352. if (isset($Permissions['Permissions']['site_disable_ip_history'])
  353. || isset($CustomPermissions['site_disable_ip_history'])
  354. ) {
  355. $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
  356. }
  357. $DB->query("
  358. INSERT INTO users_sessions
  359. (UserID, SessionID, KeepLogged, Browser, OperatingSystem, IP, LastUpdate, FullUA)
  360. VALUES
  361. ('$UserID', '".db_string($SessionID)."', '1', '$Browser', '$OperatingSystem', '".db_string(apcu_exists('DBKEY')?Crypto::encrypt($_SERVER['REMOTE_ADDR']):'0.0.0.0')."', NOW(), '".db_string($_SERVER['HTTP_USER_AGENT'])."')");
  362. $Cache->begin_transaction("users_sessions_$UserID");
  363. $Cache->insert_front($SessionID, [
  364. 'SessionID' => $SessionID,
  365. 'Browser' => $Browser,
  366. 'OperatingSystem' => $OperatingSystem,
  367. 'IP' => (apcu_exists('DBKEY')?Crypto::encrypt($_SERVER['REMOTE_ADDR']):'0.0.0.0'),
  368. 'LastUpdate' => sqltime()
  369. ]);
  370. $Cache->commit_transaction(0);
  371. $Sql = "
  372. UPDATE users_main
  373. SET
  374. LastLogin = NOW(),
  375. LastAccess = NOW()
  376. WHERE ID = '".db_string($UserID)."'";
  377. $DB->query($Sql);
  378. if (!empty($_COOKIE['redirect'])) {
  379. $URL = $_COOKIE['redirect'];
  380. setcookie('redirect', '', time() - 60 * 60 * 24, '/', '', false);
  381. header("Location: $URL");
  382. error();
  383. } else {
  384. header('Location: index.php');
  385. error();
  386. }
  387. } else {
  388. log_attempt();
  389. $Err = $U2FErr;
  390. setcookie('keeplogged', '', time() + 60 * 60 * 24 * 365, '/', '', false);
  391. }
  392. } else {
  393. log_attempt();
  394. if ($Enabled == 2) {
  395. // Save the username in a cookie for the disabled page
  396. setcookie('username', db_string($_POST['username']), time() + 60 * 60, '/', '', false);
  397. header('Location: login.php?action=disabled');
  398. # todo: Make sure the type is (int)
  399. } elseif ($Enabled === '0') {
  400. $Err = 'Your account has not been confirmed. Please check your email, including the spam folder';
  401. }
  402. setcookie('keeplogged', '', time() + 60 * 60 * 24 * 365, '/', '', false);
  403. }
  404. } else {
  405. log_attempt();
  406. $Err = 'Two-factor authentication failed';
  407. setcookie('keeplogged', '', time() + 60 * 60 * 24 * 365, '/', '', false);
  408. }
  409. } else {
  410. log_attempt();
  411. $Err = 'Your username or password was incorrect';
  412. setcookie('keeplogged', '', time() + 60 * 60 * 24 * 365, '/', '', false);
  413. }
  414. } else {
  415. log_attempt();
  416. setcookie('keeplogged', '', time() + 60 * 60 * 24 * 365, '/', '', false);
  417. }
  418. } else {
  419. log_attempt();
  420. setcookie('keeplogged', '', time() + 60 * 60 * 24 * 365, '/', '', false);
  421. }
  422. }
  423. require('sections/login/login.php');
  424. }