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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. <?php
  2. #declare(strict_types=1);
  3. # Unsure if require_once is needed here
  4. require_once 'classes/env.class.php';
  5. $ENV = ENV::go();
  6. /*-- todo ---------------------------//
  7. Add the JavaScript validation into the display page using the class
  8. //-----------------------------------*/
  9. // Allow users to reset their password while logged in
  10. if (!empty($LoggedUser['ID']) && $_REQUEST['act'] != 'recover') {
  11. header('Location: index.php');
  12. error();
  13. }
  14. if ($ENV->BLOCK_OPERA_MINI && isset($_SERVER['HTTP_X_OPERAMINI_PHONE'])) {
  15. error('Opera Mini is banned. Please use another browser.');
  16. }
  17. // Check if IP is banned
  18. if (Tools::site_ban_ip($_SERVER['REMOTE_ADDR'])) {
  19. error('Your IP address has been banned.');
  20. }
  21. require_once SERVER_ROOT.'/classes/twofa.class.php';
  22. require_once SERVER_ROOT.'/classes/u2f.class.php';
  23. require_once SERVER_ROOT.'/classes/validate.class.php';
  24. $Validate = new Validate;
  25. $TwoFA = new TwoFactorAuth($ENV->SITE_NAME);
  26. $U2F = new u2f\U2F('https://'.SITE_DOMAIN);
  27. # todo: Test strict equality very gently here
  28. if (array_key_exists('action', $_GET) && $_GET['action'] == 'disabled') {
  29. require('disabled.php');
  30. error();
  31. }
  32. if (isset($_REQUEST['act']) && $_REQUEST['act'] == 'recover') {
  33. // Recover password
  34. if (!empty($_REQUEST['key'])) {
  35. // User has entered a new password, use step 2
  36. $DB->query("
  37. SELECT
  38. m.ID,
  39. m.Email,
  40. i.ResetExpires
  41. FROM users_main AS m
  42. INNER JOIN users_info AS i ON i.UserID = m.ID
  43. WHERE i.ResetKey = ?
  44. AND i.ResetKey != ''", $_REQUEST['key']);
  45. list($UserID, $Email, $Country, $Expires) = $DB->next_record();
  46. if (!apcu_exists('DBKEY')) {
  47. error('Database not fully decrypted. Please wait for staff to fix this and try again later');
  48. }
  49. $Email = Crypto::decrypt($Email);
  50. if ($UserID && strtotime($Expires) > time()) {
  51. // If the user has requested a password change, and his key has not expired
  52. $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,}$).*$/'));
  53. $Validate->SetFields('verifypassword', '1', 'compare', 'Your passwords did not match.', array('comparefield' => 'password'));
  54. if (!empty($_REQUEST['password'])) {
  55. // If the user has entered a password.
  56. // If the user has not entered a password, $PassWasReset is not set to 1, and the success message is not shown
  57. $Err = $Validate->ValidateForm($_REQUEST);
  58. if ($Err == '') {
  59. // Form validates without error, set new secret and password.
  60. $DB->query("
  61. UPDATE
  62. users_main AS m,
  63. users_info AS i
  64. SET
  65. m.PassHash = ?,
  66. i.ResetKey = '',
  67. m.LastLogin = NOW(),
  68. i.ResetExpires = NULL
  69. WHERE m.ID = ?
  70. AND i.UserID = m.ID", Users::make_sec_hash($_REQUEST['password']), $UserID);
  71. $DB->query("
  72. INSERT INTO users_history_passwords
  73. (UserID, ChangerIP, ChangeTime)
  74. VALUES
  75. (?, ?, NOW())", $UserID, Crypto::encrypt($_SERVER['REMOTE_ADDR']));
  76. $PassWasReset = true;
  77. $LoggedUser['ID'] = $UserID; // Set $LoggedUser['ID'] for logout_all_sessions() to work
  78. logout_all_sessions();
  79. }
  80. }
  81. // Either a form asking for them to enter the password
  82. // Or a success message if $PassWasReset is 1
  83. require('recover_step2.php');
  84. } else {
  85. // Either his key has expired, or he hasn't requested a pass change at all
  86. if (strtotime($Expires) < time() && $UserID) {
  87. // If his key has expired, clear all the reset information
  88. $DB->query("
  89. UPDATE users_info
  90. SET ResetKey = '',
  91. ResetExpires = NULL
  92. WHERE UserID = ?", $UserID);
  93. $_SESSION['reseterr'] = 'The link you were given has expired.'; // Error message to display on form
  94. }
  95. // Show him the first form (enter email address)
  96. header('Location: login.php?act=recover');
  97. }
  98. } // End step 2
  99. // User has not clicked the link in his email, use step 1
  100. else {
  101. # Check for DBKEY before handling user inputs
  102. if (!apcu_exists('DBKEY')) {
  103. $Err = 'Database not fully decrypted. Please wait for staff to fix this and try again';
  104. }
  105. if (!empty($_REQUEST['email'])) {
  106. // User has entered email and submitted form
  107. $Validate->SetFields('email', '1', 'email', 'You entered an invalid email address');
  108. $Err = $Validate->ValidateForm($_REQUEST);
  109. if (!$Err) {
  110. // Form validates correctly
  111. $DB->query("
  112. SELECT
  113. `Email`
  114. FROM
  115. `users_main`
  116. ");
  117. /**
  118. * Note that if any user has a blank email field,
  119. * the comparison will fail and the script will 500!
  120. */
  121. while (list($EncEmail) = $DB->next_record()) {
  122. if (trim(
  123. strtolower($_REQUEST['email'])
  124. ) === strtolower(Crypto::decrypt($EncEmail))) {
  125. break; // $EncEmail is now the encrypted form of the given email from the database
  126. }
  127. }
  128. $DB->query("
  129. SELECT
  130. `ID`,
  131. `Username`,
  132. `Email`
  133. FROM
  134. `users_main`
  135. WHERE
  136. `Email` = '$EncEmail'
  137. ");
  138. list($UserID, $Username, $Email) = $DB->next_record();
  139. $Email = Crypto::decrypt($Email);
  140. if ($UserID) {
  141. // Email exists in the database
  142. // Set ResetKey, send out email, and set $Sent to 1 to show success page
  143. Users::reset_password($UserID, $Username, $Email);
  144. $Sent = 1; // If $Sent is 1, recover_step1.php displays a success message
  145. //Log out all of the users current sessions
  146. $Cache->delete_value("user_info_$UserID");
  147. $Cache->delete_value("user_info_heavy_$UserID");
  148. $Cache->delete_value("user_stats_$UserID");
  149. $Cache->delete_value("enabled_$UserID");
  150. $DB->query("
  151. SELECT
  152. `SessionID`
  153. FROM
  154. `users_sessions`
  155. WHERE
  156. `UserID` = '$UserID'
  157. ");
  158. while (list($SessionID) = $DB->next_record()) {
  159. $Cache->delete_value("session_$UserID"."_$SessionID");
  160. }
  161. $DB->query("
  162. UPDATE
  163. `users_sessions`
  164. SET
  165. `Active` = 0
  166. WHERE
  167. `UserID` = '$UserID'
  168. AND `Active` = 1
  169. ");
  170. } else {
  171. $Err = 'There is no user with that email address';
  172. }
  173. }
  174. } elseif (!empty($_SESSION['reseterr'])) {
  175. // User has not entered email address, and there is an error set in session data
  176. // This is typically because their key has expired.
  177. // Stick the error into $Err so recover_step1.php can take care of it
  178. $Err = $_SESSION['reseterr'];
  179. unset($_SESSION['reseterr']);
  180. }
  181. // Either a form for the user's email address, or a success message
  182. require('recover_step1.php');
  183. }
  184. } // End password recovery
  185. elseif (isset($_REQUEST['act']) && $_REQUEST['act'] == 'newlocation') {
  186. if (isset($_REQUEST['key'])) {
  187. if ($ASNCache = $Cache->get_value('new_location_'.$_REQUEST['key'])) {
  188. $Cache->cache_value('new_location_'.$ASNCache['UserID'].'_'.$ASNCache['ASN'], true);
  189. require('newlocation.php');
  190. error();
  191. } else {
  192. error(403);
  193. }
  194. } else {
  195. error(403);
  196. }
  197. } // End new location
  198. // Normal login
  199. else {
  200. $Validate->SetFields('username', true, 'regex', 'You did not enter a valid username', array('regex' => USERNAME_REGEX));
  201. $Validate->SetFields('password', '1', 'string', 'You entered an invalid password', array('minlength' => '6', 'maxlength' => '307200'));
  202. list($Attempts, $Banned) = $Cache->get_value('login_attempts_'.db_string($_SERVER['REMOTE_ADDR']));
  203. // Function to log a user's login attempt
  204. function log_attempt()
  205. {
  206. global $Cache, $Attempts;
  207. $Attempts = ($Attempts ?? 0) + 1;
  208. $Cache->cache_value('login_attempts_'.db_string($_SERVER['REMOTE_ADDR']), array($Attempts, ($Attempts > 5)), 60*60*$Attempts);
  209. $AllAttempts = $Cache->get_value('login_attempts');
  210. $AllAttempts[$_SERVER['REMOTE_ADDR']] = time()+(60*60*$Attempts);
  211. foreach ($AllAttempts as $IP => $Time) {
  212. if ($Time < time()) {
  213. unset($AllAttempts[$IP]);
  214. }
  215. }
  216. $Cache->cache_value('login_attempts', $AllAttempts, 0);
  217. }
  218. // If user has submitted form
  219. if (isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['password']) && !empty($_POST['password'])) {
  220. if ($Banned) {
  221. header("Location: login.php");
  222. error();
  223. }
  224. $Err = $Validate->ValidateForm($_POST);
  225. if (!$Err) {
  226. // Passes preliminary validation (username and password "look right")
  227. $DB->query("
  228. SELECT
  229. ID,
  230. PermissionID,
  231. CustomPermissions,
  232. PassHash,
  233. TwoFactor,
  234. Enabled
  235. FROM users_main
  236. WHERE Username = ?
  237. AND Username != ''", $_POST['username']);
  238. list($UserID, $PermissionID, $CustomPermissions, $PassHash, $TwoFactor, $Enabled) = $DB->next_record(MYSQLI_NUM, array(2));
  239. if (!$Banned) {
  240. if ($UserID && Users::check_password($_POST['password'], $PassHash)) {
  241. // Update hash if better algorithm available
  242. if (password_needs_rehash($PassHash, PASSWORD_DEFAULT)) {
  243. $DB->query("
  244. UPDATE users_main
  245. SET PassHash = ?
  246. WHERE Username = ?", make_sec_hash($_POST['password']), $_POST['username']);
  247. }
  248. if (empty($TwoFactor) || $TwoFA->verifyCode($TwoFactor, $_POST['twofa'])) {
  249. # todo: Make sure the type is (int)
  250. if ($Enabled === '1') {
  251. // Check if the current login attempt is from a location previously logged in from
  252. if (apcu_exists('DBKEY')) {
  253. $DB->query("
  254. SELECT
  255. `IP`
  256. FROM
  257. `users_history_ips`
  258. WHERE
  259. `UserID` = '$UserID'
  260. ");
  261. $IPs = $DB->to_array(false, MYSQLI_NUM);
  262. $QueryParts = [];
  263. foreach ($IPs as $i => $IP) {
  264. $IPs[$i] = Crypto::decrypt($IP[0]);
  265. }
  266. $IPs = array_unique($IPs);
  267. if (count($IPs) > 0) { // Always allow first login
  268. foreach ($IPs as $IP) {
  269. $QueryParts[] = "(StartIP<=INET6_ATON('$IP') AND EndIP>=INET6_ATON('$IP'))";
  270. }
  271. /*
  272. $DB->query('SELECT ASN FROM geoip_asn WHERE '.implode(' OR ', $QueryParts));
  273. $PastASNs = array_column($DB->to_array(false, MYSQLI_NUM), 0);
  274. $DB->query("SELECT ASN FROM geoip_asn WHERE StartIP<=INET6_ATON('$_SERVER[REMOTE_ADDR]') AND EndIP>=INET6_ATON('$_SERVER[REMOTE_ADDR]')");
  275. list($CurrentASN) = $DB->next_record();
  276. */
  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. }