/** * Test of getSanitizedHTML method of class Sanitizer. */ function testGetSanitizedHTML_03() { $san = ESAPI::getSanitizer(); $test3 = 'Test.<script>alert(document.cookie)</script>'; $result3 = $san->getSanitizedHTML('test', $test3, 100, false); $this->assertEquals('Test.', $result3); }
/** * Instantiates a new intrusion exception. * * @param string $userMessage The message displayed to the user * @param string $logMessage the message logged * * @return does not return a value. */ public function __construct($userMessage = '', $logMessage = '') { parent::__construct($userMessage); $this->logMessage = $logMessage; $logger = ESAPI::getAuditor("IntrusionException"); $logger->error(DefaultAuditor::SECURITY, false, "INTRUSION - " . $logMessage); }
function __construct() { //The xml file is in its insecure default location. //We would normally have all referenced libraries outside of the webroot. $this->esapi = new ESAPI('../owasp-esapi-php-read-only/test/testresources/ESAPI.xml'); ESAPI::setEncoder(new DefaultEncoder()); ESAPI::setValidator(new DefaultValidator()); $this->encoder = ESAPI::getEncoder(); $this->validator = ESAPI::getValidator(); }
/** * Constructor sets-up the validation rule with a descriptive name for this * validator, an optional Encoder instance (for canonicalization) and an * optional whitelist regex pattern to validate the input against prior to * HTML purification. * An instance of the HTMLPurifier class is created and stored too. * * @param string $typeName descriptive name for this validator. * @param object $encoder providing canonicalize method. * @param string $whitelistPattern Whitelist regex. * * @return does not return a value. */ public function __construct($typeName, $encoder = null, $whitelistPattern = null) { parent::__construct($typeName, $encoder); $this->_auditor = ESAPI::getAuditor('HTMLValidationRule'); try { $this->_purifier = new HTMLPurifier($this->_basicConfig()); } catch (Exception $e) { throw new ValidationException('Could not initialize HTMLPurifier.', 'Caught ' . gettype($e) . ' attempting to instantiate HTMLPurifier: ' . $e->getMessage, 'HTMLValidationRule->construct'); } }
/** * Returns an instance of StringValidationRule constructed with a regex * pattern for validating Credit Card Numbers obtained from the ESAPI * SecurityConfiguration. * * @return object object of type StringValidationRule. */ private function _getCCRule() { global $ESAPI; $config = ESAPI::getSecurityConfiguration(); $pattern = $config->getValidationPattern(self::CREDIT_CARD_VALIDATOR_KEY); $ccr = new StringValidationRule('CreditCardValidator', $this->encoder, $pattern); $ccr->setMaximumLength(19); $ccr->setAllowNull(false); return $ccr; }
/** * Creates a new instance of EnterpriseSecurityException that includes a * root cause. * * @param string $userMessage The message displayed to the user * @param string $logMessage the message logged */ public function __construct($userMessage = '', $logMessage = '') { $cause = 0; if (empty($userMessage)) { $userMessage = null; } parent::__construct($userMessage); $this->logMessage = $logMessage; $this->logger = ESAPI::getAuditor("EnterpriseSecurityException"); if (!ESAPI::getSecurityConfiguration()->getDisableIntrusionDetection()) { ESAPI::getIntrusionDetector()->addException($this); } }
/** * The errorAction handles errors and exceptions. * * @return null */ public function errorAction() { $this->getResponse()->clearBody(); $errors = $this->_getParam('error_handler'); switch ($errors->type) { case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE: case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER: case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION: // 404 error -- controller or action not found $this->getResponse()->setHttpResponseCode(404); $this->view->message = 'The page requested was not found.'; break; default: // Log exceptions. EnterpriseSecurityException were automagically logged // so they are not logged here. if ($errors->exception instanceof EnterpriseSecurityException === false) { ESAPI::getIntrusionDetector()->addException($errors->exception); } // application error - if display_errors is off then the client // is redirected to the index controller error action where a // generic error message will be rendered. $bootstrap = $this->getInvokeArg('bootstrap'); if ($bootstrap->hasOption('phpsettings')) { $o = $bootstrap->getOption('phpsettings'); if (array_key_exists('display_errors', $o) && $o['display_errors'] !== '1') { if (Zend_Session::sessionExists()) { $ns = new Zend_Session_Namespace('Contact'); $ns->error = true; } $this->_helper->getHelper('redirector')->setCode(303)->gotoSimple('error', 'index', null, $this->_request->getParams()); return; } } $this->getResponse()->setHttpResponseCode(500); $this->view->message = 'Application error'; } // conditionally display exceptions if ($this->getInvokeArg('displayExceptions') == true) { $this->view->exception = $errors->exception; } $this->view->request = $errors->request; }
/** * Helper function. * * Configures Apache's Log4PHP RootLogger based on values obtained from the * ESAPI properties file. All instances of Log4PHP Logger will inherit the * configuration. * * @return does not return a value. */ private static function _initialise() { self::$_initialised = true; $secConfig = ESAPI::getSecurityConfiguration(); $logLevel = $secConfig->getLogLevel(); // Patterns representing the format of Log entries // d date, p priority (level), m message, n newline $dateFormat = $secConfig->getLogFileDateFormat(); $logfileLayoutPattern = "%d{{$dateFormat}} %m %n"; // LogFile properties. $logFileName = $secConfig->getLogFileName(); $maxLogFileSize = $secConfig->getMaxLogFileSize(); $maxLogFileBackups = $secConfig->getMaxLogFileBackups(); // LogFile layout $logfileLayout = new LoggerLayoutPattern(); $logfileLayout->setConversionPattern($logfileLayoutPattern); // LogFile RollingFile Appender $appenderLogfile = new LoggerAppenderRollingFile('ESAPI LogFile'); $appenderLogfile->setFile($logFileName, true); $appenderLogfile->setMaxFileSize($maxLogFileSize); $appenderLogfile->setMaxBackupIndex($maxLogFileBackups); $appenderLogfile->setLayout($logfileLayout); if ($logLevel !== 'OFF') { $appenderLogfile->activateOptions(); } // Get the RootLogger and reset it, before adding our Appenders and // setting our Loglevel $rootLogger = Logger::getRootLogger(); $rootLogger->removeAllAppenders(); $rootLogger->addAppender($appenderLogfile); $rootLogger->setLevel(self::_convertESAPILeveltoLoggerLevel($logLevel)); }
/** * Test constructor of class SafeFile with Invalid path. * * @return bool True on Pass. */ function testSafeFileLowByteInFileName() { $config = ESAPI::getSecurityConfiguration(); $file = $config->getResourceDirectory() . "/ESAPI" . chr(8) . ".xml"; $this->setExpectedException('EnterpriseSecurityException'); $sf = new SafeFile($file); }
/** * Takes an HTTP query string and parses it into name-value pairs which are * returned as an associative array. This implementation will ignore * duplicate paramater names, returning only the first found parameter. * * @param string $query The HTTP query string to be parsed. * * @return array of name value pairs from the query string. */ private function _queryToMap($query) { $map = array(); $parts = explode('&', $query); foreach ($parts as $part) { try { $nvpair = explode('=', $part); $name = ESAPI::getEncoder()->decodeFromURL($nvpair[0]); $value = ESAPI::getEncoder()->decodeFromURL($nvpair[1]); if (!array_key_exists($name, $map)) { $map[$name] = $value; } } catch (EncodingException $e) { // NoOp - skip this pair - exception was logged already. } } return $map; }
/** * Validates the input string against a whitelist of acceptable characters. * * @param string $input The input string to be validated. * * @return bool True if input string contains only characters defined in the * whitelist, otherwise * False. */ public function isValid($input) { if (!is_string($input) || empty($input)) { $this->_error(self::INVALID); return false; } $canonical = ESAPI::getEncoder()->canonicalize($input, false); $detectedCharEnc = mb_detect_encoding($canonical); if ($detectedCharEnc != 'UTF-8') { $canonical = mb_convert_encoding($canonical, 'UTF-8', $detectedCharEnc); } $limit = mb_strlen($canonical, 'UTF-8'); for ($i = 0; $i < $limit; $i++) { $c = mb_substr($canonical, $i, 1, 'UTF-8'); if (in_array($c, $this->_charset, true) !== true) { $this->_error(self::INPUT_NOT_IN_WHITELIST); return false; } } return true; }
<?php /* ------------------------------------------ * initialize OWASP ESAPI for PHP * ------------------------------------------ */ require_once __ROOT__ . '/owasp-esapi-php/src/ESAPI.php'; if (!isset($ESAPI)) { $ESAPI = new ESAPI(__ROOT__ . '/owasp-esapi-php/src/ESAPI.xml'); $Encoder = $ESAPI->getEncoder(); } // end if /* ------------------------------------------ * initialize custom error handler * ------------------------------------------ */ require_once __ROOT__ . '/classes/CustomErrorHandler.php'; if (!isset($CustomErrorHandler)) { $CustomErrorHandler = new CustomErrorHandler(__ROOT__ . '/owasp-esapi-php/src/', $_SESSION["security-level"]); } // end if /* ------------------------------------------ * initialize log error handler * ------------------------------------------ */ require_once __ROOT__ . '/classes/LogHandler.php'; $LogHandler = new LogHandler(__ROOT__ . '/owasp-esapi-php/src/', $_SESSION["security-level"]); /* ------------------------------------------ * initialize SQL Query Handler * ------------------------------------------ */ require_once __ROOT__ . '/classes/SQLQueryHandler.php'; $SQLQueryHandler = new SQLQueryHandler(__ROOT__ . "/owasp-esapi-php/src/", $_SESSION["security-level"]);
/** * Create a new random reference that is guaranteed to be unique. * * @return * a random reference that is guaranteed to be unique */ function getUniqueRandomReference() { $candidate = null; do { $candidate = ESAPI::getRandomizer()->getRandomString(6, "123456789"); } while ($this->itod->offsetExists($candidate)); return $candidate; }
/** * @inheritdoc */ public function encodeForOS($codec, $input) { if ($input === null) { return null; } if ($codec instanceof Codec == false) { ESAPI::getLogger('Encoder')->error(ESAPILogger::SECURITY, false, 'Invalid Argument, expected an instance of an OS Codec.'); return null; } return $codec->encode($this->_immune_os, $input); }
<?php /** * OWASP Enterprise Security API (ESAPI) * * This file is part of the Open Web Application Security Project (OWASP) * Enterprise Security API (ESAPI) project. * * PHP version 5.2 * * LICENSE: This source file is subject to the New BSD license. You should read * and accept the LICENSE before you use, modify, and/or redistribute this * software. * * @category OWASP * @package ESAPI * @author Andrew van der Stock <*****@*****.**> * @author Mike Boberski <*****@*****.**> * @copyright 2009-2011 The OWASP Foundation * @license http://www.opensource.org/licenses/bsd-license.php New BSD license * @version SVN: $Id$ * @link http://www.owasp.org/index.php/ESAPI */ error_reporting(E_ALL | ~E_STRICT); require_once __DIR__ . '/../src/ESAPI.php'; ESAPI::getSecurityConfiguration(__DIR__ . '/testresources/ESAPI.xml'); session_start(); // For HTTPUtilities;
/** * Test of isValidDirectoryPath method, of class org.owasp.esapi.Validator. */ public function testIsValidDirectoryPath() { $list = array(); array_push($list, new HTMLEntityCodec()); $encoder = new DefaultEncoder($list); $instance = ESAPI::getValidator(); switch ($this->_os) { case self::PLATFORM_WINDOWS: // Windows paths that should pass $this->assertTrue($instance->isValidDirectoryPath('test', 'C:\\', false)); // Windows root directory $this->assertTrue($instance->isValidDirectoryPath('test', 'C:\\Windows', false)); // Windows always exist directory // Windows paths that don't exist and thus should fail $this->assertFalse($instance->isValidDirectoryPath('test', 'c:\\ridiculous', false)); $this->assertFalse($instance->isValidDirectoryPath('test', 'c:\\temp\\..\\etc', false)); // Windows path that exists but is not a directory $this->assertFalse($instance->isValidDirectoryPath('test', 'C:\\Windows\\System32\\cmd.exe', false)); // Windows command shell // Windows path that exists but is not canonical $this->assertFalse($instance->isValidDirectoryPath('test', 'C:\\Windows\\System32\\..', false)); // Unix specific paths should not pass $this->assertFalse($instance->isValidDirectoryPath('test', '/tmp', false)); // Unix Temporary directory $this->assertFalse($instance->isValidDirectoryPath('test', '/bin/sh', false)); // Unix Standard shell $this->assertFalse($instance->isValidDirectoryPath('test', '/etc/config', false)); // Unix specific paths that should not exist or work $this->assertFalse($instance->isValidDirectoryPath('test', '/etc/ridiculous', false)); $this->assertFalse($instance->isValidDirectoryPath('test', '/tmp/../etc', false)); break; case self::PLATFORM_UNIX: // Unix specific paths should pass $this->assertTrue($instance->isValidDirectoryPath('test', '/', false)); // Root directory $this->assertTrue($instance->isValidDirectoryPath('test', '/bin', false)); // Always exist directory // Unix specific path that exists but is not a directory $this->assertFalse($instance->isValidDirectoryPath('test', '/bin/sh', false)); // Standard shell // Unix specific path that exists but is not canonical $this->assertFalse($instance->isValidDirectoryPath('test', '/bin/../', false)); // Unix specific paths that should not exist or work $this->assertFalse($instance->isValidDirectoryPath('test', '/etc/ridiculous', false)); $this->assertFalse($instance->isValidDirectoryPath('test', '/tmp/../etc', false)); // Windows paths should fail $this->assertFalse($instance->isValidDirectoryPath('test', 'c:\\ridiculous', false)); $this->assertFalse($instance->isValidDirectoryPath('test', 'c:\\temp\\..\\etc', false)); // Standard Windows locations should fail $this->assertFalse($instance->isValidDirectoryPath('test', 'c:\\', false)); // Windows root directory $this->assertFalse($instance->isValidDirectoryPath('test', 'c:\\Windows\\temp', false)); // Windows temporary directory $this->assertFalse($instance->isValidDirectoryPath('test', 'c:\\Windows\\System32\\cmd.exe', false)); // Windows command shell break; } }
/** * Helper method returns a random string of alphanumeric characters of the * supplied length. * * @param int $len Length of the required string. * * @return string A string of $len alphanumeric characters. */ function getRandomAlphaNumString($len) { if (empty($len)) { return null; } ESAPI::getEncoder(); return ESAPI::getRandomizer()->getRandomString($len, Encoder::CHAR_ALPHANUMERICS); }
/** * {@inheritDoc} */ public function verifyPassword($password) { return ESAPI::getAuthenticator()->verifyPassword($this, $password); }
/** * Constructor sets-up the validation rule with a descriptive name for this * validator, an optional Encoder instance (for canonicalization) and an * optional whitelist regex pattern to validate the input against prior to * email address purification. * An instance of the HTMLPurifier class is created and stored too. * * @param string $typeName descriptive name for this validator. * @param object $encoder object providing canonicalize method. * @param string $whitelistPattern Whitelist regex. * * @return does not return a value. */ public function __construct($typeName, $encoder = null, $whitelistPattern = null) { parent::__construct($typeName, $encoder); $this->_auditor = ESAPI::getAuditor("EmailAddressValidationRule"); }
/** * Helper function. * * @param string $msg Message to output to the console. * * @return does not return a value. */ private function _logSpecial($msg) { ESAPI::getAuditor('DefaultSecurityConfiguration')->warning(Auditor::SECURITY, false, $msg); }
/** * The router is set to /action and this segment of the url is overloaded * so that /someRecipient is also valid. This __call method is invoked * whenever this segment of the url is not a defined action and in these * cases, the $actionMethod may be a valid recipient. These sre trapped * here and, if valid, the request is re-dispatched to the index action to * which we pass a recipient parameter. * If a valid recipient is not found then execution is passed to the parent * __call method. * * @param string $actionMethod Url segment. * @param array $args Request arguments. * * @return null */ public function __call($actionMethod, $args) { $logger = ESAPI::getAuditor('IndexController'); // I do not anticipate this happening often... if (!is_string($actionMethod)) { return parent::__call($actionMethod, $args); } // If there's less than two recipients defined, we don't need to trap // usernames. ignore them. if ($this->_recipientsConfig->count() < 2) { return parent::__call($actionMethod, $args); } // Strip the trailing 'Action' from the method name. $method = null; $detectedCharacterEncoding = mb_detect_encoding($actionMethod); $len = mb_strlen($actionMethod, $detectedCharacterEncoding); if (mb_substr($actionMethod, $len - 6, 6, $detectedCharacterEncoding) == 'Action') { $method = mb_substr($actionMethod, 0, $len - 6, $detectedCharacterEncoding); } else { $method = $actionMethod; } // Validate the possible recipient and, if valid, add a 'recipient' // request param and continue on to the indexAction of this controller. $recipientValidator = new Custom_Validate_ValidRecipient($this->_recipientsConfig); if ($recipientValidator->isValid($method)) { $this->_request->setActionName('index'); $this->_request->setParams(array('recipient' => $method, 'action' => 'index')); $this->_request->setDispatched(false); return; } return parent::__call($actionMethod, $args); }
/** * Public Constructor */ function __construct() { $logger = ESAPI::getAuditor("Base64"); }
/** * _addString is called by addEncodedString or addUnencodedString and adds * Codec input to the buffer character by character. It also adds some * backtrace information to the buffer before adding any characters. * * @param string $string is a UTF-32 encoded string. * * @return null */ private function _addString($string) { if ($this->_enabled == false || !ESAPI::getAuditor(CD_LOG)->isDebugEnabled() || !$this->_allowRecurse) { return; } // start with some details about the caller if ($this->_buf === null) { $caller = null; try { $caller = $this->_shortTrace(); } catch (Exception $e) { $caller = $this->_verb . 'ing'; } $this->_buf = $caller . ":\n"; } // add the string, char by char $len = mb_strlen($string, 'UTF-32'); if ($len == 0) { $this->_addNormalized(''); return; } for ($i = 0; $i < $len; $i++) { $char = mb_substr($string, $i, 1, 'UTF-32'); $this->_addNormalized($char); } }
/** * Adds a security event. These events are used to check that the user has * not reached the security thresholds set in the properties file. If a PHP * session has been started the events are stored there, otherwise they are * merely stored as an instance property. This means that if a session has * not been started prior to calling this function then events will not be * tracked across requests. * * @param string $eventName The name of the event that occurred. * * @return null */ private function _addSecurityEvent($eventName) { // if there is a threshold, then track this event $threshold = ESAPI::getSecurityConfiguration()->getQuota($eventName); if ($threshold === null) { return; } // determine the storage for events if (isset($_SESSION)) { if (!array_key_exists('ESAPI', $_SESSION)) { $_SESSION['ESAPI'] = array(); } if (!array_key_exists('IntrusionDetector', $_SESSION['ESAPI'])) { $_SESSION['ESAPI']['IntrusionDetector'] = array(); } if (!array_key_exists('UserEvents', $_SESSION['ESAPI']['IntrusionDetector'])) { $_SESSION['ESAPI']['IntrusionDetector']['UserEvents'] = array(); } // If a session was started after events existed then ensure those // events are added to the session store if (is_array($this->_userEvents) && $this->_userEvents !== $_SESSION['ESAPI']['IntrusionDetector']['UserEvents']) { $_SESSION['ESAPI']['IntrusionDetector']['UserEvents'] = $this->_userEvents; } // Assign a reference to the session store $this->_userEvents =& $_SESSION['ESAPI']['IntrusionDetector']['UserEvents']; } else { if (!isset($this->_userEvents)) { $this->_userEvents = array(); } } $event = null; if (array_key_exists($eventName, $this->_userEvents)) { $event = $this->_userEvents[$eventName]; } if ($event == null) { $this->_userEvents[$eventName] = new Event($eventName); $event = $this->_userEvents[$eventName]; } if ($threshold->count > 0) { $event->increment($threshold->count, $threshold->interval); } }
/** * Implements corresponding isValidXX logic. * * @param string $context Please see corresponding isValidXX description. * @param string $input Please see corresponding isValidXX description. * @param int $maxBytes Please see corresponding isValidXX description. * @param bool $allowNull Please see corresponding isValidXX description. * * @return does not return a value. * @throws ValidationException thrown if input is invalid. * @throws IntrusionException thrown if intrusion is detected. */ private function _assertValidFileContent($context, $input, $maxBytes, $allowNull) { if (!is_string($context)) { $context = 'Validate File Content'; } if (!is_string($input) && $input !== null) { throw new ValidationException("{$context}: Input required", "Input was not a string or NULL: context={$context}", $context); } if (!is_numeric($maxBytes) || $maxBytes < 0) { $this->_auditor->warning(ESAPILogger::SECURITY, false, 'assertValidFileContent expected $maxBytes as positive integer.' . ' Falling back to AllowedFileUploadSize.'); $maxBytes = null; } if ($input === null || $input == '') { if ($this->allowNull) { return null; } throw new ValidationException("{$context}: Input required", "Input required: context={$context}", $context); } $config = ESAPI::getSecurityConfiguration(); $esapiMaxBytes = $config->getAllowedFileUploadSize(); $charEnc = mb_detect_encoding($input); $inputLen = mb_strlen($input, $charEnc); if ($inputLen > $esapiMaxBytes) { throw new ValidationException("{$context}: Invalid file content. Size must not exceed " . "{$esapiMaxBytes} bytes.", "Invalid file content. Input ({$inputLen} bytes) exceeds " . "AllowedFileUploadSize ({$esapiMaxBytes} bytes.)", $context); } if ($maxBytes !== null && $inputLen > $maxBytes) { throw new ValidationException("{$context}: Invalid file content. Size must not exceed " . "{$maxBytes} bytes.", "Invalid file content. Input ({$inputLen} bytes) exceeds " . "maximum of ({$esapiMaxBytes} bytes.)", $context); } return null; }
/** * Helper method uses the supplied parameters to construct a pattern for * preg_match and which attempts to model log entries. It is important to * note that if changes are made to the format of log entries {@see * DefaultLogger::log()} then this method will need to be modified * accordingly. * * @param $level string uppercase log level. * @param $type string uppercase log entry type. * @param $success boolean true for a success log event, false otherwise. * @param $msg string log message as passed to the DefaultLogger method. * @param $exceptionClassName string optional class name of an exception * passed to DefaultLogger methods. * * @return string pattern (incl. terminators) for preg_match(). */ private function getExpected($level, $type, $success, $msg, $exceptionClassName = null) { $date = '[0-9-]{10,10} [0-9:]{8,8} [+-][0-9:]{5,5}'; $success = $success ? '-SUCCESS' : '-FAILURE'; $appName = ESAPI::getSecurityConfiguration()->getLogApplicationName() === true ? ' ' . ESAPI::getSecurityConfiguration()->getApplicationName() : ''; $name = __CLASS__; $serverName = '((?:(?:[0-9a-zA-Z][0-9a-zA-Z\\-]{0,61}[0-9a-zA-Z])\\.)*[a-zA-Z]{2,4}|[0-9a-zA-Z][0-9a-zA-Z\\-]{0,61}[0-9a-zA-Z]|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))'; $localSocket = "{$serverName}:[0-9]{1,5}"; $username = '******'; $remoteAddr = '([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}|UnknownRemoteHost)'; $sessionID = '([0-9]{1,7}|SessionUnknown)'; if ($exceptionClassName !== null) { $msg .= " exception '{$exceptionClassName}'"; } return "{$date} {$level}{$appName} {$name} {$type}{$success} {$localSocket} {$username}{$remoteAddr}\\[ID:{$sessionID}\\] {$msg}"; }
/** * Executor constructor. * * @return does not return a value. */ public function __construct() { $this->_auditor = ESAPI::getAuditor('Executor'); $this->_config = ESAPI::getSecurityConfiguration(); }
* Index. This is the public script through which all requests for the contact * application will be routed. * * @category Simple-PHP-Contact-Form * @package Public * @author jah <*****@*****.**> * @copyright 2010 jah <*****@*****.**> * @license New BSD License {@see LICENSE} * @version Release: @package_version@ * @link http://code.google.com/p/simple-php-contact-form/ */ // Define path to application directory defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application')); // Define path to library directory (not application/library/) defined('LIBRARY_PATH') || define('LIBRARY_PATH', realpath(dirname(__FILE__) . '/../library')); // Define path to this directory defined('PUBLIC_ROOT') || define('PUBLIC_ROOT', dirname($_SERVER['PHP_SELF']) == '\\' || dirname($_SERVER['PHP_SELF']) == '/' ? '/' : dirname($_SERVER['PHP_SELF']) . '/'); // Define application environment defined('APPLICATION_ENV') || define('APPLICATION_ENV', getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'); // Ensure application/library is on include_path set_include_path(implode(PATH_SEPARATOR, array(LIBRARY_PATH, realpath(APPLICATION_PATH . '/library'), get_include_path()))); /* ESAPI */ require_once LIBRARY_PATH . '/ESAPI/src/ESAPI.php'; global $ESAPI; $ESAPI = new ESAPI(APPLICATION_PATH . '/configs/ESAPI.xml'); ESAPI::getAuditor('Bootstrap'); /* Zend_Application */ require_once 'Zend/Application.php'; // Create application, bootstrap, and run $application = new Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini'); $application->bootstrap()->run();
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $tainted = $_SESSION['UserData']; $ESAPI = new ESAPI(); ESAPI::setEncoder(new DefaultEncoder()); ESAPI::setValidator(new DefaultValidator()); //verifying the data with ESAPI if ($ESAPI->validator->isValidNumber("Course ID", $tainted, 18, 25, false)) { $tainted = $tainted; } else { $tainted = 0; //default value } $query = "SELECT * FROM COURSE WHERE id=?"; $conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); //Connection to the database (address, user, password) $stmt = $conn->prepare($query); $stmt->bind_param("i", $checked_data); $stmt->execute(); mysql_close($conn);
/** * Returns a $representation of the hashed password, using the * accountName as the salt. The salt helps to prevent against "rainbow" * table attacks where the attacker pre-calculates hashes for known strings. * This method specifies the use of the user's account name as the "salt" * value. The Encryptor.hash method can be used if a different salt is * required. * * @param password * the password to hash * @param accountName * the account name to use as the salt * * @return * the hashed password */ function hashPassword($password, $accountName) { $salt = strtolower($accountName); return ESAPI::getEncryptor()->hash($password, $salt); }