<?php
/**
* WebOpenPatch
*
* LICENSE
*
* This source file is subject to the GNU/GPL license.
* It is also available through the world-wide-web at this URL:
* http://www.gnu.org/licenses/gpl.html
*
*
* @category Security
* @package WebOpenPatch
* @author Marcos Bezerra (mbezerra [at] gmail.com)
* @license http://www.gnu.org/licenses/gpl.html GNU/GPL
* @version 1.0
* @date May 4, 2008
*/
class WebOpenPatch {
private $output = array();
/**
* Este método recebe variáveis passadas pelo usuário,
* seja por $_GET, seja por $_POST e as sanitariza antes
* de retorná-las ao sistema.
* Também é possível passar uma string contendo toda
* a query SQL formada para sanitarizá-la antes de
* sua execução.
*
* @param mixed $var [variáveis de entrada]
* @param boolean $quotes [indica retorno com ou sem aspas simples]
* @return mixed [retorno das variáveiz sanitarizadas]
*/
public function wopAntiSqlInjection($var, $quotes = true) {
if (is_array($var)) {
foreach ($var as &$val) {
$val = $this->wopAntiSqlInjection($val);
}
}
else if (is_string($var)) {
$var = mysql_real_escape_string($var);
if ($quotes) {
$var = "'". $var ."'";
}
}
else if (is_null($var)) {
$var = "NULL";
}
else if (is_bool($var)) {
$var = ($var) ? 1 : 0;
}
return $var;
}
/**
* Este método recebe o parâmetro from do formulário de e-mail
* e verifica a existência de caracteres especiais que denotem
* algum tipo de injeção por spammers.
*
* @param string $from [e-mail do remetente]
* @return boolean [false = em ataque; true = seguro)
*/
public function wopAntiMailInjection($from) {
$from = urldecode($from);
if (eregi("(\r|\n)", $from)) {
return false;
} else {
return true;
}
}
/**
* Este método recebe quatro parâmetros:
* $key = chave do vetor para assegurar a validade da saída
* $preOutput = saída não tratada
* $charset = tipo dos caracteres de saída (default = UTF-8)
*
* O array $output conterá as seguintes transformações para HTML Entities:
* De Para
* < <
* > >
* ( (
* ) )
* # #
* & &
*
* @param string $key
* @param string $preOutput
* @param string $charset [default = UTF-8]
* @return array [vetor com a saída tratada, mapeado pelas chaves fornecidas]
*/
public function wopAntiXssInjection($key, $preOutput, $charset = 'UTF-8') {
$key = (string) $key;
$this->output[$key] = htmlentities($preOutput, ENT_QUOTES, $charset);
}
/**
* Método para retornar o array com dados tratados pelo método
* wopAntiXssInjection() para a saída da aplicação
*
* @return array
*/
public function getOutput() {
return $this->output;
}
/**
* Este método recebe uma lista branca de seções possíveis num site
* e verifica se determinada seção referenciada em $_GET faz parte
* desta lista, retornando a seção validada. Caso não faça parte da
* lista, retornará a seção default permitida ('home').
*
* @param string $getSection [seção referenciada na URL]
* @param array $sections [lista branca com as seções permitidas]
* @param string $defaultCleanSection [seção default = 'home']
* @return string [seção validada]
*/
public function wopAntiRemoteCodeInjection($getSection, $sections, $defaultCleanSection = 'home') {
if (in_array($getSection, $sections)) {
$cleanSection = $getSection;
} else {
$cleanSection = $defaultCleanSection;
}
return $cleanSection;
}
/**
* Método para criar e checar a existência de tokens
* para validação de formulários submetidos, em prevenção
* à ataques Coss-Site Request Forgeries (XSRF).
* É necessário utilizar método POST no formulário e a
* inclusão da seguinte linha no formulário:
* <input type="hidden" name="token" value="<?php echo wopAntiXsrfInjection(); ?>" />
*
* No script de checagem dos dados enviados, a validação do post é feita assim:
* if(wopAntiXsrfInjection(false)){
* //form aceito
* } else {
* //form recusado
* }
*
* @param boolean $tokenGeneration [true = gerar token; false = veerificar token]
* @return mixed [na geração retorna o token em si; na verificação, um booleano]
*/
public function wopAntiXsrfInjection($tokenGeneration = true) {
if ($tokenGeneration) {
if (session_id() == "") {
session_start();
}
$token = md5(uniqid(rand(), true));
$_SESSION['token'] = $token;
return $token;
} else {
if (isset($_SESSION['token']) && isset($_POST['token']) && $_POST['token'] == $_SESSION['token']) {
return true;
} else {
return false;
}
}
}
}
?>