Esempio n. 1
0
 /**
  * Encoder constructor.
  * 
  * @param array $_codecs An array of Codec instances which will be used for
  *                       canonicalization.
  *                    
  * @return does not return a value.
  */
 function __construct($_codecs = null)
 {
     $this->logger = ESAPI::getAuditor("Encoder");
     // initialise codecs
     $this->_base64Codec = new Base64Codec();
     $this->_cssCodec = new CSSCodec();
     $this->_htmlCodec = new HTMLEntityCodec();
     $this->_javascriptCodec = new JavaScriptCodec();
     $this->_percentCodec = new PercentCodec();
     $this->_vbscriptCodec = new VBScriptCodec();
     $this->_xmlCodec = new XMLEntityCodec();
     // initialise array of codecs for use by canonicalize
     if ($_codecs === null) {
         array_push($this->_codecs, $this->_htmlCodec);
         array_push($this->_codecs, $this->_javascriptCodec);
         array_push($this->_codecs, $this->_percentCodec);
         // leaving css and vbs codecs out - they eat / and " chars respectively
         // array_push($this->_codecs,$this->_cssCodec);
         // array_push($this->_codecs,$this->_vbscriptCodec);
     } else {
         if (!is_array($_codecs)) {
             throw new Exception('Invalid Argument. Codec list must be of type ' . 'Array.');
         } else {
             // check array contains only codec instances
             foreach ($_codecs as $codec) {
                 if ($codec instanceof Codec == false) {
                     throw new Exception('Invalid Argument. Codec list must ' . 'contain only Codec instances.');
                 }
             }
             $this->_codecs = array_merge($this->_codecs, $_codecs);
         }
     }
 }
Esempio n. 2
0
 /**
  * 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);
 }
Esempio n. 3
0
 /**
  * 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');
     }
 }
 /**
  * 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);
     }
 }
 /**
  * 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);
 }
Esempio n. 7
0
 /**
  * _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);
     }
 }
 /**
  * The constructor stores an instance of Auditor for the purpose of logging.
  */
 public function __construct()
 {
     $this->_auditor = ESAPI::getAuditor('DefaultHTTPUtilities');
     $this->_validator = ESAPI::getValidator();
 }
 /**
  * Constructor stores an instance of Auditor for logging and initialises the
  * storage for events generated for a user.
  *
  * @return null
  */
 function __construct()
 {
     $this->_auditor = ESAPI::getAuditor('IntrusionDetector');
     $this->_userEvents = array();
 }
Esempio n. 10
0
 /**
  * Validator constructor.
  *
  * @return does not return a value.
  */
 public function __construct()
 {
     $this->_auditor = ESAPI::getAuditor('DefaultValidator');
     $this->_encoder = ESAPI::getEncoder();
     $this->_fileValidator = new DefaultEncoder(array(new HTMLEntityCodec(), new PercentCodec()));
 }
 /**
  * Add a reCaptcha element to the form assuming that:
  * o we have an ini file
  * o the 'use' options is not set to 'off'
  * o the 'use' option is set to 'on', and conditionallyUseCaptcha is not
  *   false.
  *
  * @return null
  */
 public function setCaptcha()
 {
     $bs = Zend_Controller_Front::getInstance()->getParam('bootstrap');
     $captchaConfigLoc = $bs->getOption('captchaconfigloc');
     // return if captcha should not be used.
     $captchaConfig = null;
     if (!empty($captchaConfigLoc)) {
         $captchaConfig = new Zend_Config_Ini($captchaConfigLoc, APPLICATION_ENV, false);
         if ($captchaConfig instanceof Zend_Config) {
             if (strtolower($captchaConfig->recaptcha->use) == 'on' && $this->_conditionallyUseCaptcha === false || strtolower($captchaConfig->recaptcha->use) == 'off') {
                 return;
             }
         } else {
             return;
         }
     } else {
         return;
     }
     // Recaptcha key pairs can be used at a single domain (and subdomains).
     // See if there are multiple key pairs (one per domain) and select the
     // correct pair. {@see matchDomianName}
     $keyConfig = null;
     foreach ($captchaConfig->recaptcha as $_ => $keypair) {
         if ($_ == 'use') {
             continue;
         }
         if (!isset($keypair->domain)) {
             ESAPI::getAuditor('Form_Contact')->error(Auditor::SECURITY, false, 'Misconfiguration in captcha.ini - missing domain name from key pair set - Captcha Not Initialised!');
             return;
         }
         if ($this->_matchDomainName($keypair->domain) === true) {
             $keyConfig = $keypair;
             break;
         }
     }
     if ($keyConfig instanceof Zend_Config === false) {
         ESAPI::getAuditor('Form_Contact')->error(Auditor::SECURITY, false, 'Misconfiguration in captcha.ini - could not find key pairs for this host - Captcha Not Initialised!');
         return;
     }
     $this->addElement(new Zend_Form_Element_Captcha('challenge', array('order' => 750, 'captcha' => 'ReCaptcha', 'captchaOptions' => array('captcha' => 'ReCaptcha', 'service' => new Zend_Service_ReCaptcha($keyConfig->publicKey, $keyConfig->privateKey)))));
 }
Esempio n. 12
0
    $util->killAllCookies($req);
    $view .= '<p>The response should have requested your User Agent to delete your cookies. Let us see if it will honour that request.';
    $view .= " <a href=\"{$uri}?req=test2\">click me!</a></p>";
} elseif ($req->getParameter('req') == 'test2') {
    $view .= '<p>Cookies received in that request: ';
    $view .= ESAPI::getEncoder()->encodeForHTML(print_r($req->getCookies(), true));
    $view .= '</p>';
    $view .= '<p>';
    if ($req->getCookie('testcookie') === null) {
        $view .= 'It worked! testcookie was not received in that request.';
    } else {
        $view .= 'It did not work. testcookie was received in that request.';
    }
    $view .= '</p>';
    $tests['cookie'] .= ' - DONE';
    $a = ESAPI::getAuditor('HTTPUtilsExtraTests');
    $log = $util->logHTTPRequest($req, $a);
    $logO = $util->logHTTPRequestObfuscate($req, $a, array('req'));
    $view .= '<p>Please check the ESAPI Auditor logfile for two INFO entries which log that request.  The second entry will contain the obfuscated "req" parameter.';
    $view .= '</p>';
    $tests['log'] .= ' - DONE';
    $tests['logo'] .= ' - DONE';
    session_destroy();
} else {
    $href = $util->addCSRFToken("{$uri}?req=test1");
    $view .= '<p>testcookie has been set with a value \'testcookieValue\'. now <a href="';
    $view .= $href;
    $view .= '">click me</a> to have it deleted. (Please ensure logging is on before you continue!)</p>';
    setcookie('testcookie', 'testcookieValue');
}
$view .= '<p>Under Test:</p>';
 /**
  * Validates the POST half of a double submit cookie against the COOKIE half
  * and both against string length and character set constraints.
  *
  * @param string $value The POST half of a double submit cookie from, for
  *                      example a hidden HTML form field.
  *
  * @return null
  */
 public function isValid($value)
 {
     $auditor = ESAPI::getAuditor('App_Validate_Token');
     $canonicalPostToken = ESAPI::getEncoder()->canonicalize($value, false);
     $this->_setValue($canonicalPostToken);
     $isValid = false;
     $v_len = new Zend_Validate_StringLength($this->_expectedLen, $this->_expectedLen);
     if ($v_len->isValid($canonicalPostToken) !== true) {
         $this->_error(self::POST_BAD_LENGTH);
         $auditor->warning(Auditor::SECURITY, false, $this->_messageTemplates[self::POST_BAD_LENGTH]);
         return false;
     }
     $v_regex = new Custom_Validate_Charset($this->_expectedCharset);
     if ($v_regex->isValid($canonicalPostToken) !== true) {
         $this->_error(self::POST_BAD_CHARSET);
         $auditor->warning(Auditor::SECURITY, false, $this->_messageTemplates[self::POST_BAD_CHARSET]);
         return false;
     }
     $controller = Zend_Controller_Front::getInstance();
     $req = $controller->getRequest();
     $cookieVal = $req->getCookie($this->_cookieName);
     $canonicalCookie = ESAPI::getEncoder()->canonicalize($cookieVal, false);
     if ($canonicalCookie === null) {
         $this->_error(self::MISSING_COOKIE);
         $auditor->warning(Auditor::SECURITY, false, $this->_messageTemplates[self::MISSING_COOKIE]);
         return false;
     }
     if ($v_len->isValid($canonicalCookie) !== true) {
         $this->_error(self::COOKIE_BAD_LENGTH);
         $auditor->warning(Auditor::SECURITY, false, $this->_messageTemplates[self::COOKIE_BAD_LENGTH]);
         return false;
     }
     if ($v_regex->isValid($canonicalCookie) !== true) {
         $this->_error(self::COOKIE_BAD_CHARSET);
         $auditor->warning(Auditor::SECURITY, false, $this->_messageTemplates[self::COOKIE_BAD_CHARSET]);
         return false;
     }
     $v_identical = new Zend_Validate_Identical($this->_value);
     if ($v_identical->isValid($canonicalCookie) !== true) {
         $this->_error(self::TOKENS_DIFFER);
         $auditor->warning(Auditor::SECURITY, false, $this->_messageTemplates[self::TOKENS_DIFFER]);
         return false;
     }
     return true;
 }
Esempio n. 14
0
 /**
  * Encoder constructor.
  *
  * @param array $codecs An array of Codec instances which will be used for
  *                      canonicalization.
  *
  * @throws InvalidArgumentException
  *
  * @return does not return a value.
  */
 public function __construct($codecs = null)
 {
     $this->logger = ESAPI::getAuditor("Encoder");
     // initialise codecs
     $this->_base64Codec = new Base64Codec();
     $this->_cssCodec = new CSSCodec();
     $this->_htmlCodec = new HTMLEntityCodec();
     $this->_javascriptCodec = new JavaScriptCodec();
     $this->_percentCodec = new PercentCodec();
     $this->_vbscriptCodec = new VBScriptCodec();
     $this->_xmlCodec = new XMLEntityCodec();
     // initialise array of codecs for use by canonicalize
     if ($codecs === null) {
         array_push($this->_codecs, $this->_htmlCodec);
         array_push($this->_codecs, $this->_javascriptCodec);
         array_push($this->_codecs, $this->_percentCodec);
         // leaving css and vbs codecs out - they eat / and " chars respectively
         // array_push($this->_codecs,$this->_cssCodec);
         // array_push($this->_codecs,$this->_vbscriptCodec);
     } elseif (!is_array($codecs)) {
         throw new InvalidArgumentException('Expected the $codecs array parameter to be an array of instances of Codec.');
     } else {
         // check array contains only codec instances
         foreach ($codecs as $codec) {
             if ($codec instanceof Codec == false) {
                 throw new InvalidArgumentException('Expected every member of the $codecs array parameter to be an instance of Codec.');
             }
         }
         $this->_codecs = array_merge($this->_codecs, $codecs);
     }
 }
Esempio n. 15
0
 /**
  * SafeRequest can be forced to use the supplied cookies, headers and server
  * globals by passing an array containing the following keys: 'cookies',
  * 'headers', 'env'.  The values for each of the keys should be an associative
  * array e.g. 'headers' => array('REQUEST_METHOD' => 'GET').
  * If any of the three options keys are not supplied then those elements will be
  * extracted from the actual request.
  * TODO accept a string like: 'GET / HTTP/1.1\r\nHost:example.com\r\n\r\n'
  * TODO accept GET and REQUEST parameters.
  *
  * @param NULL|array $options Array (optional) of HTTP Request elements.
  */
 public function __construct($options = null)
 {
     $codecs = array(new HTMLEntityCodec(), new PercentCodec());
     $this->_encoder = new DefaultEncoder($codecs);
     $this->_auditor = ESAPI::getAuditor('SafeRequest');
     $this->_validator = ESAPI::getValidator();
     if ($options !== null && is_array($options)) {
         if (array_key_exists('cookies', $options)) {
             $this->_cookies = $this->_validateCookies($options['cookies']);
         }
         if (array_key_exists('headers', $options)) {
             $this->_headers = $this->_validateHeaders($options['headers']);
         }
         if (array_key_exists('env', $options)) {
             $this->_serverGlobals = $this->_canonicalizeServerGlobals($options['env']);
         }
     }
 }
Esempio n. 16
0
 /**
  * Executor constructor.
  *
  * @return does not return a value.
  */
 public function __construct()
 {
     $this->_auditor = ESAPI::getAuditor('Executor');
     $this->_config = ESAPI::getSecurityConfiguration();
 }
 /**
  * Validates the input string against a list of valid recipients.
  *
  * @param string $input The input to be validated as a recipient.
  *
  * @return bool True if input string is a valid recipient, otherwise
  *              False.
  */
 public function isValid($input)
 {
     $auditor = ESAPI::getAuditor('App_Validate_Recipient');
     if (!is_string($input)) {
         $auditor->warning(Auditor::SECURITY, false, 'isValid expects a string!');
         $this->_error(self::INVALID);
         return false;
     }
     if ($this->_recipients instanceof Zend_Config !== true) {
         $this->_error(self::INVALID_RECIPIENT);
         $auditor->warning(Auditor::SECURITY, false, 'isValid requires an array of recipients!');
         return false;
     }
     $encoder = ESAPI::getEncoder();
     // canonicalise the input string.
     $canonical = null;
     try {
         $canonical = $encoder->canonicalize($input, true);
     } catch (Exception $e) {
         // Process the input no further.
         $this->_error(self::INVALID_RECIPIENT);
         $auditor->warning(Auditor::SECURITY, false, 'isValid rejected a string in which double or mixed encoding was detected.', $e);
         return false;
     }
     // Convert input to lower case
     $charEnc = mb_detect_encoding($canonical);
     $canonicalLower = mb_strtolower($canonical, $charEnc);
     // Get a whitespace removal filter
     $whitespace = new Zend_Filter_PregReplace(array('match' => '/ /', 'replace' => ''));
     // for each of our valid recipients use an identical validator
     // to determine whether $canonical matches.
     $validator = new Zend_Validate_Identical();
     foreach ($this->_recipients as $_ => $cfg) {
         foreach ($cfg as $key => $validRecipient) {
             if ($key !== 'display') {
                 continue;
             }
             $charEnc = mb_detect_encoding($validRecipient . '');
             $validRecipientL = mb_strtolower($validRecipient, $charEnc);
             $validRecipientS = $whitespace->filter($validRecipientL);
             $validator->setToken($validRecipientL);
             if ($validator->isValid($canonicalLower)) {
                 return true;
             }
             $validator->setToken($validRecipientS);
             if ($validator->isValid($canonicalLower)) {
                 return true;
             }
         }
     }
     // if that fails, the form has been tampered with or a dummy option has
     // been selected - check for the latter of these now:
     foreach ($this->_dummyRecipients as $dummy => $value) {
         $charEnc = mb_detect_encoding($dummy . '');
         $dummyL = mb_strtolower($dummy, $charEnc);
         $dummyS = $whitespace->filter($dummyL);
         $validator->setToken($dummyL);
         if ($validator->isValid($canonicalLower)) {
             $this->_error(self::DUMMY_RECIPIENT);
             return false;
         }
         $validator->setToken($dummyS);
         if ($validator->isValid($canonicalLower)) {
             $this->_error(self::DUMMY_RECIPIENT);
             return false;
         }
     }
     $auditor->warning(Auditor::SECURITY, false, "isValid. Input [{$canonicalLower}] is not a valid recipient.");
     $this->_error(self::INVALID_RECIPIENT);
     return false;
 }
Esempio n. 18
0
 public function testSetLevelMultipleLogsExpectedTrue()
 {
     //Now test to see if a change to the logging level in one log affects other logs
     $newLogger = ESAPI::getAuditor('test_num2');
     $this->testLogger->setLevel(Auditor::OFF);
     $newLogger->setLevel(Auditor::INFO);
     $log_1_result = $this->testLogger->isInfoEnabled();
     $log_2_result = $newLogger->isInfoEnabled();
     $this->assertTrue(!$log_1_result && $log_2_result);
 }
Esempio n. 19
0
 /**
  * Public Constructor
  */
 function __construct()
 {
     $logger = ESAPI::getAuditor("Base64");
 }
 /**
  * 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);
 }
 * 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();
 /**
  * Validator constructor.
  *
  * @return does not return a value.
  */
 public function __construct()
 {
     global $ESAPI;
     $this->_auditor = ESAPI::getAuditor('DefaultValidator');
     $this->_encoder = ESAPI::getEncoder();
 }
 /**
  * Initialises logging.
  *
  * @return null
  */
 public function __construct()
 {
     $this->_auditor = ESAPI::getAuditor('App_Helper_SendMail');
 }