/**
  * Calls ESAPI to generate a random token which is then set as a hidden form
  * field and sent to the client as a cookie.
  *
  * @return null
  */
 public function setCSRFToken()
 {
     $this->_tokenValue = ESAPI::getRandomizer()->getRandomString($this->_tokenLength, $this->_tokenCharset);
     // set the form element value
     $this->token->setValue($this->_tokenValue);
     // set the token cookie
     setcookie(self::CSRFCOOKIE, "{$this->_tokenValue}", '0', PUBLIC_ROOT . 'send', '', false, false);
 }
 /**
  * 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;
 }
Exemplo n.º 3
0
 /**
  * Helper function.
  *
  * If the supplied logging level is at or above the current logging
  * threshold then log the message after optionally encoding any special
  * characters that might be dangerous when viewed by an HTML based log
  * viewer. Also encode any carriage returns and line feeds to prevent log
  * injection attacks. This logs all the supplied parameters: level, event
  * type, whether the event represents success or failure and the log
  * message. In addition, the application name, logger name/category, local
  * IP address and port, the identity of the user and their source IP
  * address, a logging specific user session ID, and the current date/time
  * are also logged.
  * If the supplied logging level is below the current logging threshold then
  * the message will be discarded.
  *
  * @param int       $level     the priority level of the event - an Logger Level
  *                             constant.
  * @param int       $type      the type of the event - an Logger Event constant.
  * @param bool      $success   TRUE indicates this was a successful
  *                             event, FALSE indicates this was a failed event
  *                             (the typical value).
  * @param string    $message   the message to be logged.
  * @param Exception $throwable The throwable Exception.
  *
  * @return does not return a value.
  */
 private function _log($level, $type, $success, $message, $throwable)
 {
     // If this log level is below the threshold we can quit now.
     $logLevel = self::_convertESAPILeveltoLoggerLevel($level);
     if (!$this->_log4php->isEnabledFor($logLevel)) {
         return;
     }
     $encoder = ESAPI::getEncoder();
     $secConfig = ESAPI::getSecurityConfiguration();
     // Add some context to log the message.
     $context = '';
     // The output of log level is handled here instead of providing a
     // LayoutPattern to Log4PHP.  This allows us to print TRACE instead of
     // ALL and WARNING instead of WARN.
     $levelStr = $logLevel->toString();
     if ($levelStr == 'ALL') {
         $levelStr = 'TRACE';
     } elseif ($levelStr == 'WARN') {
         $levelStr = 'WARNING';
     }
     $context .= $levelStr;
     // Application name.
     // $this->appName is set only if it is to be logged.
     if ($this->_appName !== null) {
         $context .= ' ' . $this->_appName;
     }
     // Logger name (Category in Log4PHP parlance)
     $context .= ' ' . $this->_log4phpName;
     // Event Type
     if (!is_string($type)) {
         $type = 'EVENT_UNKNOWN';
     }
     $context .= ' ' . $type;
     // Success or Failure of Event
     if ($success === true) {
         $context .= '-SUCCESS';
     } else {
         $context .= '-FAILURE';
     }
     $request = ESAPI::getHttpUtilities()->getCurrentRequest();
     if ($request === null) {
         $request = new SafeRequest();
         ESAPI::getHttpUtilities()->setCurrentHTTP($request);
     }
     $laddr = $request->getServerName();
     if ($laddr === '') {
         $laddr = 'UnknownLocalHost';
     }
     $lport = $request->getServerPort();
     $ruser = $request->getRemoteUser();
     if ($ruser === '') {
         $ruser = '******';
     }
     $raddr = $request->getRemoteAddr();
     if ($raddr === '') {
         $raddr = 'UnknownRemoteHost';
     }
     $context .= " {$laddr}:{$lport} {$ruser}@{$raddr}";
     // create a random session number for the user to represent the
     // user's session, if it doesn't exist already
     $userSessionIDforLogging = 'SessionUnknown';
     if (isset($_SESSION)) {
         if (isset($_SESSION['DefaultAuditor']) && isset($_SESSION['DefaultAuditor']['SessionIDForLogging'])) {
             $userSessionIDforLogging = $_SESSION['DefaultAuditor']['SessionIDForLogging'];
         } else {
             try {
                 $userSessionIDforLogging = (string) ESAPI::getRandomizer()->getRandomInteger(0, 1000000);
                 $_SESSION['DefaultAuditor']['SessionIDForLogging'] = $userSessionIDforLogging;
             } catch (Exception $e) {
                 // continue
             }
         }
     }
     $context .= "[ID:{$userSessionIDforLogging}]";
     // Now comes the message.
     if (!is_string($message)) {
         $message = '';
     }
     // Encode CRLF - this bit might have to go in a try block
     // Codec Debugging entries are not affected.
     if (defined('CD_LOG') == true && $this->_log4phpName === CD_LOG) {
         $crlfEncoded = $message;
     } else {
         $crlfEncoded = $this->_replaceCRLF($message, '_');
     }
     // Encode for HTML if ESAPI.xml says so
     $encodedMessage = null;
     if ($secConfig->getLogEncodingRequired()) {
         try {
             $encodedMessage = $encoder->encodeForHTML($crlfEncoded);
             if ($encodedMessage !== $crlfEncoded) {
                 $encodedMessage .= ' (This log message was encoded for HTML)';
             }
         } catch (Exception $e) {
             $exType = get_type($e);
             $encodedMessage = "The supplied log message generated an " . "Exception of type {$exType} and was not included";
         }
     } else {
         $encodedMessage = $crlfEncoded;
     }
     // Now handle the exception
     $dumpedException = '';
     if ($throwable !== null && $throwable instanceof Exception) {
         $dumpedException = ' ' . $this->_replaceCRLF($throwable, ' | ');
     }
     $messageForLog = $context . ' ' . $encodedMessage . $dumpedException;
     $this->_log4php->log($logLevel, $messageForLog, $this);
 }
Exemplo n.º 4
0
 /**
  * Sets the CSRF Token for the current session.  If the session has not been
  * started at the time this method is called then the token will not be
  * generated.
  */
 public function setCSRFToken()
 {
     if (!isset($_SESSION)) {
         return null;
     }
     if (!array_key_exists('ESAPI', $_SESSION)) {
         $_SESSION['ESAPI'] = array('HTTPUtilities' => array('CSRFToken' => ''));
     } elseif (!array_key_exists('HTTPUtilities', $_SESSION['ESAPI'])) {
         $_SESSION['ESAPI']['HTTPUtilities'] = array('CSRFToken' => '');
     }
     $_SESSION['ESAPI']['HTTPUtilities']['CSRFToken'] = ESAPI::getRandomizer()->getRandomGUID();
 }
 /**
  * Generate strong password that takes into account the user's information and old password. Implementations
  * should verify that the new password does not include information such as the username, fragments of the
  * old password, and other information that could be used to weaken the strength of the password.
  *
  * @param user
  * 		the user whose information to use when generating password
  * @param oldPassword
  * 		the old password to use when verifying strength of new password.  The new password may be checked for fragments of oldPassword.
  *
  * @return
  * 		a password with strong password strength
  */
 function generateStrongPassword($user = null, $oldPassword = null)
 {
     $randomizer = ESAPI::getRandomizer();
     $letters = $randomizer->getRandomInteger(4, 6);
     $digits = 7 - $letters;
     $passLetters = $randomizer->getRandomString($letters, DefaultEncoder::CHAR_PASSWORD_LETTERS);
     $passDigits = $randomizer->getRandomString($digits, DefaultEncoder::CHAR_PASSWORD_DIGITS);
     $passSpecial = $randomizer->getRandomString(1, DefaultEncoder::CHAR_PASSWORD_SPECIALS);
     $newPassword = $passLetters . $passSpecial . $passDigits;
     if ($this->isValidString($newPassword) && $this->isValidString($user)) {
         $this->logger->info(ESAPILogger::SECURITY, TRUE, "Generated strong password for " . $user->getAccountName());
     }
     return $newPassword;
 }
Exemplo n.º 6
0
 public function __construct($accountName)
 {
     $this->setAccountName($accountName);
     //TODO: Not the best way IMHO. I'd rather call the method via factory object each time. Needs discussion..
     $this->IDLE_TIMEOUT_LENGTH = ESAPI::getSecurityConfiguration()->getSessionIdleTimeoutLength();
     $this->ABSOLUTE_TIMEOUT_LENGTH = ESAPI::getSecurityConfiguration()->getSessionAbsoluteTimeoutLength();
     do {
         $id = ESAPI::getRandomizer()->getRandomLong();
         if (ESAPI::getAuthenticator()->getUserById($id) == null && $id != 0) {
             $this->setAccountID($id);
         }
     } while ($this->getAccountID() == 0);
 }
Exemplo n.º 7
0
/**
 * 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);
}
Exemplo n.º 8
0
 /**
  * Test of decodeFromBase64 method, of class Encoder.
  */
 public function testDecodeFromBase64()
 {
     $instance = ESAPI::getEncoder();
     for ($i = 0; $i < 100; $i++) {
         try {
             $unencoded = ESAPI::getRandomizer()->getRandomString(20, Encoder::CHAR_SPECIALS);
             $encoded = $instance->encodeForBase64($unencoded, ESAPI::getRandomizer()->getRandomBoolean());
             $decoded = $instance->decodeFromBase64($encoded);
             $this->assertEquals($unencoded, $decoded);
         } catch (Exception $unexpected) {
             $this->fail();
         }
     }
     for ($i = 0; $i < 100; $i++) {
         try {
             // get a string of 20 char_specials.
             $unencoded = ESAPI::getRandomizer()->getRandomString(20, Encoder::CHAR_SPECIALS);
             // encode the string of char_specials and then prepend an alplanum
             $encoded = ESAPI::getRandomizer()->getRandomString(1, Encoder::CHAR_ALPHANUMERICS) . $instance->encodeForBase64($unencoded, ESAPI::getRandomizer()->getRandomBoolean());
             // decoding the encoded (and prepended to) string
             $decoded = $instance->decodeFromBase64($encoded);
             // the decoded result should not equal the original string of 20 char_specials.
             $this->assertNotEquals($unencoded, $decoded);
         } catch (Exception $unexpected) {
             $this->fail();
             // Note: java expects an IO exception, but base64_decode() doesn't throw one
         }
     }
     // Test decode single character
     $this->assertEquals('', $instance->decodeFromBase64('0'));
     $this->assertEquals('', $instance->decodeFromBase64('1'));
     $this->assertEquals('', $instance->decodeFromBase64('a'));
     $this->assertEquals('', $instance->decodeFromBase64('A'));
     $this->assertEquals('', $instance->decodeFromBase64('\\'));
     $this->assertEquals('', $instance->decodeFromBase64('+'));
     $this->assertEquals('', $instance->decodeFromBase64('='));
     $this->assertEquals('', $instance->decodeFromBase64('-'));
 }
Exemplo n.º 9
0
 * ------------------------------------------ */
/*
if (!is_object($_SESSION["Objects"]["ESAPIHandler"])){
	$_SESSION["Objects"]["ESAPIHandler"] = new ESAPI(__ROOT__.'/owasp-esapi-php/src/ESAPI.xml');
	$_SESSION["Objects"]["ESAPIEncoder"] = $_SESSION["Objects"]["ESAPIHandler"]->getEncoder();
	$_SESSION["Objects"]["ESAPIRandomizer"] = $_SESSION["Objects"]["ESAPIHandler"]->getRandomizer();
}// end if

// Set up an alias by reference so object can be referenced in memory without copying
$ESAPI = &$_SESSION["Objects"]["ESAPIHandler"];
$Encoder = &$_SESSION["Objects"]["ESAPIEncoder"];
$ESAPIRandomizer = &$_SESSION["Objects"]["ESAPIRandomizer"];
*/
$ESAPI = new ESAPI(__ROOT__ . '/owasp-esapi-php/src/ESAPI.xml');
$Encoder = $ESAPI->getEncoder();
$ESAPIRandomizer = $ESAPI->getRandomizer();
/* ------------------------------------------
 * Test for database availability
 * ------------------------------------------ */
function handleError($errno, $errstr, $errfile, $errline, array $errcontext)
{
    /*
    restore_error_handler();
    restore_exception_handler();
    header("Location: database-offline.php", true, 302);
    exit();
    */
}
// end function
function handleException($exception)
{
Exemplo n.º 10
0
 function testGetRandomFilenameLengthWithExtension()
 {
     $instance = ESAPI::getRandomizer();
     $result = $instance->getRandomFilename('.php');
     $this->assertEquals(20, strlen($result));
 }