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

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