Introduction of PHP safe problem: 10 common and safe problems + example explains

Opposite at other for a few kinds of languages, PHP builds station respect to have larger dominant position in Web, even if novice, also can build a website very easily to come out. But this kind of advantage brings a few negative effects easily also, because very much PHP tutorial is done not have,involve the knowledge of safe respect.

Introduction of PHP safe problem: 10 common and safe problems + example explains

This card cent is a few parts, every branch is covered different safety browbeats and answer strategy. But, this is not after saying when you accomplish this, the website that can avoid you certainly appears any problems. If you want to enhance your website security, you should continue to read a book through reading or article, will consider how to enhance your website security

Stem from demonstrate need, code may not be very perfect. In developing a process daily, a lot of code are included was in frame follows all sorts of libraries inside. Regard a tiring-room as development, you want skilled and basic CURD not only, should know how to protect your data more.

1.SQL infuse

I bet a packet hot, you can see here for certain. SQL infuse is one of the biggest to your website menace, if your database gets the word of the attack of the SQL infuse of others, people can turn the database that gives you, still perhaps can produce more serious consequence.

The website should get dynamic data from inside the database, must carry out SQL statement, citing is as follows:

< ? Php $username = $_GET['username']; $query = "SELECT * FROM Users WHERE Username = '$username'";

The inquiry that aggressor control sends through GET and POST (or for example a few other inquiry of UA) . Usually, you hope inquiry door name is " Peter " the SQL statement that the user produces is as follows:

SELECT * FROM Users WHERE Username = 'peter'

But, aggressor sent specific user name parameter, for example: ' OR '1'='1

This can bring about SQL statement to become such:

SELECT * FROM Users WHERE Username = 'peter' OR '1' = '1'

Such, the data that he can derive below the situation that does not need a password your whole user is expressed.

So, how do we prevent the happening of this kind of accident? The means of settlement of the mainstream has two kinds. The data that transferred meaning user inputs perhaps uses the statement that has enclosed. The method of transferred meaning is to had enclosed a function, undertake filtering with the data that will be referred to the user, the label with harmful take out. But, I not quite recommend use this method, because forget more easily,do here to manage in every place.

Below, I will introduce how to use PDO to carry out the statement that has enclosed (Mysqi is same also) :

$username = $_GET['username']; $query = $pdo->prepare('SELECT * FROM Users WHERE Username = :uSername'); $query->execute(['username' =>$username]); $data = $query->fetch();

Every part of dynamic data with: Do prefix. Regard array as to transfer executive function all parameter next, it is your transferred meaning like PDO it seems that harmful data is same.

Almost all database driver support the statement that has enclosed, do not use them without reason! Nurturance uses their convention, won't forget later.

The literary works of safe problem is handled when you also can consult Phpdelusions builds SQL one piece medium to inquire about dynamic compose. Link: Https://phpdelusions.net/pdo/ . . . .

2.XSS

XSS calls CSS (Cross Site Script) again, step station script attack. What it points to is baleful aggressor baleful Html code is inserted in past Web page, browse this page when the user when, built-in among them the Html code inside Web can be carried out, achieve ill will to atttack the special aim of the user thereby.

With search page is example below:

<body>< ? Php $searchQuery = $_GET['q']; /* Some Search Magic Here */ ? ><h1>You Searched For: < ? Php Echo $searchQuery; ? > </h1><p>We Found: Absolutely Nothing Because This Is A Demo</p></body>

Because we print the content of the user directly,come out, do not pass any filtering, illegal user is OK joining together URL:

Search.php? Q=%3Cscript%3Ealert(1)%3B%3C%2Fscript%3E

The content that PHP apply colours to a drawing comes out is as follows, can see Javascript code can be carried out directly:

<body><h1>You Searched For: <script>alert(1);</script></h1><p>We Found: Absolutely Nothing Because This Is A Demo</p></body>

Ask: What is JS code carried out to have alarming?

Javascript is OK:

Spirit away the Cookie in your user browser; The remembers password function gets you site that passes a browser logs onto Zhang date and password; The confidential information of purloin user; The thing that your user can accomplish on the site, had JS attributive to carry out attributive to be able to be done, that is to say A user is OK imitate becomes any users; Built-in in your webpage baleful code; . . .

Ask: How be on guard this problem?

Good news is to compared advanced browser to had had the XSS of a few foundations to be on guard now function, do not depend on please nevertheless with this.

Right way is any inputs that do not believe an user stoutly, filter to input medium all and special character. The XSS that can eliminate the majority so atttacks:

< ? Php $searchQuery = Htmlentities($searchQuery, ENT_QUOTES);

Or you can use Twig of pattern plate engine, general pattern plate engine can acquiesce add Htmlentities to be on guard for output.

If you maintained the input content of the user, also want special attention when output, in the following example, we allow an user to fill in oneself rich guest link:

<body><a Href="< ? Php Echo $homepageUrl; ? > ">Visit Users Homepage</a></body>

Above code is likely the first do not come out to have a problem soon, but hypothesis user fills the following content:

#" Onclick="alert(1)

Can be by apply colours to a drawing:

<body><a Href="#" Onclick="alert(1)">Visit Users Homepage</a></body>

Do not believe the data that the user inputs forever forever, or, assume the content of the user has aggressiveness forever, the manner is decorous, handle the user input of good every time and output carefully next.

Plant additionally when Cookie, if need not JS reads extraction word, must install please for "HTTP ONLY" . This setting can make JavaScript cannot read the Cookie that takes PHP end to plant.

3.XSRF/CSRF

CSRF is the abbreviate that the request that cross a station forges, it is aggressor cheats an user to visit through measure of a few technologies once the website that attestation crosses runs a few operations.

Although be revealed here example is GET request, but just relatively understand more easily at POST, be not defend method, neither is the Cookies with close illicit much perhaps pace expresses sheet.

If you have a page that allows an user to delete account, following place show:

< ? Php //delete-account.php $confirm = $_GET['confirm']; If($confirm==='yes') {//goodbye}

Aggressor can build to spark in the compose on his site the table of this URL is simple (the table that applies to POST likewise is simple) , perhaps click URL to load for picture temptation user:

<img Src="https://example.com/delete-account.php? Confirm=yes" />

Once the user sparks, can implement the directive that deletes account, blink your account disappeared.

Such attack compares defence defence XSS and SQL infuse are a few more complex.

The most commonly used defence method is to generate your card of a CSRF to impose close safe string, call its Token commonly, store Token at Cookie or in Session.

Every time you are when webpage construction table is simple, make Token what the card puts in expressing sheet conceal a field, after sheet requests a server, the watch is met the Cookie according to the user or the Token in Session makes card comparing right, desired result just gives successfully through.

Because aggressor cannot know the content of Token your card (every Token that expresses sheet makes the card is random) , because this cannot pretend to be an user.

< ? Php /* are you built-in the page */ that expresses sheet? ><form Action="/delete-account.php" Method="post "><input Type="hidden" Name="csrf" Value="< ? Php Echo $_SESSION['csrf']; ? > "><input Type="hidden" Name="confirm" Value="yes" /><input Type="submit" Value="Delete My Account" /></form>## < ? Php //delete-account.php $confirm = $_POST['confirm']; $csrf = $_POST['csrf']; $knownGoodToken = $_SESSION['csrf']; If($csrf! ==$knownGoodToken) {Die('Invalid Request'); } If($confirm==='yes') {//goodbye}

Ask an attention, this is a very simple give typical examples, you can join more code. If you are used, is to resemble Symfony such PHP frame, so the function that carried CSRF your card oneself.

You still can examine about OWASP more detailed problem mixes the article of more defense mechanism: Https://github.com/OWASP/CheatS. . . .

4.LFI

LFI (this locality file is included) it is an user reads the flaw that takes a file from disk without test and verify.

I often encounter the road with non-standard process designing by code give typical examples, they not test and verify filters the input of the user. We are with the following file exemple, the pattern plate document that wants it apply colours to a drawing requests to load with GET.

<body>< ? Php $page = $_GET['page']; If(! $page) {$page = 'main.php'; } Include($page); ? ></body>

Because Include is OK to load any files, it is PHP not just, aggressor can serve as any files on the system include a target to deliver.

Index.php? Page= . . / . . / Etc/passwd

This will be brought about / Etc/passwd file is read to take and reveal go up in the browser.

Want defence this kind of attack, you must consider carefully to allow the kind that the user inputs, delete may harmful character, in be like input character " . " " / " " " .

If you want to use really,resemble such road by the system (I do not suggest in any way) , you can add automatically PHP is patulous, delete any blame [the character of A-zA-Z0-9-_] , appoint from the to load in folder of appropriative pattern plate, lest be included files of any blame pattern plate.

I am in different development documentation, see the PHP code that creates this kind of loophole for many times. Design train of thought from what be about to have clarity at the beginning, allow what to need included file type, delete redundant content. You still can construct should read the absolutely route that takes a file, and whether does file of test and verify exist will serve as protection, is not any positions give read take.

5.Inadequate password with a ha hopes

Major Web application needs to save the attestation information of the user. What if the password with a ha hopes,do is enough good, the website in you by breach when, the password that can protect an user is not read illegally to take.

Above all, the business that should do least of all, store user code proclaimed in writing namely rise. Major user can be used on many websites same a password, this is not changeable fact. The website that becomes you by breach, the Zhang date of the other website that means an user also by breach.

Next, you should not use simple haing rare algorithm, what have the algorithm that with a ha hopes technically to optimize for the password to should be not used in fact. Haing rare algorithm is like MD5 or SHA design original intention is carried out namely rise very fast. You do not need this, the time that the ultimate goal that the password with a ha hopes allows hacker expenditure is endless namely and energy cannot defeat solution to come out password.

The point with mainer another is you should be password Ha Xi to add salt (Salt) , the processing that add salt avoided two same codes to be able to produce the problem of same Ha Xi.

The following use MD5 will make case, must not use MD5 to with a ha hope please so your password, MD5 is insecure.

If our user User1 and User315 have identical password Ilovecats123, although this password is strong password it seems that, have word of alphabetical know exactly about sth, but in the database, the password of two users breaths out rare data will be identical: 5e2b4d823db9d044ecd5e084b6d33ea5.

If a website that if the hacker is taken,issued you, got these haing rare data, he will not need to go the password of User315 of the violent user that defeat solution. We should let him spend big energy to break the code that solves you as far as possible, so we undertake to data salt handles adding:

< ? Php //warning: ! ! This is an example of very insecure password Ha Xi, do not want to use please! ! $password = 'cat123'; $salt = Random_bytes(20); $hash = Md5($password. $salt);

It is finally when the data of exclusive password Ha Xi that saves you, do not forget to also had saved even $salt please, otherwise you will not user of test and verify.

In instantly, best password breaths out rare option is Bcrypt, this is the Ha Xi algorithm that designs to breath out rare password technically, at the same time this covers the difficulty that you still allow to configure a few parameter to increase broken solution in haing rare algorithm.

The code that safety also carried oneself in the PHP of new edition breaths out rare function Password_hash, this function had included the processing that add salt. Function of corresponding password test and verify is used for Password_verify detect the code is right. Password_verify still can prevent sequential attack effectively.

It is use case below:

< ? Php //user Signup $password = $_POST['password']; $hashedPassword = Password_hash($password, PASSWORD_DEFAULT); //login $password = $_POST['password']; $hash = '1234'; //load This Value From Your Db If(password_verify($password, $hash)) {Echo 'Password Is Valid! '; } Else {Echo 'Invalid Password. '; }

Need clarifies is: The password with a ha hopes is not the password is added close. Ha Xi (Hash) it is target text version changeover becomes those who have identical length, not reversible scrappy string (or call a message the summary) , and add close (Encrypt) it is target text version changeover becomes those who have different length, reversible close article. Apparent the biggest distinction between them is reversibility, storing when the password, what we want is the attribute that Ha Xi cannot go against this kind.

6.Bagman attack

MITM (bagman) attack is not to be aimed at a server to be atttacked directly, undertake in the light of the user however, aggressor regards bagman deceit server as him is an user, beguiling user he is a server, come thereby the discharge of intercept user and website, and from which content of infuse ill will perhaps is read take illicit secret information, happen in communal WiFi network normally, happen likely also in the place that other discharge passes, for example ISP operation business.

It is use HTTPS to this only defense, use HTTPS can increase your connection close, and cannot be read be taken or distort discharge. You can get free SSL letter from Let's Encrypt, or be in from other vendor buy, the here is unspecified fine introducing that how to configure WEB server correctly, because this and applied process security have nothing to do, and depend on greatly your setting.

You still can adopt a few measure to make HTTPS safer, in WEB server configuration adds Strict-Transport-Security indicative head, this head information tells a browser, your website passes HTTPS visit from beginning to end, if will not return erroneous report through HTTPS,clew browser should not show this page.

However, here has a clear problem, if your website never has been visited before the browser, cannot know you use this designation head, use Hstspreload with respect to need at that time.

Can register your website here: Https://hstspreload.org/

All websites that your herein refers will are by mark only HTTPS, hard encode arrives in the source code of Google Chrome, FireFox, Opera, Safari, IE11 and Edge.

You are OK still Certification Authority Authorization (CAA) Record is added in DNS configuration, can allow a certificate to issue an orgnaization only (for example: Let's Encrypt) the domain name letter that issues you, this enhanced the security of the user further.

7.Command infuse

This may be the most serious charge that the server encounters, the target that commands infuse is to cheat a server to execute aleatoric Shell order

If you are used Shell_exec or it is Exec function. Let us make a small case, allow the differs from server Ping lead plane with simple user.

< ? Php $targetIp = $_GET['ip']; $output = Shell_exec("ping -c 5 $targetIp");

Output will include Ping 5 of pair of target lead plane second. Unless use Sh to command executive Shell script, otherwise aggressor can execute any wanted operations.

Ping.php? Ip=8.8.8.8;ls -l /etc

Shell mixes executive Ping by the 2nd command of aggressor joining together, this is breakneck apparently.

Acknowledgment PHP offerred a function to come parameter of transferred meaning Shell.

The input of user of Escapeshellarg transferred meaning encloses his into only quote.

< ? Php $targetIp = Escapeshellarg($_GET['ip']); $output = Shell_exec("ping -c 5 $targetIp");

Now your command should be quite safe, with respect to the individual character, I still avoid to use PHP to call exterior command, but this depends on completely yourself's be fond of.

Additional, I suggest whether input of user of farther test and verify accords with the form that you expect.

8.XXE

XXE (XML is exterior and hypostatic) it is process of a kind of application the XML with use incorrect configuration is analytic implement when analytic and exterior XML, this locality file that bring about includes charge, OK even and long-range code is carried out.

XML has a little-known character, it allows documentation author to will serve as entity remotely to include with this locality file in its XML file.

< ? Xml Version="1.0" Encoding="ISO-8859-1" ? >< ! DOCTYPE Foo [< ! ELEMENT Foo ANY>< ! ENTITY Passwd SYSTEM "file:///etc/passwd" > ]><foo>&passwd;</foo>

Resemble such, / Etc/passwd file content is gone to by dump in XML file.

If your use Libxml can call Libxml_disable_entity_loader,will protect oneself to avoid suffer this kind of attack. The acquiesce that microscope XML library asks before using is configured, in order to ensure configuration is successful.

9.Incorrect in producing an environment erroneous report reveals sensitive data

[] (Https://secure.php.net/manual. . . , because incorrect erroneous report divulged sensitive information,may be in in manufacturing environment, for example: Information of folder structure, database structure, join and user information.

Introduction of PHP safe problem: 10 common and safe problems + example explains

Are you not to hope the user sees this?

The frame that uses according to you commonly or CMS, configuration method can have distinct change. Normally frame is had allow you to change the site the setting that produces an environment for some kind. The wrong message that such meetings see all users is heavy directional in log file, show the 500 errors that are not descriptive sex to the user, allow you to be checked according to wrong code at the same time.

But you should install according to your PHP environment: Error_reporting and Display_errors.

10.Entry limitation

Resemble logging onto such sensitive watch sheet to should have a strict rate restriction, in order to prevent violent attack. Save every user to try a time in the entry that failed inside a few minutes in the past, if this rate exceeds the threshold value that you define, reject to log onto an attempt further, until refrigeration period ends. Still can inform through email the user logs onto failure, so that they know their account,be become target.

A few other complement

Do not want accredit to deliver your object ID from the user, from beginning to end the visit attributive server to asking a boy or girl friend and use library hour maintain user of test and verify the rich guest with newest subscription safe and relevant attention, the code that knows newest solution to never save an user in the log does not want memory of library of will whole code not to want to establish Git memory warehouse in WEB root catalog forever in WEB root catalog, unless you hope to divulge whole code library to assume the input of the user is insecure setting system prohibits from beginning to end,the IP of doubtful behavior shows, for example: The tool trusts tripartite code is safety not overly to URL random scanning, reptile do not use Composer to if do not hope the site is crossed by tripartite,get code from Github directly region Iframe, if you are the operation business that lacks practice experience or joint development personnel,asking a setting to turn over Iframe indicative head is insecure vaguely, ensure please check code not to understand safe function how to should work when you constantly as far as possible, why can perhaps install, ask known person please, do not ignore it not to want its to write forever impose close kind, if you do not have enough entropy,this may be a bad method, if,abandon insecure on Internet, possible by filch information, make incident answer a plan to ban for ready-made of this kind of circumstance please show with list of WEB root catalog, server of a lot of WEB configures acquiescent metropolis listed catalog content, it is insufficient that this may bring about data to divulge a client to carry test and verify, need again all content in PHP of test and verify not hesitate all cost avoid to turn over alignment to change user content, this may bring about long-range code to carry out, about the detailed information of this problem, consult please this article: Https://paragonie.com/blog/20. . .

Small stick person

I am not a safe expert, fear cannot accomplishing All matters. Although write the process that safe software is a special anguish, but still can pass follow a few basic regulation, write the applied program of reasonable safety. Actually, a lot of frame also helped us do a lot of works in this respect.

Before problem happening, it is OK that security problem does not resemble solecism waiting in development level is tracked. Accordingly, in the process that writes code, always should have the consciousness of avoid safety risk. If your pressure by force of demand for service and must temporary oversight the job that a few safety are on guard, I think you are necessary to impart the potential risk that everybody becomes so beforehand.

If you from this article somewhat accrual, the friends that also share it to you please, let us build safe website in all.

未经允许不得转载:News » Introduction of PHP safe problem: 10 common and safe problems + example explains