如何修復會話固定漏洞
PHP中的安全性 (Security in PHP)
When writing PHP code it is very important to keep the following security vulnerabilities in mind to avoid writing insecure code.
在編寫PHP代碼時,記住以下安全漏洞非常重要,以避免編寫不安全的代碼。
漏洞類型 (Types Of Vulnerabilities)
These are the common vulnerabilities you'll encounter when writing PHP code. We'll discuss a few in further depth below.
這些是編寫PHP代碼時會遇到的常見漏洞。 我們將在下面進一步深入討論。
Cross Site Request Forgery A vulnerability in the application caused by the programmer not checking where a request was sent from - this attack is sent to a high privilege level user to gain higher level access to the application.
跨站點請求偽造程序員未檢查發送請求的位置而在應用程序中引起的漏洞-該攻擊被發送給高特權級別的用戶,以獲得對應用程序的更高級別的訪問權限。
Cross Site Scripting A vulnerability in the application caused by the programmer not sanitizing input before outputting the input to the browser (for example a comment on a blog). It is commonly used to run malicious javascript in the browser to do attacks such as stealing session cookies among other malicious actions to gain higher level privileges in the application.
跨站點腳本(cross site Scripting)應用程序中的一個漏洞,是由程序員在將輸入輸出到瀏覽器之前未對輸入進行消毒(例如,對博客的評論)。 它通常用于在瀏覽器中運行惡意javascript進行攻擊,例如在其他惡意操作中竊取會話cookie,以在應用程序中獲得更高級別的特權。
Local File Inclusion A vulnerability in the application caused by the programmer requiring a file input provided by the user and not sanitizing the input before accessing the requested file. This results in a file being included where it should not of been.
包含本地文件由程序員要求用戶提供文件輸入并且在訪問請求的文件之前不清除輸入內容導致的應用程序中的漏洞。 這將導致文件不應包含在其中。
Remote File Inclusion A vulnerability in the application caused by the programmer requiring a file input provided by the user and not sanitizing the input before accessing the requested file. This results in a file being pulled from a remote server and included where it should not of been.
遠程文件包含由程序員引起的應用程序中的此漏洞,要求程序員提供用戶提供的文件輸入,并且在訪問請求的文件之前不清除輸入。 這將導致文件從遠程服務器中拉出,并包含在不應包含的位置。
Session Hijacking A vulnerability caused by an attacker gaining access to a user’s session identifier and being able to use another user’s account impersonating them. This is often used to gain access to an administrative user’s account.
會話劫持(Session Hijacking)由攻擊者獲得對用戶會話標識符的訪問權,并能夠使用其他用戶的帳戶來模擬它們的漏洞。 這通常用于獲得對管理用戶帳戶的訪問權限。
Session Identifier Acquirement Session Identifier Acquirement is a vulnerability caused by an attacker being able to either guess the session identifier of a user or exploit vulnerabilities in the application itself or the user’s browser to obtain a session identifier.
會話標識符獲取會話標識符獲取是由攻擊者能夠猜測用戶的會話標識符或利用應用程序本身或用戶的瀏覽器中的漏洞獲取會話標識符所引起的漏洞。
SQL Injection A vulnerability in the application caused by the programmer not sanitizing input before including it into a query into the database. This leads to the attacker having full read and more often than not write access to the database. With this type of access an attacker can do very bad things.
SQL注入SQL注入是應用程序中的一個漏洞,由程序員在將輸入包含到數據庫中的查詢之前未對輸入進行清理。 這導致攻擊者具有對數據庫的完全讀取權限,并且經常具有對數據庫的不寫入權限。 通過這種訪問方式,攻擊者可以做非常壞的事情。
Now let's look at some common vulnerabilities in more detail.
現在,讓我們更詳細地研究一些常見漏洞。
會話劫持 (Session Hijacking)
Session Hijacking is a vulnerability caused by an attacker gaining access to a user’s session identifier and being able to use another user’s account impersonating them. This is often used to gain access to an administrative user’s account.
會話劫持是由攻擊者獲得對用戶會話標識符的訪問權,并能夠使用其他用戶的帳戶來模擬它們的漏洞。 這通常用于獲得對管理用戶帳戶的訪問權限。
防御PHP中的會話劫持攻擊 (Defending against Session Hijacking attacks in PHP)
To defend against Session Hijacking attacks you need to check the current user’s browser and location information against information stored about the session. Below is an example implementation that can help mitigate the effects of a session hijacking attack. It checks the IP Address, User Agent, and if the Session Expired removing a session before it’s resumed.
為了防御會話劫持攻擊,您需要根據存儲的有關會話的信息檢查當前用戶的瀏覽器和位置信息。 下面是一個示例實現,可以幫助減輕會話劫持攻擊的影響。 它會檢查IP地址,用戶代理以及會話是否過期,然后再恢復會話。
<?php
session_start();// Does IP Address match?
if ($_SERVER['REMOTE_ADDR'] != $_SESSION['ipaddress'])
{
session_unset();
session_destroy();
}// Does user agent match?
if ($_SERVER['HTTP_USER_AGENT'] != $_SESSION['useragent'])
{session_unset();session_destroy();
}// Is the last access over an hour ago?
if (time() > ($_SESSION['lastaccess'] + 3600))
{session_unset();session_destroy();
}
else
{$_SESSION['lastaccess'] = time();
}
跨站腳本 (Cross Site Scripting)
Cross Site Scripting is a type of vulnerability in a web application caused by the programmer not sanitizing input before outputting the input to the web browser (for example a comment on a blog). It is commonly used to run malicious javascript in the web browser to do attacks such as stealing session cookies among other malicious actions to gain higher level privileges in the web application.
跨站點腳本是Web應用程序中的一種漏洞,它是由程序員在將輸入輸出到Web瀏覽器(例如,對博客的評論)之前未清理輸入而引起的。 它通常用于在Web瀏覽器中運行惡意javascript進行攻擊,例如在其他惡意操作中竊取會話cookie,以在Web應用程序中獲得更高級別的特權。
跨站點腳本攻擊示例 (Example Cross Site Scripting Attack)
A blog allows users to style their comments with HTML tags, however the script powering the blog does not strip out <script>
tags allowing any user to run javascript on the page. An attacker can use this to their advantage to run malicious javascript in the browser. They could infect users with malware, steal session cookies, and more.
博客允許用戶使用HTML標記來設置其注釋樣式,但是為博客提供動力的腳本不會刪除<script>
標記,允許任何用戶在頁面上運行javascript。 攻擊者可以利用此漏洞來在瀏覽器中運行惡意javascript。 他們可能用惡意軟件感染用戶,竊取會話Cookie等。
<script>alert('Cross Site Scripting!');
</script>
防御PHP中的跨站點腳本攻擊的網站 (Defending your website from cross site scripting attacks in PHP)
In PHP there are two primary functions, htmlspecialchars()
and strip_tags()
, built in to protect yourself from cross site scripting attacks.
在PHP中,內置了兩個主要函數htmlspecialchars()
和strip_tags()
,以保護自己免受跨站點腳本攻擊。
The htmlspecialchars($string)
function will prevent an HTML string from rendering as HTML and display it as plain text to the web browser. htmlspecialchars() code example
htmlspecialchars($string)
函數將阻止HTML字符串呈現為HTML,并將其顯示為純文本格式到Web瀏覽器。 htmlspecialchars()代碼示例
<?php
$usercomment = "<string>alert('Cross Site Scripting!');</script>";
echo htmlspecialchars($usercomment);
The other approach is the strip_tags($string, $allowedtags)
function which removes all HTML tags except for the HTML tags that you’ve whitelisted. It’s important to note that with the strip_tags()
function you have to be more careful, this function does not prevent the user from including javascript as a link, you’ll have to sanitize that on our own.
另一種方法是strip_tags($string, $allowedtags)
函數,該函數將刪除所有HTML標記(已列入白名單HTML標記)。 需要特別注意的是,使用strip_tags()
函數時,您必須格外小心,該函數不會阻止用戶將javascript作為鏈接包含進來,您必須自己對其進行清理。
strip_tags() code example
strip_tags()代碼示例
<?php
$usercomment = "<string>alert('Cross Site Scripting!');</script>";
$allowedtags = "<p><a><h1><h2><h3>";
echo strip_tags($usercomment, $allowedtags);
Setting the X-XSS-Protection Header:
設置X-XSS-Protection標頭:
In PHP you can send the X-XSS-Protection
Header which will tell browsers to check for a reflected Cross Site Scripting attack and block the page from loading. This does not prevent all cross site scripting attacks only reflected ones and should be used in combination with other methods.
在PHP中,您可以發送X-XSS-Protection
標頭,該標頭將告訴瀏覽器檢查是否反映了跨站點腳本攻擊,并阻止頁面加載。 這不能防止所有跨站點腳本攻擊僅反映出來,而應與其他方法結合使用。
<?php
header("X-XSS-Protection: 1; mode=block");
Writing your own sanitization function Another option, if you would like more control over how the sanitization works, is to write your own HTML Sanitization function, this is not recommended for PHP Beginners as a mistake would make your website vulnerable.
編寫自己的清理功能如果要對清理的工作方式進行更多控制,另一種選擇是編寫自己HTML清理功能,PHP初學者不建議這樣做,因為這樣會使您的網站容易受到攻擊。
使用內容安全策略保護您的網站免受跨站點腳本攻擊 (Defending your website from cross site scripting attacks with a Content Security Policy)
An effective approach to preventing cross site scripting attacks, which may require a lot of adjustments to your web application’s design and code base, is to use a content security policy.
防止跨站點腳本攻擊的一種有效方法是使用內容安全策略,這種攻擊可能需要對Web應用程序的設計和代碼庫進行大量調整。
將內容安全策略設置為HTTP標頭 (Set a Content Security Policy as an HTTP Header)
The most common way of setting a Content Security Policy is by setting it directly in the HTTP Header. This can be done by the web server by editing it’s configuration or by sending it through PHP.
設置內容安全策略的最常見方法是直接在HTTP標頭中進行設置。 這可以由Web服務器通過編輯其配置或通過PHP發送來完成。
Example of a Content Security Policy set in a HTTP Header
HTTP標頭中設置的內容安全策略的示例
<?php
header("content-security-policy: default-src 'self'; img-src https://*; child-src 'none';");
將內容安全策略設置為元標記 (Set a Content Security Policy as a Meta tags)
You can include your Content Security Policy in the page’s HTML and set on a page by page basis. This method requires you to set on every page or you lose the benefit of the policy.
您可以將內容安全策略包含在頁面HTML中,并逐頁進行設置。 此方法要求您在每個頁面上進行設置,否則您將失去使用該策略的好處。
Example of a Content Security Policy set in a HTML Meta Tag
在HTML元標記中設置的內容安全策略的示例
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src https://*; child-s
SQL注入 (SQL Injection)
SQL injection is a vulnerability in the application caused by the programmer not sanitizing input before including it into a query into the database. This leads to the attacker having full read and more often than not write access to the database. With this type of access an attacker can do very bad things.
SQL注入是應用程序中的一個漏洞,它是由程序員在將輸入包含到數據庫中的查詢之前沒有對輸入進行清理而引起的。 這導致攻擊者具有對數據庫的完全讀取權限,并且經常具有對數據庫的不寫入權限。 通過這種訪問方式,攻擊者可以做非常壞的事情。
示例SQL注入攻擊 (Example SQL Injection attack)
The below PHP Script runs an SQL Statement to get a user’s email by ID. However the input is not sanitized making it vulnerable to SQL Injection
下面PHP腳本運行一個SQL語句,以按ID獲取用戶的電子郵件。 但是,輸入沒有經過清理,因此容易受到SQL注入的攻擊
<?php
$input = $_GET['id'];
$dbserver = "localhost";
$dbuser = "camper";
$dbpass = "supersecretcampsitepassword";
$dbname = "freecodecamp";$conn = new mysqli($dbserver, $dbuser, $dbpass, $dbname);if ($conn->connect_error) {die("Connection failed: " . $conn->connect_error);
}$sql = "SELECT email FROM users WHERE id =" . $input;$result = $conn->query($sql);if ($result->num_rows > 0) {while($row = $result->fetch_assoc()) {echo $row["email"];}
} else {echo "no results";
}$conn->close();
SELECT email FROM users WHERE id = `$input`;
So with the above the input is not type casted (I.e. casting the input with (int) so only a number is allowed) nor escaped allowing someone to perform an SQL Injection attack - for example the URL getemailbyuserid.php?id=1'; My Query Here-- -
would allow you to run arbitrary SQL queries with little effort.
因此,使用上面的方法,不會對輸入進行類型轉換(即,使用(int)轉換輸入,因此只允許輸入數字),也無法進行轉義以允許某人執行SQL注入攻擊-例如URL getemailbyuserid.php?id=1'; My Query Here-- -
getemailbyuserid.php?id=1'; My Query Here-- -
允許您getemailbyuserid.php?id=1'; My Query Here-- -
運行任意SQL查詢。
保護您的網站免受PHP中SQL注入攻擊 (Defending your website from sql injection attacks in PHP)
There are a few approaches to defend your website from SQL Injection Attacks. These approaches are Whitelisting, Type Casting, and Character Escaping
有幾種方法可以保護您的網站免受SQL Injection Attacks的攻擊。 這些方法是白名單,類型轉換和字符轉義
Whitelisting: The whitelisting approach is used in cases where only a few inputs are expected. You can list each expected input in a PHP Switch and then have a default for invalid input. You do not have to worry about a type casting issue or a character escape bypass but the allowed input is extreamly limited. It remains an option, see the example below.
白名單:白名單方法用于只需要少量輸入的情況。 您可以在PHP Switch中列出每個期望的輸入,然后為無效輸入提供默認值。 您不必擔心類型轉換問題或字符轉義旁路,但是允許的輸入受到極大限制。 它仍然是一個選項,請參見下面的示例。
<?php
switch ($input) {case "1"://db query 1break;case "2"://db query 2break;default:// invalid input return error
}
Type Casting: The type casting approach is commonly used for an application using numeric input. Simply cast the input with (int) $input
and only a numeric value will be allowed.
類型轉換:類型轉換方法通常用于使用數字輸入的應用程序。 只需使用(int) $input
,將只允許使用數字值。
Character Escaping: The character escaping approach will escape characters such as quotes and slashes provided by the user to prevent an attack. If you are using MySQL Server and the MySQLi library to access your database, the mysqli_real_escape_string($conn, $string)
function will take two arguments, the MySQLi connection, and the string and will properly escape the user’s input to block an sql injection attack. The exact function you use depends on the database type and php library you are using check the php library’s documentation for more information on escaping user input.
字符轉義:字符轉義方法將轉義用戶提供的引號和斜杠等字符,以防止攻擊。 如果使用MySQL Server和MySQLi庫訪問數據庫,則mysqli_real_escape_string($conn, $string)
函數將使用兩個參數,即MySQLi連接和字符串,并將正確轉義用戶的輸入以阻止sql注入攻擊。 您使用的確切功能取決于您使用的數據庫類型和php庫,請查閱php庫的文檔以獲取有關轉義用戶輸入的更多信息。
有關PHP的更多信息: (More on PHP:)
PHP best practices
PHP最佳做法
Best PHP code examples
最佳PHP代碼示例
How to prevent a slow loris attack on a PHP server
如何防止PHP服務器上的loris緩慢攻擊
How to set up a local debugging environment in PHP
如何在PHP中設置本地調試環境
翻譯自: https://www.freecodecamp.org/news/php-security-vulnerabilities/
如何修復會話固定漏洞