Ir para o conteúdo

Programar em PHP e SQL de forma segura

Mensagens Recomendadas

teckV    1

PHP E SQL security today

Artigo muito bom sobre questões importantes sobre o desenvolvimento em PHP e SQL.

Nos dias de hoje com o uso massificado e firewall e proteções de rede e perimetro a principal via de ataque é o layer Aplicacional. As firewall podem bloquear portos e trafego mas são obrigadas a deixar passar determinado trafegonomeadamente HTTP necessário ao funcionamento de aplicações web sejam sites publicossejam extranets...

Portantos as aplicações web são um caminho entre o mundo exterior (a internet insegura) e o mundo interior (as redes seguras internas)o qual está na mira dos crackers... a maior parte da pesquise em metodos de ataque desenvolve-se hoje em torno de vulnerabilidades aplicacionais... muitos dos programadores não conhecem bem este mundo e progrmam de forma insegura permitindo que todo o trabalho de segurança seja posto em causa abrindo as portas aos atacantes..

retirado da revista INSECUREMAG e por estar muito bom (não é preciso reiventar a roda) vou apresenta-lo aqui num formato de topico de forum...



gostava que este topico fosse usado por todos como um local para discutir este tipo de assuntos relacionados com programar em PHPSQL do ponto de vista de segurança... se alguem tiver (há muitas mais coisas a abordar nesta materia) algo a crescentar

peço a todos seriedade e não se sentirem seguros sobre o que escrever usem outro post mais informal... gostava de manter um grande nivel técnico aqui e vou continuar a acreescentar coisas...

esta primeira parte aborda temas gericos no desenvolvimento web com analisar INPUTs e SQL Injection...

se repararem em vez passwd escrevo passw-d por questões evidentes

PHP E SQL security today

Whether your site is the web presence for a large multinationala gallery showing your product range and inviting potential customers to come into the shopor a personal site exhibiting your holiday photosweb security matters. After the hard work put in to make your site look good and respond to your usersthe last thing you want is for a malicious hacker to come along and break it somehow.

There are a number of problems in web securityand unfortunately not all of them have definite solutionsbut here we'll look at some of the problems that should be considered every time you set out to write a PHP script. These are the problems whichwith well-designed codecan be eliminated entirely. Before looking in detail at the solutionsthoughlet's take a moment to define the problems themselves.

SQL InjectionIn this attacka user is able to execute SQL queries in your website's database. This attack is usually performed by entering text into a form field

which causes a subsequent SQL querygenerated from the PHP form processing codeto execute part of the content of the form field as though it were SQL. The effects of this attack range from the harmless (simply using SELECT to pull another data set) to the devastating (DELETEfor instance).

In more subtle attacksdata could be changedor new data added.

Directory Traversal

This attack can occur anywhere user-supplied data (from a form field or uploaded filenamefor example) is used in a filesystem operation. If a user specifies ../../../../../../etc/passw-d as form dataand your script appends that to a directory name to obtain user-specific filesthis string could lead to the inclusion of the password

file contentsinstead of the intended file. More severe cases involve file operations such as moving and deletingwhich allow an attacker to make arbitrary changes to your filesystem structure.

Authentication IssuesAuthentication issues involve users gaining access to something they shouldn'tbut to which other users should. An example would be a user

who was able to steal (or construct) a cookie allowing them to login to your site under an Administrator sessionand therefore be able to change anything they liked.

Remote Scripts (XSS)

XSSor Cross-Site Scripting (also sometimes referred to as CSSbut this can be confused with Cascading Style Sheetssomething entirely different!) is the process of exploiting a security hole in one site to run arbitrary code on that site's server.

The code is usually included into a running PHP script from a remote location. This is a serious attack which could allow any code the attacker chooses to be run on the vulnerable serverwith all of the permissions of the user hosting the scriptincluding database and filesystem access.

Processing User Data – Form Input

Verification & HTML DisplayValidating Input And Stripping TagsWhen a user enters information into a form which is to be later processed on your sitethey have the

power to enter anything they want. Code which processes form input should be carefully written to ensure that the input is as requested; password fields have the required level of complexitye-mail fields have at least some charactersan @ signsome more charactersa periodand two or more characters at the end; zip or postal codes are of the required formatand so on.

Each of these may be verified using regular expressionswhich scan the input for certain patterns. An example for e-mail address verification is the PHP code shown below. This evaluates to true if an e-mail address was entered in the field named 'email'.


This code just constructs a regular expression based on the format described above for an e-mail address. Note that this will return true for anything with an @ sign and a dot followed by 2 or 3 characters. That is the general format for an e-mail addressbut it doesn't mean that address necessarily exists; you'd have to send mail to it to be sure of that.

Interesting as this ishow does it relate to security? Wellconsider a guestbook as an example.

Hereusers are invited to enter a message into a formwhich then gets displayed on the HTML page along with everyone else's messages. For nowwe won't go into database security issues; the problems dealt with below can occur whether the data is stored in a databasea fileor some other construct.

If a user enters data which contains HTMLor even JavaScriptthen when the data is included into your HTML for display latertheir HTML or JavaScript will also get included. If your guestbook page displayed whatever was entered into the form fieldand a user entered the following:

HiI <b>love</b> your site.

Then the effect is minimalwhen displayed laterthis would appear as:

HiI love your site.

Of coursewhen the user enters JavaScriptthings can get a lot worse. For examplethe data belowwhen entered into a form which does not prevent JavaScript ending up in the final displayed pagewill cause the page to redirect to a different website. Obviouslythis only works if the client has JavaScript enabled in their browserbut the vast

majority of users do.

HiI love your site. Its great!<scriptlanguage=”JavaScript”>document.location=””;</script>

For a split second when this is displayedthe user will see:

HiI love your site. Its great!

The browser will then kick in and the page will be refreshed from In this caseit would be a fairly harmless alternative pagealthough it does result in a denial of service attack;

users can no longer get to your guestbook.

Consider a case where this was entered into an online order form. Your order dispatchers would not be able to view the data because every time they triedtheir browser would redirect to another site.

Worse stillif the redirection occurred on a critical page for a large businessor the redirection was to a site containing objectionable materialcustom may be lost as a result of the attack.

FortunatelyPHP provides a way to prevent this style of attack. The functions strip_tags()nl2br() and htmlspecialchars() are your friendshere.

strip_tags() removes any PHP or HTML tags from a string. This prevents the HTML display problemsthe JavaScript execution (the <script> tag will no longer be present) and a variety of problems where there is a chance that PHP code could be executed.

nl2br() converts newline characters in the input to <br /> HTML tags. This allows you to format multi-line input correctlyand is mentioned here only because it is important to run strip_tags() prior to running nl2br() on your dataotherwise the newly inserted <br /> tags will be stripped out when strip_tags() is run!

Finallyhtmlspecialchars() will entity-quote characters such as <> and & remaining in the input after strip_tags() has run. This prevents them being misinterpreted as HTML and makes sure they are displayed properly in any output.

Having presented those three functionsthere are a few points to make about their usage. Clearlynl2br() and htmlspecialchars() are suited for output formattingcalled on data just before it is outputallowing the database or file-stored data to retain normal formatting such as newlines and characters such as &. These functions are designed mainly to ensure that output of data into an HTML page is presented neatlyeven after running strip_tags() on any input.

strip_tags() on the other handshould be run immediately on input of databefore any other processing occurs. The code below is a function to clean user input of any PHP or HTML tagsand works for both GET and POST request methods.

function _INPUT($name)
return strip_tags($_GET[$name]); 
return strip_tags($_POST[$name]);

This function could easily be expanded to include cookies in the search for a variable name. I called it _INPUT because it directly parallels the $_ arrays which store user input. Note also that when using this functionit does not matter whether the page was requested with a GET or a POST method; the code can use _INPUT() and expect the correct value regardless of request method.

To use this functionconsider the following two lines of codewhich both have the same effectbut the second strips the PHP and HTML tags firstthus increasing the security of the script.

$name = $_GET['name');
$name = _INPUT('name');

If data is to be entered into a databasemore processing is needed to prevent SQL injectionwhich will be discussed later.

Executing Code Containing User InputAnother concern when dealing with user data is the possibility that it may be executed in PHP code or in the system shell. PHP provides the eval() functionwhich allows arbitrary PHP code within a string to be evaluated (run).

There are also the system()passthru() and exec() functionsand the backtick operatorall of which allow a string to be run as a command in the operating system shell.

Where possibleavoid the use of all such functionsespecially where user input is entered into the command or code. An example of a situation where this can lead to attack is the following commandwhich would display the results of the command on the web page.

echo 'Your usage log:<br />';
$username = $_GET['username'];
passthru(“cat /logs/usage/$username”);

passthru() runs a command and displays the output as output from the PHP scriptwhich is included into the final page the user sees. Herethe intent is obvious: a user can pass their username in a GET request such as usage.php?username=andrew and their usage log would be displayed in the browser window.

But what if the user passed the following URL usage.php?username=andrew;cat%20/etc/passw-d

Herethe username value now contains a semicolonwhich is a shell command terminatorand a new command afterwards. The %20 is a URL-Encoded space characterand is converted to a space automatically by PHP. Nowthe command which gets run by passthru() is:

cat /logs/usage/andrew;cat /etc/passw-d 

Clearly this kind of command abuse cannot be allowed. An attacker could use this vulnerability to readdelete or modify any file the web server has access to.

Luckilyonce againPHP steps in to provide a solutionin the form of the escapeshellarg() function. escapeshellarg() escapes any characters which could cause an argument or command to be terminated.

As an exampleany single or double quotes in the string are replaced with \' or \”and semicolons are replaced with \;. These replacementsand any others performed by escapeshellarg()ensure that code such as that presented below is safe to run.

$username = escapeshellarg($_GET['username']);
passthru(“cat /logs/usage/$username”);

Nowif the attacker attempts to read the password file using the request string abovethe shell will attempt to access a file called “/logs/usage/andrew;cat /etc/passw-d” and will failsince this file will almost certainly not exist.

At all costseval() called on code containing user input should be avoided; there is almost always a better way to achieve the desired effect. Howeverif it must be doneensure that strip_tags has been calledand that any quoting and character escapes have been performed.

Combining the above techniques to provide tag stripping special shell character escapesentityquoting of HTML and regular expression-based input validationit is possible to construct secure web scripts with relatively little work over and above constructing one without the security considerations.

In particularusing a function such as the _INPUT() presented above makes the secure version of input acquisition almost as painless as the insecure version PHP provides.

Andrew J Bennieston has been building secure PHP systems for several yearsand contributes to leading computer security websites and forums. He takes an active role in researching the best practices in secure programming and applying those to working systems. Article commissioned by Acunetix ( flagship flagship product Acunetix Web Vulnerability Scannerscans a website for vulnerabilities to SQL injection and PHP securityamongst others.



Partilhar esta mensagem

Link para a mensagem
Partilhar noutros sites
kingless    0

Excelente artigo :P Apesar de não dar exemplos da forma mais utilizada pelos hacker para atacar sites. (PHP INJECTION)

EDIT:,com_topatt/Itemid,19/  Lista das hackers que mais atacam, podem ver a quantidade de sites que são hackeados todos dias.... Quando tiverem a desenvolver um projecto a segurança tem que estar sempre em primeiro lugar.

Partilhar esta mensagem

Link para a mensagem
Partilhar noutros sites
NCS_One    2


So uma pequena correçao, devia estar assim :

function _INPUT($name)
return strip_tags($_GET[$name]); 
return strip_tags($_POST[$name]);

Esta = em vez de ==

As vezes as pequenas coisas fazem perder muito tempo e eu perdi pelo menos 15 minutos. :-[

Partilhar esta mensagem

Link para a mensagem
Partilhar noutros sites

Crie uma conta ou ligue-se para comentar

Só membros podem comentar

Criar nova conta

Registe para ter uma conta na nossa comunidade. É fácil!

Registar nova conta


Já tem conta? Inicie sessão aqui.

Entrar Agora


Aviso Sobre Cookies

Ao usar este site você aceita os nossos Termos de Uso e Política de Privacidade