Advertisement
bangnokia

Untitled

Nov 6th, 2012
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. session_start();
  3.  
  4. //require user configuration and database connection parameters
  5. require('config.php');
  6.  
  7. if (($_SESSION['logged_in'])==TRUE) {
  8. //valid user has logged-in to the website
  9.  
  10. //Check for unauthorized use of user sessions
  11.  
  12. $iprecreate= $_SERVER['REMOTE_ADDR'];
  13. $useragentrecreate=$_SERVER["HTTP_USER_AGENT"];
  14. $signaturerecreate=$_SESSION['signature'];
  15.  
  16. //Extract original salt from authorized signature
  17.  
  18. $saltrecreate = substr($signaturerecreate, 0, $length_salt);
  19.  
  20. //Extract original hash from authorized signature
  21.  
  22. $originalhash = substr($signaturerecreate, $length_salt, 40);
  23.  
  24. //Re-create the hash based on the user IP and user agent
  25. //then check if it is authorized or not
  26.  
  27. $hashrecreate= sha1($saltrecreate.$iprecreate.$useragentrecreate);
  28.  
  29. if (!($hashrecreate==$originalhash)) {
  30.  
  31. //Signature submitted by the user does not matched with the
  32. //authorized signature
  33. //This is unauthorized access
  34. //Block it
  35.  
  36. header(sprintf("Location: %s", $forbidden_url));    
  37. exit;    
  38. }
  39.  
  40. //Session Lifetime control for inactivity
  41. //Credits: http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes
  42.  
  43. if ((isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > $sessiontimeout)))  {
  44.  
  45. session_destroy();  
  46. session_unset();  
  47.  
  48. //redirect the user back to login page for re-authentication
  49.  
  50. $redirectback=$domain.'securelogin/';
  51. header(sprintf("Location: %s", $redirectback));
  52. }
  53. $_SESSION['LAST_ACTIVITY'] = time();
  54.  
  55. }
  56.  
  57. //Pre-define validation
  58. $validationresults=TRUE;
  59. $registered=TRUE;
  60. $recaptchavalidation=TRUE;
  61.  
  62. //Trapped brute force attackers and give them more hard work by providing a captcha-protected page
  63.  
  64. $iptocheck= $_SERVER['REMOTE_ADDR'];
  65. $iptocheck= mysql_real_escape_string($iptocheck);
  66.  
  67. if ($fetch = mysql_fetch_array( mysql_query("SELECT `loggedip` FROM `ipcheck` WHERE `loggedip`='$iptocheck'"))) {
  68.  
  69. //Already has some IP address records in the database
  70. //Get the total failed login attempts associated with this IP address
  71.  
  72. $resultx = mysql_query("SELECT `failedattempts` FROM `ipcheck` WHERE `loggedip`='$iptocheck'");
  73. $rowx = mysql_fetch_array($resultx);
  74. $loginattempts_total = $rowx['failedattempts'];
  75.  
  76. If ($loginattempts_total>$maxfailedattempt) {
  77.  
  78. //too many failed attempts allowed, redirect and give 403 forbidden.
  79.  
  80. header(sprintf("Location: %s", $forbidden_url));    
  81. exit;
  82. }
  83. }
  84.  
  85. //Check if a user has logged-in
  86.  
  87. if (!isset($_SESSION['logged_in'])) {
  88.     $_SESSION['logged_in'] = FALSE;
  89. }
  90.  
  91. //Check if the form is submitted
  92.  
  93. if ((isset($_POST["pass"])) && (isset($_POST["user"])) && ($_SESSION['LAST_ACTIVITY']==FALSE)) {
  94.  
  95. //Username and password has been submitted by the user
  96. //Receive and sanitize the submitted information
  97.  
  98. function sanitize($data){
  99. $data=trim($data);
  100. $data=htmlspecialchars($data);
  101. $data=mysql_real_escape_string($data);
  102. return $data;
  103. }
  104.  
  105. $user=sanitize($_POST["user"]);
  106. $pass= sanitize($_POST["pass"]);
  107.  
  108. //validate username
  109. if (!($fetch = mysql_fetch_array( mysql_query("SELECT `username` FROM `authentication` WHERE `username`='$user'")))) {
  110.  
  111. //no records of username in database
  112. //user is not yet registered
  113.  
  114. $registered=FALSE;
  115. }
  116.  
  117. if ($registered==TRUE) {
  118.  
  119. //Grab login attempts from MySQL database for a corresponding username
  120. $result1 = mysql_query("SELECT `loginattempt` FROM `authentication` WHERE `username`='$user'");
  121. $row = mysql_fetch_array($result1);
  122. $loginattempts_username = $row['loginattempt'];
  123.  
  124. }
  125.  
  126. if(($loginattempts_username>2) || ($registered==FALSE) || ($loginattempts_total>2)) {
  127.  
  128. //Require those user with login attempts failed records to
  129. //submit captcha and validate recaptcha
  130.  
  131. require_once('recaptchalib.php');
  132. $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
  133. if (!$resp->is_valid) {
  134.  
  135. //captcha validation fails
  136.  
  137. $recaptchavalidation=FALSE;
  138. } else {
  139. $recaptchavalidation=TRUE;  
  140. }
  141. }
  142.  
  143. //Get correct hashed password based on given username stored in MySQL database
  144.  
  145. if ($registered==TRUE) {
  146.  
  147. //username is registered in database, now get the hashed password
  148.  
  149. $result = mysql_query("SELECT `password` FROM `authentication` WHERE `username`='$user'");
  150. $row = mysql_fetch_array($result);
  151. $correctpassword = $row['password'];
  152. $salt = substr($correctpassword, 0, 64);
  153. $correcthash = substr($correctpassword, 64, 64);
  154. $userhash = hash("sha256", $salt . $pass);
  155. }
  156. if ((!($userhash == $correcthash)) || ($registered==FALSE) || ($recaptchavalidation==FALSE)) {
  157.  
  158. //user login validation fails
  159.  
  160. $validationresults=FALSE;
  161.  
  162. //log login failed attempts to database
  163.  
  164. if ($registered==TRUE) {
  165. $loginattempts_username= $loginattempts_username + 1;
  166. $loginattempts_username=intval($loginattempts_username);
  167.  
  168. //update login attempt records
  169.  
  170. mysql_query("UPDATE `authentication` SET `loginattempt` = '$loginattempts_username' WHERE `username` = '$user'");
  171.  
  172. //Possible brute force attacker is targeting registered usernames
  173. //check if has some IP address records
  174.  
  175. if (!($fetch = mysql_fetch_array( mysql_query("SELECT `loggedip` FROM `ipcheck` WHERE `loggedip`='$iptocheck'")))) {
  176.  
  177. //no records
  178. //insert failed attempts
  179.  
  180. $loginattempts_total=1;
  181. $loginattempts_total=intval($loginattempts_total);
  182. mysql_query("INSERT INTO `ipcheck` (`loggedip`, `failedattempts`) VALUES ('$iptocheck', '$loginattempts_total')");  
  183. } else {
  184.  
  185. //has some records, increment attempts
  186.  
  187. $loginattempts_total= $loginattempts_total + 1;
  188. mysql_query("UPDATE `ipcheck` SET `failedattempts` = '$loginattempts_total' WHERE `loggedip` = '$iptocheck'");
  189. }
  190. }
  191.  
  192. //Possible brute force attacker is targeting randomly
  193.  
  194. if ($registered==FALSE) {
  195. if (!($fetch = mysql_fetch_array( mysql_query("SELECT `loggedip` FROM `ipcheck` WHERE `loggedip`='$iptocheck'")))) {
  196.  
  197. //no records
  198. //insert failed attempts
  199.  
  200. $loginattempts_total=1;
  201. $loginattempts_total=intval($loginattempts_total);
  202. mysql_query("INSERT INTO `ipcheck` (`loggedip`, `failedattempts`) VALUES ('$iptocheck', '$loginattempts_total')");  
  203. } else {
  204.  
  205. //has some records, increment attempts
  206.  
  207. $loginattempts_total= $loginattempts_total + 1;
  208. mysql_query("UPDATE `ipcheck` SET `failedattempts` = '$loginattempts_total' WHERE `loggedip` = '$iptocheck'");
  209. }
  210. }
  211. } else {
  212.  
  213. //user successfully authenticates with the provided username and password
  214.  
  215. //Reset login attempts for a specific username to 0 as well as the ip address
  216.  
  217. $loginattempts_username=0;
  218. $loginattempts_total=0;
  219. $loginattempts_username=intval($loginattempts_username);
  220. $loginattempts_total=intval($loginattempts_total);
  221. mysql_query("UPDATE `authentication` SET `loginattempt` = '$loginattempts_username' WHERE `username` = '$user'");
  222. mysql_query("UPDATE `ipcheck` SET `failedattempts` = '$loginattempts_total' WHERE `loggedip` = '$iptocheck'");
  223.  
  224. //Generate unique signature of the user based on IP address
  225. //and the browser then append it to session
  226. //This will be used to authenticate the user session
  227. //To make sure it belongs to an authorized user and not to anyone else.
  228. //generate random salt
  229. function genRandomString() {
  230. //credits: http://bit.ly/a9rDYd
  231.     $length = 50;
  232.     $characters = "0123456789abcdef";      
  233.     for ($p = 0; $p < $length ; $p++) {
  234.         $string .= $characters[mt_rand(0, strlen($characters))];
  235.     }
  236.  
  237.     return $string;
  238. }
  239. $random=genRandomString();
  240. $salt_ip= substr($random, 0, $length_salt);
  241.  
  242. //hash the ip address, user-agent and the salt
  243. $useragent=$_SERVER["HTTP_USER_AGENT"];
  244. $hash_user= sha1($salt_ip.$iptocheck.$useragent);
  245.  
  246. //concatenate the salt and the hash to form a signature
  247. $signature= $salt_ip.$hash_user;
  248.  
  249. //Regenerate session id prior to setting any session variable
  250. //to mitigate session fixation attacks
  251.  
  252. session_regenerate_id();
  253.  
  254. //Finally store user unique signature in the session
  255. //and set logged_in to TRUE as well as start activity time
  256.  
  257. $_SESSION['signature'] = $signature;
  258. $_SESSION['logged_in'] = TRUE;
  259. $_SESSION['LAST_ACTIVITY'] = time();
  260. }
  261. }
  262.  
  263. if (!$_SESSION['logged_in']):
  264.  
  265. ?>
  266.  
  267. <!-- START OF LOGIN FORM -->
  268. <form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST">
  269. Username:  <input type="text" class="<?php if ($validationresults==FALSE) echo "invalid"; ?>" id="user" name="user">
  270. Password: <input name="pass" type="password" class="<?php if ($validationresults==FALSE) echo "invalid"; ?>" id="pass" >
  271. <?php if (($loginattempts_username > 5) || ($registered==FALSE) || ($loginattempts_total> 5)) { ?>
  272. Type the captcha below:
  273. <?php
  274. require_once('recaptchalib.php');
  275. echo recaptcha_get_html($publickey);
  276. ?>
  277. <?php } ?>
  278. <?php if ($validationresults==FALSE) echo '<font color="red">Please enter valid username, password or captcha (if required).</font>'; ?>
  279. <input type="submit" value="Login">                  
  280. </form>
  281. <!-- END OF LOGIN FORM -->
  282. <a href="register.php">Register</a>.
  283. <?php
  284. exit();
  285. endif;
  286. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement