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