SlideShare uma empresa Scribd logo
Segurança
em 2016
Segurança PHP em 2016 www.galvao.eti.br
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 1 / 37
Presidente da ABRAPHP – Associação Brasileira de Profissionais PHP
Diretor da PHP Conference Brasil
Contribui para a tradução da documentação oficial
Atua como Zend Framework Evangelist para o ZTeam, da Zend.
Professor Especialista de Pós-Graduação UNOESC (SC) e
Faculdade Alfa (PR)
20+ anos desenvolvendo sistemas e aplicações com interface web
15+ destes com PHP
7+ com Zend Framework
Palestrante em eventos nacionais e internacionais
Instrutor de cursos presenciais e a distância
Fundador e líder do GU PHPBR
Fundador* e membro do GU PHPRS
Site: http://www.galvao.eti.br/
http://people.php.net/galvao
Twitter: @galvao
Slides e Documentos: http://slideshare.net/ergalvao
Github: http://github.com/galvao
Posts: https://medium.com/@galvao
Quem?!
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 2 / 37
www.galvao.eti.brSegurança PHP em 2016
Sumário
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 3 / 37
www.galvao.eti.br
O status da Segurança PHP em 2016
● Hashing
● PRNG
● Criptografia
● Banco de Dados
● Tipagem
Segurança PHP em 2016
Sumário
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 4 / 37
www.galvao.eti.brSegurança PHP em 2016
Tudo se resume a evolução
Hashing (Senhas)
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 5 / 37
www.galvao.eti.brSegurança PHP em 2016
md5('my_password');
sha1('my_password');
crypt('my_password', 'my_salt');
Hashing (Senhas)
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 6 / 37
www.galvao.eti.br
md5('my_password');
sha1('my_password');
crypt('my_password', 'my_salt');
Segurança PHP em 2016
Hashing (Senhas)
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 7 / 37
www.galvao.eti.br
md5('my_password');
sha1('my_password');
crypt('my_password', 'my_salt');
Segurança PHP em 2016
Hashing (Senhas)
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 8 / 37
www.galvao.eti.br
<?php
$hash = password_hash('my_password',
PASSWORD_BCRYPT,
['cost' => 10,
'salt' => 'this_is_my_salt_is_my_salt']
);
Segurança PHP em 2016
Hashing (Senhas)
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 9 / 37
www.galvao.eti.br
<?php
$hash = password_hash('my_password',
PASSWORD_BCRYPT,
['cost' => 10,
'salt' => 'this_is_my_salt_is_my_salt']
);
if (password_verify('my_password', $hash)) {
// YAY!
}
Segurança PHP em 2016
Hashing (Senhas)
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 10 / 37
www.galvao.eti.br
<?php
$pass = 'my_password';
$options = ['cost' => 10];
$hash = password_hash($pass,
PASSWORD_DEFAULT,
$options
);
if (password_verify($pass, $hash)) {
if (password_needs_rehash($hash,
PASSWORD_DEFAULT,
$options)) {
$newHash = password_hash($pass,
PASSWORD_DEFAULT,
$options);
}
}
Segurança PHP em 2016
Hashing (Senhas)
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 11 / 37
www.galvao.eti.br
<?php
$pass = 'my_password';
$options = ['cost' => 10];
$hash = password_hash($pass,
PASSWORD_DEFAULT,
$options
);
if (password_verify($pass, $hash)) {
if (password_needs_rehash($hash,
PASSWORD_DEFAULT,
$options)) {
$newHash = password_hash($pass,
PASSWORD_DEFAULT,
$options);
}
}
Segurança PHP em 2016
Hashing (Senhas)
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 12 / 37
www.galvao.eti.br
<?php
$pass = 'my_password';
$options = ['cost' => 10];
$hash = password_hash($pass,
PASSWORD_DEFAULT,
$options
);
if (password_verify($pass, $hash)) {
if (password_needs_rehash($hash,
PASSWORD_DEFAULT,
$options)) {
$newHash = password_hash($pass,
PASSWORD_DEFAULT,
$options);
}
}
Segurança PHP em 2016
PRNG
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 13 / 37
www.galvao.eti.br
rand($min, $max);
mt_rand($min, $max);
// Implementação qualquer de randomização
// de strings, tipo essa
Segurança PHP em 2016
PRNG
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 14 / 37
www.galvao.eti.br
rand($min, $max);
mt_rand($min, $max);
// Implementação qualquer de randomização
// de strings, tipo essa
Segurança PHP em 2016
PRNG
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 15 / 37
www.galvao.eti.br
rand($min, $max);
mt_rand($min, $max);
// Implementação qualquer de randomização
// de strings, tipo essa
Segurança PHP em 2016
PRNG
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 16 / 37
www.galvao.eti.brSegurança PHP em 2016
<?php
$randomInt = random_int(0, 10);
PRNG
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 17 / 37
www.galvao.eti.brSegurança PHP em 2016
<?php
$randomInt = random_int(0, 10);
$randomStr = random_bytes(22);
PRNG
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 18 / 37
www.galvao.eti.brSegurança PHP em 2016
<?php
$randomInt = random_int(0, 10);
$randomStr = random_bytes(22);
echo $randomInt . PHP_EOL;
echo base64_encode($randomStr);
PRNG
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 19 / 37
www.galvao.eti.brSegurança PHP em 2016
<?php
try {
$randomInt = random_int(0, 10);
echo $randomInt . PHP_EOL;
} catch (Exception $e) {
die('Lib de randomização não encontrada: ' .
$e->getMessage());
}
try {
$randomStr = random_bytes(22);
echo base64_encode($randomStr);
} catch (Exception $e) {
die('Lib de randomização não encontrada: ' .
$e->getMessage());
}
PRNG
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 20 / 37
www.galvao.eti.brSegurança PHP em 2016
<?php
try {
$randomInt = random_int(0, 10);
echo $randomInt . PHP_EOL;
} catch (Exception $e) {
die('Lib de randomização não encontrada: ' .
$e->getMessage());
}
try {
$randomStr = random_bytes(22);
echo base64_encode($randomStr);
} catch (Exception $e) {
die('Lib de randomização não encontrada: ' .
$e->getMessage());
}
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 21 / 37
www.galvao.eti.br
mcrypt_encrypt(MCRYPT_RIJNDAEL_128,
$key,
$str,
MCRYPT_MODE_CBC,
$iv
);
mcrypt_decrypt(MCRYPT_RIJNDAEL_128,
$key,
$crypt,
MCRYPT_MODE_CBC,
$iv
);
Segurança PHP em 2016
Criptografia
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 22 / 37
www.galvao.eti.br
mcrypt_encrypt(MCRYPT_RIJNDAEL_128,
$key,
$str,
MCRYPT_MODE_CBC,
$iv
);
mcrypt_decrypt(MCRYPT_RIJNDAEL_128,
$key,
$crypt,
MCRYPT_MODE_CBC,
$iv
);
Segurança PHP em 2016
Criptografia
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 23 / 37
www.galvao.eti.br
$key = Sodiumrandombytes_buf(SodiumCRYPTO_SECRETBOX_KEYBYTES);
$nonce =
Sodiumrandombytes_buf(SodiumCRYPTO_SECRETBOX_NONCEBYTES);
$ciphertext = Sodiumcrypto_secretbox('test', $nonce, $key);
Segurança PHP em 2016
Criptografia
$plaintext = Sodiumcrypto_secretbox_open($ciphertext, $nonce, $key);
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 24 / 37
www.galvao.eti.br
$crypt = openssl_encrypt('teste', 'blowfish', 'foo', 0, '11122233');
Segurança PHP em 2016
Criptografia
$plaintext = openssl_decrypt($crypt, 'blowfish', 'foo', 0, '11122233');
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 25 / 37
www.galvao.eti.brSegurança PHP em 2016
Banco de Dados
mysql_*();
Queries com valores diretos;
Entre outras coisas...
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 26 / 37
www.galvao.eti.brSegurança PHP em 2016
Banco de Dados
mysql_*();
Queries com valores diretos;
Entre outras coisas...
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 27 / 37
www.galvao.eti.brSegurança PHP em 2016
Banco de Dados
$dsn = 'mysql:dbname=nome_do_banco;host=127.0.0.1';
$user = 'usuario_do_banco';
$password = 'senha_do_banco';
$value = 'ABC'
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Conexão falhou: ' . $e->getMessage();
}
$sql = 'SELECT * FROM produto WHERE nome=:clause';
$sth = $dbh->prepare($sql);
$sth->bindParam(':clause', $value, PDO::PARAM_STR);
$sth->execute();
$red = $sth->fetchAll();
var_dump($red[0]['nome']);
$dbh = NULL;
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 28 / 37
www.galvao.eti.brSegurança PHP em 2016
Banco de Dados
$dsn = 'mysql:dbname=nome_do_banco;host=127.0.0.1';
$user = 'usuario_do_banco';
$password = 'senha_do_banco';
$value = 'ABC'
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Conexão falhou: ' . $e->getMessage();
}
$sql = 'SELECT * FROM produto WHERE nome=:clause';
$sth = $dbh->prepare($sql);
$sth->bindParam(':clause', $value, PDO::PARAM_STR);
$sth->execute();
$red = $sth->fetchAll();
var_dump($red[0]['nome']);
$dbh = NULL;
Tipagem
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 29 / 37
www.galvao.eti.br
<?php
declare(strict_types=1);
function foo(int $x, int $y)
{
return $x + $y;
}
echo foo('1', 2);
Segurança PHP em 2016
Tipagem
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 30 / 37
www.galvao.eti.br
<?php
declare(strict_types=1);
function foo(int $x, int $y)
{
return $x + $y;
}
echo foo('1', 2);
Segurança PHP em 2016
Fatal error: Uncaught TypeError: Argument 1 passed to foo()
must be of the type integer, string given, called in
/home/vagrant/php7tests/t1.php on line 9
and defined in /home/vagrant/php7tests/t1.php:4
Stack trace:
...
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 31 / 37
www.galvao.eti.brSegurança PHP em 2016
Constantes
Nem tudo muda…
… ou o que eu quero dizer com “outras coisas”
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 32 / 37
www.galvao.eti.brSegurança PHP em 2016
Constantes
Imagem
by nixCraft
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 33 / 37
www.galvao.eti.brSegurança PHP em 2016
Constantes
Segurança deixa a aplicação lenta?
Segurança é difícil de aprender?
Segurança é difícil de implementar?
A resposta continua sendo a mesma:
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 34 / 37
www.galvao.eti.brSegurança PHP em 2016
Constantes
Segurança deixa a aplicação lenta?
Segurança é difícil de aprender?
Segurança é difícil de implementar?
A resposta continua sendo a mesma:
NÃO IMPORTA!
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 35 / 37
www.galvao.eti.brSegurança PHP em 2016
Constantes
Notegraphy,
Galvão
INFORME-SE!
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 36 / 37
www.galvao.eti.brSegurança PHP em 2016
Acompanhe as mudanças da linguagem
https://wiki.php.net/rfc
Usando libsodium com PHP
https://paragonie.com/book/pecl-libsodium
Pesquise e ESTUDE!
https://www.owasp.org/
RTFM!!!
http://php.net/manual/en
Muito obrigado!
CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 37 / 37
www.galvao.eti.br
? Dúvidas?
↓ Críticas?
↑ Elogios?!
Segurança PHP em 2016

Mais conteúdo relacionado

PDF
Tudo o que você precisa saber sobre o php7
PDF
DRYing the Skeleton: Reducing code repetition in ZF2
ODP
Php7 esta chgando! O que você precisa saber
PPTX
PHP 7 - A Maioridade do PHP
PDF
Muito prazer, eu sou PHP
PDF
Unbreakeable php
PDF
15 coisas sobre php para saber antes de morrer
PDF
PHP para aplicações Web de grande porte
Tudo o que você precisa saber sobre o php7
DRYing the Skeleton: Reducing code repetition in ZF2
Php7 esta chgando! O que você precisa saber
PHP 7 - A Maioridade do PHP
Muito prazer, eu sou PHP
Unbreakeable php
15 coisas sobre php para saber antes de morrer
PHP para aplicações Web de grande porte

Mais procurados (20)

PPTX
PHP Além da universidade
PDF
PHP na Tela Escura: Aplicações Poderosas em Linha de Comando
ODP
Otimizando a execução de código-fonte PHP
PDF
Zend Framework 3 - porque só o que existe pode ser aprimorado
PDF
Zend framework 3 Hangout 2016
PDF
Desenvolvendo mvp com python
PDF
[FISL 16] PHP no Campo de Batalha: Segurança Avançada e Programação Defensiva...
PDF
O futuro do elephante: as promessas do php para 2019
PPTX
Rumo à Certificação PHP
ZIP
Pog Nunca Mais - Técnicas e Macetes para o Desenvolvimento em PHP
PDF
Como fazer boas libs
ODP
Php Test Fest PHPMS, Maio 2008
PDF
O que esperar do Zend Framework 3
ODP
Brasiliatestfest
KEY
Introdução ao Python & Web Services
PDF
PHP Jedi - Boas Práticas e Alta Performance
PDF
Migrando para PHP7 - Novidades
ODP
O que há de novo no PHP 5.3
PPT
Mini-curso codeIgniter - aula 1
PPTX
PHPSP TestFest 2010
PHP Além da universidade
PHP na Tela Escura: Aplicações Poderosas em Linha de Comando
Otimizando a execução de código-fonte PHP
Zend Framework 3 - porque só o que existe pode ser aprimorado
Zend framework 3 Hangout 2016
Desenvolvendo mvp com python
[FISL 16] PHP no Campo de Batalha: Segurança Avançada e Programação Defensiva...
O futuro do elephante: as promessas do php para 2019
Rumo à Certificação PHP
Pog Nunca Mais - Técnicas e Macetes para o Desenvolvimento em PHP
Como fazer boas libs
Php Test Fest PHPMS, Maio 2008
O que esperar do Zend Framework 3
Brasiliatestfest
Introdução ao Python & Web Services
PHP Jedi - Boas Práticas e Alta Performance
Migrando para PHP7 - Novidades
O que há de novo no PHP 5.3
Mini-curso codeIgniter - aula 1
PHPSP TestFest 2010
Anúncio

Destaque (9)

PDF
DrupalCamp Campinas 2016 - Auditando performance, conteúdo e boas práticas em...
PPTX
Protegendo Aplicações Php com PHPIDS - Php Conference 2009
PPT
Tratando as vulnerabilidades do Top 10 com php
PDF
Security & PHP
PDF
Segurança em Aplicações Web
PPT
OWASP Top 10 - Experiência e Cases com Auditorias Teste de Invasão em Aplicaç...
PPTX
Desenvolvendo sistemas seguros com PHP
PPTX
Segurança em PHP - Blinde seu código de você mesmo!
PDF
PHP Conference Brasil 2011 - Desenvolvendo Seguro (do rascunho ao deploy)
DrupalCamp Campinas 2016 - Auditando performance, conteúdo e boas práticas em...
Protegendo Aplicações Php com PHPIDS - Php Conference 2009
Tratando as vulnerabilidades do Top 10 com php
Security & PHP
Segurança em Aplicações Web
OWASP Top 10 - Experiência e Cases com Auditorias Teste de Invasão em Aplicaç...
Desenvolvendo sistemas seguros com PHP
Segurança em PHP - Blinde seu código de você mesmo!
PHP Conference Brasil 2011 - Desenvolvendo Seguro (do rascunho ao deploy)
Anúncio

Semelhante a Segurança PHP em 2016 (20)

PDF
Escrevendo códigos php seguros
PDF
Hello SAFE World!!!
ODP
Php 02 Primeiros Passos
ODP
Prog web 02-php-primeiros-passos
PPT
Php FrameWARks - sem CakePHP
PDF
Introducao ao PHP
PPTX
Aula 01 - Curso PHP e MySQL
PDF
Pdo do PHP Palestra
PDF
Linguagem PHP
ODP
Da argila ao forte: como desenvolver uma loja com PagSeguro
PDF
Código legado - PHP Conference Brasil - 2014
PDF
Aula 02 - Introdução ao PHP - Programação Web
PDF
Strings, Arrays e Manipulação Datas em PHP
PDF
Palestra PHPSP+Locaweb 2014 - PDO
ODP
Dependency injection
PPT
PHP GERAL
PDF
PHP, mas o que é isso ?
ODP
Php 07 Cakephp
PDF
Simplificando o Javascrip
Escrevendo códigos php seguros
Hello SAFE World!!!
Php 02 Primeiros Passos
Prog web 02-php-primeiros-passos
Php FrameWARks - sem CakePHP
Introducao ao PHP
Aula 01 - Curso PHP e MySQL
Pdo do PHP Palestra
Linguagem PHP
Da argila ao forte: como desenvolver uma loja com PagSeguro
Código legado - PHP Conference Brasil - 2014
Aula 02 - Introdução ao PHP - Programação Web
Strings, Arrays e Manipulação Datas em PHP
Palestra PHPSP+Locaweb 2014 - PDO
Dependency injection
PHP GERAL
PHP, mas o que é isso ?
Php 07 Cakephp
Simplificando o Javascrip

Mais de Er Galvão Abbott (20)

ODP
PHP e Open Source
PDF
ABRAPHP: Conquistas e Realizações - 2012-2014
ODP
Implementing security routines with zf2
PDF
Desenvolvendo aplicações com ZF2
PDF
Apresentacao frameworks
ODP
Web: funcionamento, evolução e mercado
PDF
PHP: Evolução
PDF
ZF2 Menor, melhor e mais poderoso
ODP
Implementando rotinas de geolocalização
ODP
OSS, Comunidade, Eventos e como sua empresa ganha com isso
ODP
OWASP: O que, Por que e Como
PDF
Além da autenticação: Permissões de acesso com Zend Framework
PDF
Proposta de Boas Práticas e Padrões de Desenvolvimento Web
PDF
PHPBR TestFest
PDF
Preto, Branco e as Sombras de Cinza
PDF
Top 10 OWASP com PHP
PDF
Aplicacoes Web Com AJAX
PDF
Implementando Segurança Em Sua Aplicação PHP
PDF
Prevenindo XSS: Execute apenas o SEU código
PDF
PHP e Segurança - Uma união possível
PHP e Open Source
ABRAPHP: Conquistas e Realizações - 2012-2014
Implementing security routines with zf2
Desenvolvendo aplicações com ZF2
Apresentacao frameworks
Web: funcionamento, evolução e mercado
PHP: Evolução
ZF2 Menor, melhor e mais poderoso
Implementando rotinas de geolocalização
OSS, Comunidade, Eventos e como sua empresa ganha com isso
OWASP: O que, Por que e Como
Além da autenticação: Permissões de acesso com Zend Framework
Proposta de Boas Práticas e Padrões de Desenvolvimento Web
PHPBR TestFest
Preto, Branco e as Sombras de Cinza
Top 10 OWASP com PHP
Aplicacoes Web Com AJAX
Implementando Segurança Em Sua Aplicação PHP
Prevenindo XSS: Execute apenas o SEU código
PHP e Segurança - Uma união possível

Último (20)

PPTX
Curso de Java 14 - (Explicações Adicionais (Classes Abstrata e Interface)).pptx
PDF
Fullfilment AI - Forum ecommerce 2025 // Distrito e Total Express
PDF
20250805_ServiceNow e a Arquitetura Orientada a Serviços (SOA) A Base para Ap...
PDF
Mergulho profundo técnico para gestão de transportes no SAP S/4HANA, S4TM6 Col14
PDF
Custos e liquidação no SAP Transportation Management, TM130 Col18
PPTX
Émile Durkheim slide elaborado muito bom
PPTX
Aula sobre banco de dados com firebase db
PDF
Apple Pippin Uma breve introdução. - David Glotz
PPTX
Curso de Java 9 - (Threads) Multitarefas.pptx
PDF
Processos na gestão de transportes, TM100 Col18
PPTX
Curso de Java 15 - (Uso de Servlets (Entendendo a Estrutura)).pptx
PDF
Custos e faturamento no SAP S/4HANA Transportation Management, S4TM3 Col26
PDF
Fundamentos de gerenciamento de ordens e planejamento no SAP TransportationMa...
PPTX
Curso de Java 17 - (JEE (Sessões e Cookies)).pptx
PPTX
Programação - Linguagem C - Variáveis, Palavras Reservadas, tipos de dados, c...
PPTX
Curso de Java 12 - (JDBC, Transation, Commit e Rollback).pptx
PPTX
Gestao-de-Bugs-em-Software-Introducao.pptxxxxxxxx
PPTX
Curso de Java 11 - (Serializable (Serialização de Objetos)).pptx
PPTX
Aula16ManipulaçãoDadosssssssssssssssssssssssssssss
PDF
Gestão de transportes básica no SAP S/4HANA, S4611 Col20
Curso de Java 14 - (Explicações Adicionais (Classes Abstrata e Interface)).pptx
Fullfilment AI - Forum ecommerce 2025 // Distrito e Total Express
20250805_ServiceNow e a Arquitetura Orientada a Serviços (SOA) A Base para Ap...
Mergulho profundo técnico para gestão de transportes no SAP S/4HANA, S4TM6 Col14
Custos e liquidação no SAP Transportation Management, TM130 Col18
Émile Durkheim slide elaborado muito bom
Aula sobre banco de dados com firebase db
Apple Pippin Uma breve introdução. - David Glotz
Curso de Java 9 - (Threads) Multitarefas.pptx
Processos na gestão de transportes, TM100 Col18
Curso de Java 15 - (Uso de Servlets (Entendendo a Estrutura)).pptx
Custos e faturamento no SAP S/4HANA Transportation Management, S4TM3 Col26
Fundamentos de gerenciamento de ordens e planejamento no SAP TransportationMa...
Curso de Java 17 - (JEE (Sessões e Cookies)).pptx
Programação - Linguagem C - Variáveis, Palavras Reservadas, tipos de dados, c...
Curso de Java 12 - (JDBC, Transation, Commit e Rollback).pptx
Gestao-de-Bugs-em-Software-Introducao.pptxxxxxxxx
Curso de Java 11 - (Serializable (Serialização de Objetos)).pptx
Aula16ManipulaçãoDadosssssssssssssssssssssssssssss
Gestão de transportes básica no SAP S/4HANA, S4611 Col20

Segurança PHP em 2016

  • 1. Segurança em 2016 Segurança PHP em 2016 www.galvao.eti.br CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 1 / 37
  • 2. Presidente da ABRAPHP – Associação Brasileira de Profissionais PHP Diretor da PHP Conference Brasil Contribui para a tradução da documentação oficial Atua como Zend Framework Evangelist para o ZTeam, da Zend. Professor Especialista de Pós-Graduação UNOESC (SC) e Faculdade Alfa (PR) 20+ anos desenvolvendo sistemas e aplicações com interface web 15+ destes com PHP 7+ com Zend Framework Palestrante em eventos nacionais e internacionais Instrutor de cursos presenciais e a distância Fundador e líder do GU PHPBR Fundador* e membro do GU PHPRS Site: http://www.galvao.eti.br/ http://people.php.net/galvao Twitter: @galvao Slides e Documentos: http://slideshare.net/ergalvao Github: http://github.com/galvao Posts: https://medium.com/@galvao Quem?! CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 2 / 37 www.galvao.eti.brSegurança PHP em 2016
  • 3. Sumário CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 3 / 37 www.galvao.eti.br O status da Segurança PHP em 2016 ● Hashing ● PRNG ● Criptografia ● Banco de Dados ● Tipagem Segurança PHP em 2016
  • 4. Sumário CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 4 / 37 www.galvao.eti.brSegurança PHP em 2016 Tudo se resume a evolução
  • 5. Hashing (Senhas) CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 5 / 37 www.galvao.eti.brSegurança PHP em 2016 md5('my_password'); sha1('my_password'); crypt('my_password', 'my_salt');
  • 6. Hashing (Senhas) CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 6 / 37 www.galvao.eti.br md5('my_password'); sha1('my_password'); crypt('my_password', 'my_salt'); Segurança PHP em 2016
  • 7. Hashing (Senhas) CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 7 / 37 www.galvao.eti.br md5('my_password'); sha1('my_password'); crypt('my_password', 'my_salt'); Segurança PHP em 2016
  • 8. Hashing (Senhas) CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 8 / 37 www.galvao.eti.br <?php $hash = password_hash('my_password', PASSWORD_BCRYPT, ['cost' => 10, 'salt' => 'this_is_my_salt_is_my_salt'] ); Segurança PHP em 2016
  • 9. Hashing (Senhas) CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 9 / 37 www.galvao.eti.br <?php $hash = password_hash('my_password', PASSWORD_BCRYPT, ['cost' => 10, 'salt' => 'this_is_my_salt_is_my_salt'] ); if (password_verify('my_password', $hash)) { // YAY! } Segurança PHP em 2016
  • 10. Hashing (Senhas) CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 10 / 37 www.galvao.eti.br <?php $pass = 'my_password'; $options = ['cost' => 10]; $hash = password_hash($pass, PASSWORD_DEFAULT, $options ); if (password_verify($pass, $hash)) { if (password_needs_rehash($hash, PASSWORD_DEFAULT, $options)) { $newHash = password_hash($pass, PASSWORD_DEFAULT, $options); } } Segurança PHP em 2016
  • 11. Hashing (Senhas) CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 11 / 37 www.galvao.eti.br <?php $pass = 'my_password'; $options = ['cost' => 10]; $hash = password_hash($pass, PASSWORD_DEFAULT, $options ); if (password_verify($pass, $hash)) { if (password_needs_rehash($hash, PASSWORD_DEFAULT, $options)) { $newHash = password_hash($pass, PASSWORD_DEFAULT, $options); } } Segurança PHP em 2016
  • 12. Hashing (Senhas) CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 12 / 37 www.galvao.eti.br <?php $pass = 'my_password'; $options = ['cost' => 10]; $hash = password_hash($pass, PASSWORD_DEFAULT, $options ); if (password_verify($pass, $hash)) { if (password_needs_rehash($hash, PASSWORD_DEFAULT, $options)) { $newHash = password_hash($pass, PASSWORD_DEFAULT, $options); } } Segurança PHP em 2016
  • 13. PRNG CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 13 / 37 www.galvao.eti.br rand($min, $max); mt_rand($min, $max); // Implementação qualquer de randomização // de strings, tipo essa Segurança PHP em 2016
  • 14. PRNG CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 14 / 37 www.galvao.eti.br rand($min, $max); mt_rand($min, $max); // Implementação qualquer de randomização // de strings, tipo essa Segurança PHP em 2016
  • 15. PRNG CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 15 / 37 www.galvao.eti.br rand($min, $max); mt_rand($min, $max); // Implementação qualquer de randomização // de strings, tipo essa Segurança PHP em 2016
  • 16. PRNG CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 16 / 37 www.galvao.eti.brSegurança PHP em 2016 <?php $randomInt = random_int(0, 10);
  • 17. PRNG CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 17 / 37 www.galvao.eti.brSegurança PHP em 2016 <?php $randomInt = random_int(0, 10); $randomStr = random_bytes(22);
  • 18. PRNG CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 18 / 37 www.galvao.eti.brSegurança PHP em 2016 <?php $randomInt = random_int(0, 10); $randomStr = random_bytes(22); echo $randomInt . PHP_EOL; echo base64_encode($randomStr);
  • 19. PRNG CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 19 / 37 www.galvao.eti.brSegurança PHP em 2016 <?php try { $randomInt = random_int(0, 10); echo $randomInt . PHP_EOL; } catch (Exception $e) { die('Lib de randomização não encontrada: ' . $e->getMessage()); } try { $randomStr = random_bytes(22); echo base64_encode($randomStr); } catch (Exception $e) { die('Lib de randomização não encontrada: ' . $e->getMessage()); }
  • 20. PRNG CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 20 / 37 www.galvao.eti.brSegurança PHP em 2016 <?php try { $randomInt = random_int(0, 10); echo $randomInt . PHP_EOL; } catch (Exception $e) { die('Lib de randomização não encontrada: ' . $e->getMessage()); } try { $randomStr = random_bytes(22); echo base64_encode($randomStr); } catch (Exception $e) { die('Lib de randomização não encontrada: ' . $e->getMessage()); }
  • 21. CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 21 / 37 www.galvao.eti.br mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_CBC, $iv ); mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $crypt, MCRYPT_MODE_CBC, $iv ); Segurança PHP em 2016 Criptografia
  • 22. CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 22 / 37 www.galvao.eti.br mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_CBC, $iv ); mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $crypt, MCRYPT_MODE_CBC, $iv ); Segurança PHP em 2016 Criptografia
  • 23. CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 23 / 37 www.galvao.eti.br $key = Sodiumrandombytes_buf(SodiumCRYPTO_SECRETBOX_KEYBYTES); $nonce = Sodiumrandombytes_buf(SodiumCRYPTO_SECRETBOX_NONCEBYTES); $ciphertext = Sodiumcrypto_secretbox('test', $nonce, $key); Segurança PHP em 2016 Criptografia $plaintext = Sodiumcrypto_secretbox_open($ciphertext, $nonce, $key);
  • 24. CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 24 / 37 www.galvao.eti.br $crypt = openssl_encrypt('teste', 'blowfish', 'foo', 0, '11122233'); Segurança PHP em 2016 Criptografia $plaintext = openssl_decrypt($crypt, 'blowfish', 'foo', 0, '11122233');
  • 25. CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 25 / 37 www.galvao.eti.brSegurança PHP em 2016 Banco de Dados mysql_*(); Queries com valores diretos; Entre outras coisas...
  • 26. CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 26 / 37 www.galvao.eti.brSegurança PHP em 2016 Banco de Dados mysql_*(); Queries com valores diretos; Entre outras coisas...
  • 27. CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 27 / 37 www.galvao.eti.brSegurança PHP em 2016 Banco de Dados $dsn = 'mysql:dbname=nome_do_banco;host=127.0.0.1'; $user = 'usuario_do_banco'; $password = 'senha_do_banco'; $value = 'ABC' try { $dbh = new PDO($dsn, $user, $password); } catch (PDOException $e) { echo 'Conexão falhou: ' . $e->getMessage(); } $sql = 'SELECT * FROM produto WHERE nome=:clause'; $sth = $dbh->prepare($sql); $sth->bindParam(':clause', $value, PDO::PARAM_STR); $sth->execute(); $red = $sth->fetchAll(); var_dump($red[0]['nome']); $dbh = NULL;
  • 28. CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 28 / 37 www.galvao.eti.brSegurança PHP em 2016 Banco de Dados $dsn = 'mysql:dbname=nome_do_banco;host=127.0.0.1'; $user = 'usuario_do_banco'; $password = 'senha_do_banco'; $value = 'ABC' try { $dbh = new PDO($dsn, $user, $password); } catch (PDOException $e) { echo 'Conexão falhou: ' . $e->getMessage(); } $sql = 'SELECT * FROM produto WHERE nome=:clause'; $sth = $dbh->prepare($sql); $sth->bindParam(':clause', $value, PDO::PARAM_STR); $sth->execute(); $red = $sth->fetchAll(); var_dump($red[0]['nome']); $dbh = NULL;
  • 29. Tipagem CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 29 / 37 www.galvao.eti.br <?php declare(strict_types=1); function foo(int $x, int $y) { return $x + $y; } echo foo('1', 2); Segurança PHP em 2016
  • 30. Tipagem CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 30 / 37 www.galvao.eti.br <?php declare(strict_types=1); function foo(int $x, int $y) { return $x + $y; } echo foo('1', 2); Segurança PHP em 2016 Fatal error: Uncaught TypeError: Argument 1 passed to foo() must be of the type integer, string given, called in /home/vagrant/php7tests/t1.php on line 9 and defined in /home/vagrant/php7tests/t1.php:4 Stack trace: ...
  • 31. CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 31 / 37 www.galvao.eti.brSegurança PHP em 2016 Constantes Nem tudo muda… … ou o que eu quero dizer com “outras coisas”
  • 32. CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 32 / 37 www.galvao.eti.brSegurança PHP em 2016 Constantes Imagem by nixCraft
  • 33. CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 33 / 37 www.galvao.eti.brSegurança PHP em 2016 Constantes Segurança deixa a aplicação lenta? Segurança é difícil de aprender? Segurança é difícil de implementar? A resposta continua sendo a mesma:
  • 34. CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 34 / 37 www.galvao.eti.brSegurança PHP em 2016 Constantes Segurança deixa a aplicação lenta? Segurança é difícil de aprender? Segurança é difícil de implementar? A resposta continua sendo a mesma: NÃO IMPORTA!
  • 35. CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 35 / 37 www.galvao.eti.brSegurança PHP em 2016 Constantes Notegraphy, Galvão
  • 36. INFORME-SE! CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 36 / 37 www.galvao.eti.brSegurança PHP em 2016 Acompanhe as mudanças da linguagem https://wiki.php.net/rfc Usando libsodium com PHP https://paragonie.com/book/pecl-libsodium Pesquise e ESTUDE! https://www.owasp.org/ RTFM!!! http://php.net/manual/en
  • 37. Muito obrigado! CC Attribution-ShareAlike 3.0 Unported License by Er Galvão Abbott - 5/4/16 - 37 / 37 www.galvao.eti.br ? Dúvidas? ↓ Críticas? ↑ Elogios?! Segurança PHP em 2016