Assignments On Class 38: Session Management and Security
Assignment 1: Secure Session Management in PHP
Objective:
- Implement
secure session management by using techniques such as session ID
regeneration, secure cookies, session timeout, and binding sessions to the
user’s IP address and User-Agent.
Instructions:
1.
Create a PHP application that allows users to log
in.
2.
After a successful login, implement the following
security measures:
o
Regenerate the session ID to prevent session
fixation.
o
Set secure session cookies with the secure and HttpOnly flags.
o
Implement session timeout after 15 minutes of
inactivity.
o
Bind the session to the user’s IP address and
User-Agent.
3.
Add a simple logout feature to destroy the session
and log out the user.
Step-by-Step Solution:
1.
Start by creating a simple login form (login.php):
html
Copy code
<form action="login.php"
method="POST">
<label for="username">Username:
</label>
<input type="text" id="username"
name="username" required><br>
<label for="password">Password:
</label>
<input type="password" id="password"
name="password" required><br>
<input type="submit" value="Login">
</form>
2.
Create the login processing script (login_process.php):
php
Copy code
<?php
session_start();
// Hardcoded user credentials for
simplicity
$valid_username = "user";
$valid_password = "password123";
if ($_SERVER['REQUEST_METHOD'] ==
'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
// Check credentials
if ($username === $valid_username
&& $password === $valid_password) {
// Regenerate session ID to prevent
session fixation
session_regenerate_id(true);
// Set secure session cookies
session_set_cookie_params([
'secure' => true, // Only send cookie over HTTPS
'httponly' => true, // Prevent JavaScript access to the cookie
'samesite' => 'Strict' // Prevent cross-site request forgery
]);
$_SESSION['username'] = $username;
$_SESSION['last_activity'] = time(); // Set the last activity time
// Store the user's IP and User-Agent
for binding
$_SESSION['ip_address'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
header("Location:
dashboard.php");
} else {
echo "Invalid credentials!";
}
}
?>
3.
Implement session timeout and binding to IP/
User-Agent (dashboard.php):
php
Copy code
<?php
session_start();
// Check if session is valid (IP
and User-Agent matching)
if ($_SESSION['ip_address'] !== $_SERVER['REMOTE_ADDR']
|| $_SESSION['user_agent'] !== $_SERVER['HTTP_USER_AGENT']) {
session_unset(); // Clear session data
session_destroy(); // Destroy session
header("Location: login.php");
exit();
}
// Implement session timeout
(after 15 minutes of inactivity)
$session_timeout = 900; // 15 minutes
if (isset($_SESSION['last_activity'])
&& (time() - $_SESSION['last_activity'] > $session_timeout)) {
session_unset(); // Clear session data
session_destroy(); // Destroy session
header("Location: login.php");
exit();
}
$_SESSION['last_activity'] = time(); // Update last activity time
// If valid, show the dashboard
content
echo "Welcome, " . $_SESSION['username']
. "!";
?>
<a href="logout.php">Logout</a>
4.
Create the logout functionality (logout.php):
php
Copy code
<?php
session_start();
session_unset(); // Clear session data
session_destroy(); // Destroy session
header("Location:
login.php");
exit();
?>
Assignment 2: Implementing CSRF Protection with
Sessions
Objective:
- Protect
your application from Cross-Site Request Forgery (CSRF) by using
session-based tokens.
Instructions:
1.
Create a PHP form (e.g., for updating user details).
2.
Add a CSRF token to the form as a hidden field.
3.
When the form is submitted, validate the CSRF token
from the session and the form to ensure it's legitimate.
4.
Display an appropriate message if the token is
invalid.
Step-by-Step Solution:
1.
Start by creating a PHP form for updating user
details (update_form.php):
php
Copy code
<?php
session_start();
// Generate a CSRF token if it
does not exist
if (!isset($_SESSION['csrf_token']))
{
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>
<form action="update_process.php"
method="POST">
<label for="username">Username:
</label>
<input type="text" id="username"
name="username" required><br>
<input type="hidden" name="csrf_token"
value="<?php echo $_SESSION['csrf_token']; ?>">
<input type="submit" value="Update">
</form>
2.
Handle the form submission and CSRF validation (update_process.php):
php
Copy code
<?php
session_start();
// Check if CSRF token is valid
if (!isset($_POST['csrf_token'])
|| $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die("CSRF token validation
failed.");
}
// Simulate updating user details
(e.g., updating a username)
if (isset($_POST['username'])) {
$username = $_POST['username'];
echo "User details updated
successfully for: " . htmlspecialchars($username);
}
// Unset the CSRF token after
successful form submission
unset($_SESSION['csrf_token']);
?>
Assignment 3: Session Hijacking Protection and
Secure Session Handling
Objective:
- Implement
security measures to prevent session hijacking and fix related
vulnerabilities.
Instructions:
1.
Create a login system with PHP where the session ID
is regenerated on login.
2.
Bind the session ID to the user's IP address and
User-Agent.
3.
Implement a mechanism that invalidates the session
if the IP address or User-Agent changes after login.
Step-by-Step Solution:
1.
Create a login page (login.php) to
accept username and password:
html
Copy code
<form action="login_process.php"
method="POST">
<label for="username">Username:
</label>
<input type="text" id="username"
name="username" required><br>
<label for="password">Password:
</label>
<input type="password" id="password"
name="password" required><br>
<input type="submit" value="Login">
</form>
2.
Process the login and regenerate the session ID (login_process.php):
php
Copy code
<?php
session_start();
// Hardcoded credentials for
simplicity
$valid_username = "user";
$valid_password = "password123";
if ($_SERVER['REQUEST_METHOD'] ==
'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
if ($username === $valid_username
&& $password === $valid_password) {
// Regenerate the session ID to prevent
session fixation
session_regenerate_id(true);
$_SESSION['username'] = $username;
$_SESSION['last_activity'] = time(); // Store the last activity time
$_SESSION['ip_address'] = $_SERVER['REMOTE_ADDR']; // Bind session to IP
$_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT']; // Bind session to User-Agent
header("Location:
dashboard.php");
} else {
echo "Invalid credentials!";
}
}
?>
3.
Validate session on the dashboard (dashboard.php):
php
Copy code
<?php
session_start();
// Validate session
if ($_SESSION['ip_address'] !== $_SERVER['REMOTE_ADDR']
|| $_SESSION['user_agent'] !== $_SERVER['HTTP_USER_AGENT']) {
session_unset(); // Unset session data
session_destroy(); // Destroy session
header("Location: login.php");
exit();
}
// Display dashboard
echo "Welcome, " . $_SESSION['username']
. "!";
?>
<a href="logout.php">Logout</a>
4.
Logout functionality (logout.php):
php
Copy code
<?php
session_start();
session_unset(); // Clear session data
session_destroy(); // Destroy session
header("Location:
login.php");
exit();
?>
Conclusion:
These
assignments introduce students to secure session management and provide
step-by-step solutions for key concepts such as session regeneration, CSRF
protection, IP/User-Agent binding, and protection against session hijacking. By
implementing these security practices, students will gain hands-on experience
in building more secure web applications.