PHP Security Programming

Source: Internet
Author: User
Tags phpinfo sql injection attack

1. Order Injection (Command injection)The following 5 functions can be used in PHP to execute external applications or functionssystem, Exec, PassThru, Shell_exec, "(single apostrophe, same as shell_exec function, such as <? $results = ' wc-w *.txt '; Echo $results;? >)Example:<?php//ex1.php$dir = $_get["dir"];if (isset ($dir)) { System ("Ls-al". $dir);}?>Submit http://www.sectop.com/ex1.php?dir=| cat/etc/passwdafter submission, the command becomes system ("Ls-al | CAT/ETC/PASSWD ");2. Eval Injection (eval injection)$var = "var";if (isset ($_get["Arg"])) {$arg = $_get["arg"];eval ("\ $var = $arg;");echo "\ $var =". $var;}Http://www.test.com/index.php?arg=phpinfo ()Dynamic functions:<?phpfunc A () {dosomething ();} func B () {dosomething ();} if (Isset ($_get["func"])) {$myfunc = $_get["func"];echo $myfunc ();} ?>Http://www.test.com/index.php?func=phpinfoPrecautionary approach:1. Try not to execute external commands 2. Use custom functions or libraries to replace the functions of external commands3. Use the Escapeshellarg function to handle command parameters4. Use Safe_mode_exec_dir to specify the path to the executable fileThe esacpeshellarg function will escape any character that causes the argument or command to end, single quote "'", replace with "\", double quote "" ", replace with" \ "", semicolon ";" Replace with "\;"using Safe_mode_exec_dir to specify the path to the executable file, you can put the command that will be used in this pathSafe_mode = onSafe_mode_exec_dir =/usr/local/php/bin/3. Client-side scripting Attack (script insertion)attack steps for client script implantationA, the attacker registered a normal user after landing siteB, open the Message page, insert the attack JS code, such as inserting <script>while (1) {Windows.open ();} </script> Unlimited bullet box, insert <script>location.href= "http://www.sectop.com";</script> Jump Fishing pageC, other user login website (including administrator), browse the content of this messageD, hidden in the message content of the JS code is executed, the attack succeededSolution: Htmlspecialchars (NL2BR ($row [' question '), ent_quotes); Escape special characters
4. Cross-site scripting attacks (Scripting, XSS)Cross-site scripting is primarily used by attackers to read Web site users ' cookies or other personal data, and once an attacker obtains such data, he can impersonate the user to log on to the site and gain access to the user. General steps:A, the attacker sends an HTTP link to the target user in a way that is XSSB. The target user logs on to this website and opens an XSS link sent by the attacker during the loginC, the website executes this XSS attack scriptd, the target user page jumps to the attacker's website, the attacker obtains the target user's informationE. The attacker uses information from the target user to log on to the website to complete the attack5. SQL injection attack (SQL injection)6. Cross-site request forgery attack (forgeries, CSRF)A, check the source of the Web page$_server[the domain name in "http_referer"] is consistent in $_server["SERVER_NAME"]B, check the built-in hidden variableswhen a page is accessed, a random number is generated on the server side and placed in the hidden field of the form, and the value is also stored in the server session, validating that the submitted random number and the session are consistent in the submission form, and inconsistent with the source forgery. C, use post, do not use get7. Session hijacking (sessions hijacking)Obtain the user's session_id through XSS or other means, and then use the following link to impersonate the identity of a legitimate userhttp://www.test.com/session.php?PHPSESSID=dce417abdb9a004673c125ccf69dcb8b
8, Session fixed attack (session fixation)Precautionary approachA. Change session ID periodicallyfunction bool session_regenerate_id ([bool delete_old_session])at the beginning of index.php, addsession_start ();session_regenerate_id (TRUE);...This will result in a new session ID every time you reloadB. Changing the name of the sessionthe default name of the session is PHPSESSID, which will be stored in the cookie, if the hacker does not grab packet analysis, it can not guess the name, blocking the partial attacksession_start ();session_name ("Mysessionid");...c. Turn off transparent session IDtransparent session ID refers to the Sessioin ID used to pass a link when the HTTP request in the browser does not use cookies to create the session ID; open php.ini, editsession.use_trans_sid = 0in your codeint_set ("Session.use_trans_sid", 0);session_start ();...D. Check session ID from cookie onlysession.use_cookies = 1 means using cookies to store session IDsession.use_only_cookies = 1 means that only cookies are used to store session IDs, which avoids fixed session attacksin the code:int_set ("Session.use_cookies", 1);int_set ("Session.use_only_cookies", 1); P>E. Passing hidden parameters using URLssession_start ();$seid = MD5 (Uniqid (rand ()), TRUE));$_session["Seid"] = $seid;Although the attacker can obtain session data, but can not know the value of the $seid, as long as the Seid value is checked with the Seid in the session, it is possible to confirm whether the current page is the Web program itself called. 9. HTTP response Split attack (HTTP Response splitting)$fp = Fsockopen (www.00aq.com, 80); Open the Internet socket connection <?phpfputs ($fp, "get/http/1.1\r\n");//write HTTP request headerfputs ($fp, "host:www.00aq.com\r\n\r\n");$http _response = ""; The string for the HTTP responseWhile (!feof ($fp)) {$http _response. = Fgets ($fp,);//Read the 256-bit HTTP response string} fclose ($FP);//Close Internet socket connectionEcho nl2br (htmlentities ($http _response));//Display HTTP response information?> HTTP response splitting is due to an attacker's well-designed use of e-mail or links to allow the target user to generate two responses with one request, the previous response being the server's response, and the second being the attacker's designed response. This attack occurs because the Web program places the consumer's data in the HTTP response header, and the data of those users is a well-crafted function of the attacker who might suffer a split of the HTTP request response, including the following:header (); Setcookie (); session_id (); Setrawcookie ();The HTTP response split typically occurs in:Location Header: Writes the consumer's data to the redirected URL addressSet-cookie Header: Write user data to cookiesHeader ("Location:".)     $_get[' page ']); Precautionary approach: A. Replace the CRLF newline character header ("Location:".      STRTR ($_get[' page '), array ("\ r" = "", "\ n" = "="))) B. In the latest version of PHP PHP with the latest versions, no newline characters are allowed in the HTTP header to hide the HTTP response header Apache in httpd.conf, option Servertokens = Prod, serversignature = off in php php.ini, option expose_php = Off10 Files Upload Vulnerability (file Upload Attack)array{[File] = array{[Name] = test.txt//File name[Type] = Text/plain//mime type[Tmp_name] =/tmp/php5d.tmp//Temp file[ERROR] = 0//error message[Size] = 536//File size, per byte }  } The $_files[' file ' [' ERROR '] variable is used to save the error message when uploading the file, and its value is as follows:error message numeric description UPLOAD_ERR_OK0 No errors upload_err_ini_size1 The size of the uploaded file exceeds the php.ini setting upload_err_from_size2 The size of the uploaded file exceeds the max_file_size value in the HTML form upload_err_partial3 upload only part of the file upload_err_no_file4 no file upload Guard against: Detect file types, naming rules, etc.11. Directory Traversal Vulnerability (directory traversal)12. Remote file contains attack (inclusion)13. Dynamic function Injection Attack (Variable Evaluation)14. URL attack (URL attack) 15. Form Submission Spoofing attack (spoofed form submissions)16. HTTP request Spoofing Attack (spoofed HTTP requests)
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.