Secure Software Implementation and Coding PDF

Summary

This document appears to be lecture slides on secure software implementation, focusing on code injection and command injection vulnerabilities. It covers topics such as SQL injection, code injection examples in PHP, along with prevention techniques, and includes questions to assess understanding.

Full Transcript

Lecture 8 Secure Software Implementation/Coding Domain 4 Injection Flaws Official (ISC)2® Guide to the CSSLP® CBK® Second Edition Mohammed Alqmase Analysis Design Implementation Deployment Opera...

Lecture 8 Secure Software Implementation/Coding Domain 4 Injection Flaws Official (ISC)2® Guide to the CSSLP® CBK® Second Edition Mohammed Alqmase Analysis Design Implementation Deployment Operation Secure Code Security Requirements Threat Model Security Design Principles Outlines Common Software Vulnerabilities and Controls ❖ Buffer/Stack/Heap Overflow ❖ Injection Flaws ❖ Broken Authentication and Session Management ❖ Cross-Site Scripting (XSS) ❖ Non-persistent or Reflected XSS ❖ Persistent or Stored XSS ❖ DOM based XSS ❖ Cross-Site Request Forgery (CSRF) ❖ Insecure Direct Object References ❖ Security Misconfiguration ❖ File Attacks ❖ Side Channel Attacks Outlines Defensive Coding Practices - Concepts and Techniques: ❖ Input Validation ❖ Canonicalization ❖ Sanitization ❖ Error Handling ❖ Safe APIs ❖ Memory Management ❖ Exception Management ❖ Session Management ❖ Configuration Parameters Management ❖ Secure Startup ❖ Cryptography ❖ Concurrency ❖ Tokenization ❖ Sandboxing ❖ Anti-Tampering SQL Injection Questions Q1: What is the main issue with the following PHP code that handles a login form? $username = $_POST['username']; $password = $_POST['password']; $query="SELECT * FROM users WHERE username = '$username' AND password='$password'"; $result = mysqli_query($conn, $query); A. The code uses an outdated version of PHP. B. The code does not handle empty input fields. C. The code is vulnerable to SQL injection because it directly concatenates user inputs into the SQL query. D. The code does not connect to the database correctly. SQL Injection Questions Q2: Which of the following inputs could lead to a successful SQL injection attack against the vulnerable code below? $search = $_GET['search']; $query = "SELECT * FROM products WHERE name LIKE '%$search%'"; $result = mysqli_query($conn, $query); A. apple B. '; DROP TABLE products; # C. 100 OR 1=1 D. All of the above SQL Injection Questions Q3: What is wrong with the following PHP code, and how can it be mitigated? $id = $_GET['id']; $new_email = $_POST['email']; $query = "UPDATE users SET email = '$new_email' WHERE id = $id"; mysqli_query($conn, $query); A. The code is secure as it is. B. The code is vulnerable to SQL injection because it directly includes user inputs in the query. Use parameterized queries to fix it. C. The code will fail because of incorrect SQL syntax. D. The query should use double quotes instead of single quotes for variables. Code Injection Code Injection Definition Code Injection: The attacker injects code in the programming or scripting language used by the application (e.g., PHP, Python, JavaScript). Certain functions in PHP and other programming languages are commonly exploited in code injection attacks. Below are some PHP functions that are particularly vulnerable: 1. eval(): 2. include() / require() / include_once() / require_once(): 3. preg_replace() 4. assert() Code Injection Functions eval(): Evaluates a string as PHP code. Rarely needed; only in cases where dynamic code execution is necessary include() / require() / include_once() / require_once(): preg_replace() :Performs a regular expression search and replace, and with the /e modifier, it evaluates the replacement as PHP code. assert() :Evaluates a string as PHP code if the condition is false. Used to assert that certain conditions hold true, primarily for debugging. Code Injection How Does it work? Scenario: A PHP web application has a feature that allows users to execute custom code snippets as part of a coding challenge platform. However, it does not properly sanitize or validate user inputs before executing them with the eval() function. if ($_SERVER['REQUEST_METHOD'] === 'POST') { $code = $_POST['code']; eval($code); } echo 'This is a test'; phpinfo(); system('rm -rf C:\\important_folder'); system('rmdir /s /q C:\xampp\htdocs\config'); Run Code Injection How to Prevent it? 1. Avoid Using Dangerous Functions: eval(), assert(), and preg_replace() with the /e Code Injection How Does it work? $user_name = $_POST['name']; $user_feedback = $_POST['feedback']; Customer Feedback $email_template = "Feedback from {{name}}: {{feedback}}"; $email_body = preg_replace( [ John Doe "/{{name}}/e", "/{{feedback}}/e" ], Great service! [ $user_name, $user_feedback ], $email_template ); Send mail('[email protected]', 'New Feedback', $email_body); Feedback from John Doe: Great service! Code Injection How Does it work? $user_name = $_POST['name']; $user_feedback = $_POST['feedback']; Customer Feedback $email_template = "Feedback from {{name}}: {{feedback}}"; $email_body = preg_replace( "; system('rm -rf /var'); // [ "/{{name}}/e", "/{{feedback}}/e" ], Awesome! [ $user_name, $user_feedback ], $email_template ); Send mail('[email protected]', 'New Feedback', $email_body); Feedback from "; system('rm -rf /var/www/html'); //: Awesome! Code Injection How to Prevent it? 1. Use Safe Methods for Dynamic Content: 2. Avoid the /e Modifier in preg_replace() 3. Use preg_replace_callback() Instead Code Injection How to Prevent it? $user_name = htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8'); $user_feedback = htmlspecialchars($_POST['feedback'], ENT_QUOTES, 'UTF-8'); $email_template = "Feedback from {{name}}: {{feedback}}"; $email_body = preg_replace_callback( [ "/{{name}}/", "/{{feedback}}/" ], function ($matches) use ($user_name, $user_feedback) { if ($matches == '{{name}}') { return $user_name; } if ($matches == '{{feedback}}') { return $user_feedback; } }, $email_template ); mail('[email protected]', 'New Feedback Received', $email_body); Code Injection How Does it work? $plugin = $_GET['plugin']; $file_path = "plugins/". $plugin. ".php"; include($file_path); Malicious Input: URL: http://example.com/index.php?plugin=../../uploads/malicious_code Included File: plugins/../../uploads/malicious_code.php What Happens: 1. The attacker uses directory traversal (../../) to access a different directory. 2. This allows them to include a file that they uploaded to the server, such as malicious_code.php. 3. The malicious_code.php file could contain harmful PHP code, Code Injection How to Prevent it? 1. Use Whitelisting Over Blacklisting: 2. Sanitize and Validate Inputs $plugin = $_GET['plugin']; $allowed_plugins = ['contact_form', 'newsletter', 'gallery']; if (in_array($plugin, $allowed_plugins)) { $file_path = "plugins/". $plugin. ".php"; include($file_path); } else { echo "Invalid plugin specified."; } Code Injection Questions Q4: What is the primary reason to avoid using preg_replace('/e') in PHP? A. It has been deprecated and is no longer supported in recent PHP versions. B. It is slow and causes performance issues. C. It allows the evaluation of PHP code from user input, leading to code injection vulnerabilities. D. It does not support regular expressions. Code Injection Questions Q5: How can you prevent code injection when using the include() function with user inputs? $page = $_GET['page']; include($page); A. Validate that $page only includes safe characters and paths, and restrict it to known filenames. B. Sanitize $page using htmlspecialchars(). C. Use eval($page) instead of include($page). D. There is no way to prevent code injection with include(). Code Injection Questions Q6: Which of the following inputs could lead to a successful code injection attack against the vulnerable PHP code below? $command = $_GET['command']; eval($command); A. 1 + 1 == 2 B. echo 'Hello World'; C. phpinfo(); D. All of the above Command Injection Command Injection Definition Command Injection: The attacker executes arbitrary system commands on the host OS via the vulnerable application, often through functions that call system shell commands. Command Injection Functions In PHP, certain functions that execute system commands are vulnerable to command injection attacks if user inputs are not properly validated and sanitized. Some of these functions include: exec() system() shell_exec() passthru() popen() proc_open() backticks ()` Command Injection How Does it work? A log viewer application allows users to search through server logs using a PHP script that pipes commands to grep for filtering results. $searchTerm = $_GET['search']; echo shell_exec("grep '$searchTerm' /var/log/apache2/access.log"); Attack Vector: An attacker could use input like: search=access.log; cat /etc/passwd to view sensitive files on the server. Command Injection How Does it work? A company operates a web application that allows users to perform network diagnostics by network diagnostics pinging a specified IP address or domain name. The application is designed to help users troubleshoot network issues by providing an interface where they can enter an IP address or hostname to be pinged. However, due to improper handling of user input, the application 8.8.8.8 is vulnerable to command injection attacks. $host = $_POST['host']; ping $command = "ping ". $host; $output = shell_exec($command); echo "$output"; Command Injection How Does it work? A company operates a web application that allows users to perform network diagnostics by network diagnostics pinging a specified IP address or domain name. The application is designed to help users troubleshoot network issues by providing an interface where they can enter an IP address or hostname to be pinged. However, due to 8.8.8.8; rm -rf /var improper handling of user input, the application is vulnerable to command injection attacks. $host = $_POST['host']; ping $command = "ping ". $host; $output = shell_exec($command); echo "$output"; Command Injection How to Prevent it? $host = $_POST['host']; $command = "ping ". $host; $output = shell_exec($command); echo "$output"; $host = $_POST['host']; if (!filter_var($host, FILTER_VALIDATE_IP)) { if(!preg_match('/^[a-zA-Z0-9.-]+$/', $host)){ die('Invalid IP address or hostname.'); } } $command = "ping ". escapeshellarg($host); $output = shell_exec($command); echo "". htmlspecialchars($output). ""; Command Injection How to Prevent it? 1. Always Validate and Sanitize Inputs: Use functions like escapeshellarg() and escapeshellcmd() to sanitize input parameters. 2. Avoid Using User Input Directly: Do not pass raw user input into commands without proper checks. 3. Use Safer Alternatives: For some tasks, there might be PHP functions that avoid shell execution altogether (e.g., file operations). 4. Minimize Privileges: Run commands with the least privilege required to reduce the impact of potential exploitation. Command Injection How to Prevent it? 1. Use PHP Built-in Functions: Whenever possible, use PHP's built-in functions instead of shell commands. Examples: Use scandir() or glob() for directory listing instead of ls. Use unlink() for file deletion instead of rm. Use copy(), rename(), and move_uploaded_file() for file operations instead of cp or mv. Use PHP functions like file_put_contents(), file_get_contents(), and fopen() for reading and writing files instead of shell commands like cat or echo. Use the GD library or Imagick for resizing, cropping, and other image manipulations instead of using system("convert $source -resize 100x100 $dest") without input validation. Use PHP functions like fsockopen(), stream_socket_client(), or cURL for network connections instead of Using system("ping $host") to check server connectivity. Command Injection Questions Q7: Which of the following inputs would be dangerous if passed to the following PHP code? $filename = $_GET['filename']; shell_exec("rm ". $filename); A. file.txt B. important_data.txt C. ; rm -rf / D. All of the above Command Injection Questions Q8: What is the primary risk associated with the following PHP code? $userInput = $_GET['file']; system("cat ". $userInput); A. The code will only display the contents of text files. B. The code is vulnerable to command injection because user input is directly appended to a shell command. C. The code is secure as long as the input is not empty. D. The code is efficient and performs as expected. Command Injection Questions Q9: Which PHP function is MOST susceptible to command injection attacks? A. file_get_contents() B. exec() C. str_replace() D. json_encode() Command Injection Questions Q10: What can be a dangerous consequence of using the exec() function in PHP without proper input validation? $userCommand = $_GET['cmd']; exec($userCommand); A. The code may execute slower than expected. B. The code could cause syntax errors in PHP. C. The code could execute arbitrary system commands, allowing an attacker to control the server. D. The code will only run commands that are predefined. Command Injection Questions Q11: How can you mitigate command injection vulnerabilities when using functions like system(), exec(), or shell_exec() in PHP? A. Use htmlspecialchars() to sanitize input. B. Restrict input to a whitelist of allowed commands and use escapeshellarg() or escapeshellcmd(). C. Use eval() to execute the commands. D. Allow all inputs as long as they are not empty. Cross-Site Scripting (XSS)

Use Quizgecko on...
Browser
Browser