Assignments On Class 28: PHP Security Practices

Rashmi Mishra
0

  

Assignments On Class 28: PHP Security Practices

Here are some assignments focused on PHP security practices that will help students reinforce their understanding and application of secure coding techniques.

Assignment 1: Identify Vulnerabilities

Objective: Assess an existing PHP script for common security vulnerabilities.

Instructions:

1.  Provide students with a sample PHP script that contains multiple security vulnerabilities, such as SQL Injection, XSS, CSRF, and insecure file upload.

2.  Ask students to:

o    Identify at least three vulnerabilities in the script.

o    Explain the nature of each vulnerability and how it can be exploited.

o    Provide recommendations for fixing each identified vulnerability.

Deliverables: A written report detailing the vulnerabilities and proposed solutions.


Assignment 2: Secure Coding Practices

Objective: Implement secure coding practices in a PHP application.

Instructions:

1.  Create a simple PHP application (e.g., user registration and login system).

2.  Ensure the following security measures are implemented:

o    Use prepared statements for database interactions to prevent SQL Injection.

o    Validate and sanitize all user inputs using PHP's built-in functions.

o    Implement CSRF protection in forms.

o    Ensure any output displayed to users is properly escaped to prevent XSS attacks.

o    Use HTTPS in your application (describe how you would implement it if working on a local server).

Deliverables: A functional PHP application with secure coding practices implemented, along with a short write-up explaining how security measures were applied.


Assignment 3: Error Handling and Logging

Objective: Implement error handling and logging mechanisms.

Instructions:

1.  Modify the previously created PHP application to include:

o    Custom error handling that does not display detailed error messages to users.

o    Logging of errors to a file or a logging service instead.

o    Create a custom error page that displays a user-friendly message.

2.  Include tests to ensure that errors are logged correctly without exposing sensitive information to users.

Deliverables: The modified PHP application code and a report on how the error handling and logging were implemented.


Assignment 4: Secure File Upload

Objective: Implement secure file upload functionality.

Instructions:

1.  Create a PHP script that allows users to upload files.

2.  Ensure that:

o    Only specific file types (e.g., images) are allowed.

o    File size limits are enforced.

o    File names are sanitized to prevent path traversal vulnerabilities.

o    Uploaded files are stored outside the web root directory or with appropriate permissions.

3.  Include a method to display uploaded files securely.

Deliverables: A PHP file upload script demonstrating secure practices, along with documentation on the measures taken to ensure security.


Assignment 5: Security Policy Document

Objective: Create a security policy for a hypothetical PHP web application.

Instructions:

1.  Based on the best practices learned in class, draft a security policy document that outlines:

o    User authentication and authorization measures.

o    Data protection strategies, including encryption.

o    Input validation and output sanitization practices.

o    Incident response and reporting mechanisms.

2.  Discuss how this policy would guide developers in maintaining security throughout the development lifecycle.

Deliverables: A comprehensive security policy document.


Assignment 6: Security Testing

Objective: Perform security testing on a PHP application.

Instructions:

1.  Choose a PHP application (either your own or an open-source project).

2.  Conduct a security audit using tools like:

o    OWASP ZAP (Zed Attack Proxy)

o    Burp Suite (Community Edition)

o    Any other relevant security testing tools.

3.  Identify vulnerabilities and document your findings.

Deliverables: A report detailing the findings from the security audit, including recommendations for remediation.


These assignments will not only help students understand PHP security practices but also provide practical experience in applying these concepts in real-world scenarios.

Assignment 1: Identify Vulnerabilities

Sample PHP Script:

php

Copy code

<?php

// Vulnerable script

$conn = mysqli_connect("localhost", "username", "password", "database");

$email = $_GET['email'];

$sql = "SELECT * FROM users WHERE email = '$email'";

$result = mysqli_query($conn, $sql);

while ($row = mysqli_fetch_assoc($result)) {

    echo "Hello, " . $row['name'] . "<br>";

}

?>

Identified Vulnerabilities:

1.  SQL Injection:

o    Explanation: The email parameter is directly embedded in the SQL query, allowing an attacker to manipulate the SQL statement.

o    Recommendation: Use prepared statements to prevent SQL Injection.

2.  XSS (Cross-Site Scripting):

o    Explanation: If the user's name is displayed without proper escaping, an attacker could inject JavaScript.

o    Recommendation: Use htmlspecialchars() to escape output.

3.  Potential CSRF (Cross-Site Request Forgery):

o    Explanation: If this script is part of a form submission, an attacker could forge requests.

o    Recommendation: Implement CSRF tokens in forms.


Assignment 2: Secure Coding Practices

Secure Coding Implementation:

php

Copy code

<?php

session_start();

$conn = new mysqli("localhost", "username", "password", "database");

 

// Prepared Statement for user login

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

    if ($email === false) {

        die("Invalid email format.");

    }

 

    $stmt = $conn->prepare("SELECT * FROM users WHERE email = ?");

    $stmt->bind_param("s", $email);

    $stmt->execute();

    $result = $stmt->get_result();

    $user = $result->fetch_assoc();

 

    if ($user) {

        echo "Hello, " . htmlspecialchars($user['name'], ENT_QUOTES, 'UTF-8');

    } else {

        echo "User not found.";

    }

}

 

// CSRF token generation

if (empty($_SESSION['csrf_token'])) {

    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));

}

?>

 

<form method="POST" action="">

    <input type="email" name="email" required>

    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">

    <button type="submit">Login</button>

</form>

Summary of Security Measures:

  • Prepared statements are used to prevent SQL Injection.
  • Input validation with filter_var() ensures email format.
  • Output is sanitized using htmlspecialchars() to prevent XSS.
  • CSRF token is included to protect against CSRF attacks.

Assignment 3: Error Handling and Logging

Modified PHP Application Code:

php

Copy code

<?php

session_start();

$conn = new mysqli("localhost", "username", "password", "database");

 

// Custom error handling

set_error_handler(function($errno, $errstr) {

    error_log("Error [$errno]: $errstr");

    // Display a generic error message to users

    echo "Something went wrong. Please try again later.";

});

 

// Sample code for login

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

    if ($email === false) {

        die("Invalid email format.");

    }

 

    $stmt = $conn->prepare("SELECT * FROM users WHERE email = ?");

    $stmt->bind_param("s", $email);

    if (!$stmt->execute()) {

        trigger_error("Database query failed: " . $stmt->error);

    }

    $result = $stmt->get_result();

    $user = $result->fetch_assoc();

   

    if ($user) {

        echo "Hello, " . htmlspecialchars($user['name'], ENT_QUOTES, 'UTF-8');

    } else {

        echo "User not found.";

    }

}

 

// Error logging to a file

ini_set('log_errors', 'On');

ini_set('error_log', '/path/to/php-error.log');

?>

Summary of Changes:

  • Custom error handler logs errors to a file without displaying details to users.
  • Generic error messages are shown to users to avoid revealing sensitive information.

Assignment 4: Secure File Upload

Secure File Upload Script:

php

Copy code

<?php

session_start();

$allowedTypes = ['image/jpeg', 'image/png'];

 

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {

    $fileType = $_FILES['file']['type'];

    $fileSize = $_FILES['file']['size'];

   

    // Validate file type and size

    if (!in_array($fileType, $allowedTypes) || $fileSize > 2000000) { // 2MB limit

        die("Invalid file type or size exceeded.");

    }

 

    // Sanitize the file name

    $fileName = basename($_FILES['file']['name']);

    $fileName = preg_replace("/[^a-zA-Z0-9.]/", "_", $fileName); // Allow only safe characters

 

    // Move the uploaded file

    if (move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $fileName)) {

        echo "File uploaded successfully.";

    } else {

        echo "File upload failed.";

    }

}

?>

 

<form method="POST" enctype="multipart/form-data">

    <input type="file" name="file" required>

    <button type="submit">Upload</button>

</form>

Summary of Security Measures:

  • Validates file type and size before upload.
  • Sanitizes the file name to prevent path traversal.
  • The uploaded files should be stored outside the web root directory or with limited permissions.

Assignment 5: Security Policy Document

Sample Security Policy Document Outline:

1. Introduction

  • Purpose and scope of the security policy.

2. User Authentication and Authorization

  • Require strong passwords and regular changes.
  • Implement multi-factor authentication.

3. Data Protection Strategies

  • Encrypt sensitive data at rest and in transit.
  • Regularly back up data and ensure secure storage.

4. Input Validation and Output Sanitization

  • Validate all inputs using appropriate filters.
  • Escape output to prevent XSS.

5. Incident Response and Reporting

  • Define processes for detecting and responding to security incidents.
  • Outline the roles and responsibilities during an incident.

6. Regular Security Audits

  • Schedule regular security reviews and updates to the policy.

Assignment 6: Security Testing

Security Testing Steps:

1.  Tool Selection: Choose OWASP ZAP for testing.

2.  Configure the Tool:

o    Set up ZAP to scan the PHP application.

3.  Performing the Scan:

o    Run an active scan on the application URL to identify vulnerabilities.

4.  Review Results:

o    Document any found vulnerabilities (e.g., XSS, SQL Injection).

5.  Recommendations:

o    Provide remediation steps for each identified vulnerability (e.g., implementing input validation, using prepared statements).

Deliverables:

  • A detailed report of vulnerabilities found, including screenshots, descriptions, and remediation recommendations.

These solutions guide students through practical implementations of secure coding practices and provide a solid understanding of PHP security measures. They should be encouraged to experiment further and delve deeper into security topics as part of their learning process.


Post a Comment

0Comments

Post a Comment (0)