/** * Decrypt data. * * @param array $keys That must be an array that contains private and public keys. * @param mixed $data Encrypted data that has to be decrypted. * * @return mixed */ public static function decrypt(array $keys, $data) { $chiper = new JCryptCipherRijndael256(); $key = new JCryptKey("rijndael256", $keys["private"], $keys["public"]); $crypt = new JCrypt($chiper, $key); return $crypt->decrypt($data); }
/** * Run when a membership activated * @param PlanOsMembership $row */ function onMembershipActive($row) { if (!$row->user_id && $row->username && $row->user_password) { //Need to create the account here $data['name'] = trim($row->first_name . ' ' . $row->last_name); //Decrypt the password $data['username'] = $row->username; //Password $privateKey = md5(JFactory::getConfig()->get('secret')); $key = new JCryptKey('simple', $privateKey, $privateKey); $crypt = new JCrypt(new JCryptCipherSimple(), $key); $data['password'] = $data['password2'] = $data['password'] = $crypt->decrypt($row->user_password); $data['email1'] = $data['email2'] = $data['email'] = $row->email; $params = JComponentHelper::getParams('com_users'); $data['groups'] = array(); $data['groups'][] = $params->get('new_usertype', 2); $user = new JUser(); if (!$user->bind($data)) { return false; } // Store the data. if (!$user->save()) { return false; } $row->user_id = $user->get('id'); $row->store(); } }
function onAfterInitialise() { $app = JFactory::getApplication(); // No remember me for admin if ($app->isAdmin()) { return; } $user = JFactory::getUser(); if ($user->get('guest')) { $hash = JApplication::getHash('JLOGIN_REMEMBER'); if ($str = JRequest::getString($hash, '', 'cookie', JREQUEST_ALLOWRAW | JREQUEST_NOTRIM)) { jimport('joomla.utilities.simplecrypt'); $credentials = array(); $goodCookie = true; $filter = JFilterInput::getInstance(); // Create the encryption key, apply extra hardening using the user agent string. // Since we're decoding, no UA validity check is required. $privateKey = JApplication::getHash(@$_SERVER['HTTP_USER_AGENT']); $key = new JCryptKey('simple', $privateKey, $privateKey); $crypt = new JCrypt(new JCryptCipherSimple(), $key); try { $str = $crypt->decrypt($str); if (!is_string($str)) { throw new Exception('Decoded cookie is not a string.'); } $cookieData = json_decode($str); if (null === $cookieData) { throw new Exception('JSON could not be docoded.'); } if (!is_object($cookieData)) { throw new Exception('Decoded JSON is not an object.'); } // json_decoded cookie could be any object structure, so make sure the // credentials are well structured and only have user and password. if (isset($cookieData->username) && is_string($cookieData->username)) { $credentials['username'] = $filter->clean($cookieData->username, 'username'); } else { throw new Exception('Malformed username.'); } if (isset($cookieData->password) && is_string($cookieData->password)) { $credentials['password'] = $filter->clean($cookieData->password, 'string'); } else { throw new Exception('Malformed password.'); } $return = $app->login($credentials, array('silent' => true)); if (!$return) { throw new Exception('Log-in failed.'); } } catch (Exception $e) { $config = JFactory::getConfig(); $cookie_domain = $config->get('cookie_domain', ''); $cookie_path = $config->get('cookie_path', '/'); // Clear the remember me cookie setcookie(JApplication::getHash('JLOGIN_REMEMBER'), false, time() - 86400, $cookie_path, $cookie_domain); JLog::add('A remember me cookie was unset for the following reason: ' . $e->getMessage(), JLog::WARNING, 'security'); } } } }
function onAfterInitialise() { $app = JFactory::getApplication(); // No remember me for admin if ($app->isAdmin()) { return; } $user = JFactory::getUser(); if ($user->get('guest')) { $hash = JApplication::getHash('JLOGIN_REMEMBER'); if ($str = JRequest::getString($hash, '', 'cookie', JREQUEST_ALLOWRAW | JREQUEST_NOTRIM)) { jimport('joomla.utilities.simplecrypt'); // Create the encryption key, apply extra hardening using the user agent string. // Since we're decoding, no UA validity check is required. $privateKey = JApplication::getHash(@$_SERVER['HTTP_USER_AGENT']); $key = new JCryptKey('simple', $privateKey, $privateKey); $crypt = new JCrypt(new JCryptCipherSimple(), $key); $str = $crypt->decrypt($str); $cookieData = @unserialize($str); // Deserialized cookie could be any object structure, so make sure the // credentials are well structured and only have user and password. $credentials = array(); $filter = JFilterInput::getInstance(); $goodCookie = true; if (is_array($credentials)) { if (isset($cookieData['username']) && is_string($cookieData['username'])) { $credentials['username'] = $filter->clean($cookieData['username'], 'username'); } else { $goodCookie = false; } if (isset($cookieData['password']) && is_string($cookieData['password'])) { $credentials['password'] = $filter->clean($cookieData['password'], 'string'); } else { $goodCookie = false; } } else { $goodCookie = false; } if (!$goodCookie || !$app->login($credentials, array('silent' => true))) { $config = JFactory::getConfig(); $cookie_domain = $config->get('cookie_domain', ''); $cookie_path = $config->get('cookie_path', '/'); // Clear the remember me cookie setcookie(JApplication::getHash('JLOGIN_REMEMBER'), false, time() - 86400, $cookie_path, $cookie_domain); } } } }
/** * @covers JCrypt::genRandomBytes */ public function testGenRandomBytes() { // We're just testing wether the value has the expected length, // we obviously can't test the result since it's random. $randomBytes16 = JCrypt::genRandomBytes(); $this->assertEquals(strlen($randomBytes16), 16); $randomBytes8 = JCrypt::genRandomBytes(8); $this->assertEquals(strlen($randomBytes8), 8); $randomBytes17 = JCrypt::genRandomBytes(17); $this->assertEquals(strlen($randomBytes17), 17); }
/** * @testdox Validates keys are correctly generated * * @covers JCryptCipherCrypto::generateKey */ public function testGenerateKey() { $cipher = new JCryptCipherCrypto(); $key = $cipher->generateKey(); // Assert that the key is the correct type. $this->assertInstanceOf('JCryptKey', $key); // Assert the private key is our expected value. $this->assertSame('unused', $key->private); // Assert the public key is the expected length $this->assertSame(Crypto::KEY_BYTE_SIZE, JCrypt::safeStrlen($key->public)); // Assert the key is of the correct type. $this->assertAttributeEquals('crypto', 'type', $key); }
protected static function generateKey() { jimport('joomla.crypt.crypt'); $key = JCrypt::genRandomBytes(32); $salt = md5_file(JPATH_SITE . '/configuration.php'); $key = base64_encode(self::pbkdf2($key, $salt, 32)); $filecontents = "<?php defined('WF_EDITOR') or die(); define('WF_SERVERKEY', '{$key}'); ?>"; $filename = JPATH_COMPONENT_ADMINISTRATOR . '/serverkey.php'; $result = JFile::write($filename, $filecontents); if (!$result) { return ''; } else { return base64_decode($key); } }
/** * CURL-wrapper * * @param string $url * @param string $type * @param array $arguments * @param boolean @run_bridge * * @return string */ public function getCURL($url, $type = 'get', $arguments = null, $runBridge = false) { // Load variables $httpHeaders = array(); // Initialize CURL $handle = curl_init($url); if ($handle == false) { return null; } curl_setopt_array($handle, $this->getCurlDefaultArguments()); $this->setCurlHeaders($handle); $this->setCurlHttpAuthentication($handle); // Forward cookies to Magento if ($runBridge == true) { $this->setCurlCookies($handle); } // Detect whether certain HTTP headers are set by the client foreach ($_SERVER as $header => $value) { if (!preg_match('/^http_/i', $header)) { continue; } $header = strtoupper(preg_replace('/http_/i', '', $header)); if ($header == 'X_REQUESTED_WITH') { $httpHeaders[] = 'X-REQUESTED-WITH' . ': ' . $value; } else { if (preg_match('/^ACCEPT_/', $header)) { $httpHeaders[] = str_replace('_', '-', $header) . ': ' . $value; } } } // Add proxy HTTP headers if (isset($_SERVER['REMOTE_ADDR'])) { $httpHeaders[] = 'X-REAL-IP: ' . $_SERVER['REMOTE_ADDR']; } if (isset($_SERVER['REMOTE_ADDR'])) { $httpHeaders[] = 'X-FORWARDED-FOR: ' . $_SERVER['REMOTE_ADDR']; } if (isset($_SERVER['SERVER_ADDR'])) { $httpHeaders[] = 'VIA: ' . $_SERVER['SERVER_ADDR']; } // Set SSL options $uri = JURI::getInstance(); if ($uri->isSSL() == true) { $httpHeaders[] = 'FRONT-END-HTTPS: On'; } if ($uri->isSSL() == true) { $httpHeaders[] = 'X-FORWARD-PROTO: https'; } // Add some extra HTTP headers for HTTP Keep Alive if (MagebridgeModelConfig::load('keep_alive') == 0) { $httpHeaders[] = 'Connection: close'; } else { $httpHeaders[] = 'Connection: keep-alive'; } // Spoof the browser if (MagebridgeModelConfig::load('spoof_browser') == 1) { if ($runBridge == true && $this->app->isSite() == 1) { curl_setopt($handle, CURLOPT_REFERER, MageBridgeUrlHelper::getRequest()); curl_setopt($handle, CURLOPT_USERAGENT, isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ''); } else { curl_setopt($handle, CURLOPT_USERAGENT, $this->getUserAgentBySystem()); } } // Automatically handle file uploads $tmp_files = $this->helper->upload(); if (!empty($tmp_files)) { foreach ($tmp_files as $name => $tmp_file) { if (class_exists('CurlFile')) { $arguments[$name] = new CurlFile($tmp_file['tmp_name'], $tmp_file['type']); } else { $arguments[$name] = '@' . $tmp_file['tmp_name']; } } } // Set extra options when a POST is handled if ($type == 'post') { $arguments = is_array($arguments) && MagebridgeModelConfig::load('curl_post_as_array') == 0 ? http_build_query($arguments) : $arguments; curl_setopt($handle, CURLOPT_POST, true); curl_setopt($handle, CURLOPT_POSTFIELDS, $arguments); $httpHeaders[] = 'Expect:'; //print_r($arguments);exit; } // Add the HTTP headers curl_setopt($handle, CURLOPT_HTTPHEADER, $httpHeaders); // Set encoding to zero curl_setopt($handle, CURLOPT_ENCODING, ''); // Handle direct output and bridge output $this->debug->notice('CURL init: ' . $url . ' (' . (MageBridgeUrlHelper::getRequest() ? MageBridgeUrlHelper::getRequest() : 'no request') . ')'); $this->handleFileDownloads($handle); $data = curl_exec($handle); $size = YireoHelper::strlen($data); if ($size > 1024) { $size = round($size / 1024, 2) . 'Kb'; } $this->debug->profiler('CURL response size: ' . $size); // Cleanup the temporary uploads $this->helper->cleanup($tmp_files); // Separate the headers from the body $this->head['header_found'] = false; $this->head['last_url'] = curl_getinfo($handle, CURLINFO_EFFECTIVE_URL); $this->head['http_code'] = curl_getinfo($handle, CURLINFO_HTTP_CODE); $this->head['size'] = curl_getinfo($handle, CURLINFO_HEADER_SIZE); $this->head['info'] = curl_getinfo($handle); // Determine the separator $separator = null; if (strpos($data, "\r\n\r\n") > 0) { $separator = "\r\n\r\n"; } elseif (strpos($data, "\n\n") > 0) { $separator = "\n\n"; } // Split data into segments if (strpos($data, $separator) > 0) { $dataSegments = explode($separator, $data); $this->head['header_found'] = true; foreach ($dataSegments as $dataSegmentIndex => $dataSegment) { // Check for a segment that seems to contain HTTP-headers if (preg_match('/(Set-Cookie|Content-Type|Transfer-Encoding):/', $dataSegment)) { // Get this segment $this->head['headers'] = trim($dataSegment); // Use the remaining segments for the body unset($dataSegments[$dataSegmentIndex]); $this->body = implode("\r\n", $dataSegments); break; } // Only allow for a body after a header (and ignore double headers) unset($dataSegments[$dataSegmentIndex]); } } // Exit when no proper headers have been found if ($this->head['header_found'] == false) { $this->debug->warning('CURL contains no HTTP headers'); return null; } if (empty($this->head['http_code'])) { $this->head['http_code'] = 200; } // Statistics $this->debug->profiler('CURL total time: ' . round(curl_getinfo($handle, CURLINFO_TOTAL_TIME), 4) . ' seconds'); $this->debug->profiler('CURL connect time: ' . round(curl_getinfo($handle, CURLINFO_CONNECT_TIME), 4) . ' seconds'); $this->debug->profiler('CURL DNS-time: ' . round(curl_getinfo($handle, CURLINFO_NAMELOOKUP_TIME), 4) . ' seconds'); $this->debug->profiler('CURL download speed: ' . round(curl_getinfo($handle, CURLINFO_SPEED_DOWNLOAD * 8 / 1024), 4) . ' Kb/s'); //$this->debug->trace( "CURL information", curl_getinfo($handle)); //$this->debug->trace( "HTTP headers", $this->head ); //$this->debug->trace( "HTTP body", $this->body ); // Handle MageBridge HTTP-messaging if (preg_match_all('/X-MageBridge-(Notice|Error|Warning): ([^\\s]+)/', $this->head['headers'], $matches)) { foreach ($matches[0] as $index => $match) { $type = $matches[1][$index]; $message = $matches[2][$index]; if (!empty($type) && !empty($message)) { $message = base64_decode($message); $this->app->enqueueMessage($message, $type); } } } // Process the X-MageBridge-Customer header if ($this->getHeader('X-MageBridge-Customer') != null) { $value = $this->getHeader('X-MageBridge-Customer'); MageBridgeModelBridge::getInstance()->addSessionData('customer/email', $value); MageBridgeModelUser::getInstance()->postlogin($value, null, true, true); } // Process the X-MageBridge-Form-Key header if ($this->getHeader('X-MageBridge-Form-Key') != null) { $value = $this->getHeader('X-MageBridge-Form-Key'); MageBridgeModelBridge::getInstance()->addSessionData('form_key', $value); } // Log other Status Codes than 200 if ($this->head['http_code'] != 200) { if ($this->head['http_code'] == 500) { $this->debug->error('CURL received HTTP status ' . $this->head['http_code']); } else { $this->debug->warning('CURL received HTTP status ' . $this->head['http_code']); } } // If we receive status 0, log it if ($this->head['http_code'] == 0) { $this->head['http_error'] = curl_error($handle); $this->debug->trace('CURL error', curl_error($handle)); } // If we receive an exception, exit the bridge if ($this->head['http_code'] == 0 || $this->head['http_code'] == 500) { $this->init = self::CONNECTION_ERROR; $this->state = 'INTERNAL ERROR'; curl_close($handle); return $this->body; } // If we receive a 404, log it if ($this->head['http_code'] == 404) { $this->init = self::CONNECTION_ERROR; $this->state = '404 NOT FOUND'; curl_close($handle); if ($this->app->isSite() == 1 && MagebridgeModelConfig::load('enable_notfound') == 1) { JError::raiseError(404, JText::_('Page Not Found')); return null; } else { header('HTTP/1.0 404 Not Found'); return $this->body; } } // If we have an empty body, log it if (empty($this->body)) { $this->debug->warning('CURL received empty body'); if (!empty($this->head['headers'])) { $this->debug->trace('CURL headers', $this->head['headers']); } } // Define which cookies to spoof $cookies = MageBridgeBridgeHelper::getBridgableCookies(); $defaultSessionName = ini_get('session.name'); if (empty($defaultSessionName)) { $defaultSessionName = 'PHPSESSID'; } $cookies[] = $defaultSessionName; // Add the default session for sake of badly written Magento extensions // Handle cookies if (MagebridgeModelConfig::load('bridge_cookie_all') == 1) { preg_match_all('/Set-Cookie: ([a-zA-Z0-9\\-\\_\\.]+)\\=(.*)/', $this->head['headers'], $matches); } else { preg_match_all('/Set-Cookie: (' . implode('|', $cookies) . ')\\=(.*)/', $this->head['headers'], $matches); } // Loop through the matches if (!empty($matches)) { $matchedCookies = array(); foreach ($matches[0] as $index => $match) { // Extract the cookie-information $cookieName = $matches[1][$index]; $cookieValue = $matches[2][$index]; // Strip the meta-data from the cookie if (preg_match('/^([^\\;]+)\\;(.*)/', $cookieValue, $cookieValueMatch)) { $cookieValue = $cookieValueMatch[1]; } // Trim the cookie $cookieValue = trim($cookieValue); // Check if the cookie was dealt with or not if (in_array($cookieName, $matchedCookies)) { continue; } else { $matchedCookies[] = $cookieName; } // Set the cookie if (!headers_sent()) { if ($cookieName == 'persistent_shopping_cart' && isset($matches[3][$index]) && preg_match('/expires=([^\\;]+)/', $matches[3][$index], $paramsMatch)) { $expires = strtotime($paramsMatch[1]); } else { $expires = 0; } setcookie($cookieName, $cookieValue, $expires, '/', '.' . JURI::getInstance()->toString(array('host'))); $_COOKIE[$cookieName] = $cookieValue; } // Store this cookie also in the default Joomal! session (in case extra cookies are disabled) $session = JFactory::getSession(); $session->set('magebridge.cookie.' . $cookieName, $cookieValue); } } // Handle the extra remember-me cookie $user = JFactory::getUser(); if ($user->id > 0 && !empty($_COOKIE['persistent_shopping_cart'])) { $password = $user->password_clear; if (empty($password)) { $password = $this->input->getString('password'); } if (empty($password)) { $password = $user->password; } if (!empty($password)) { $credentials = array('username' => $user->username, 'password' => $password); // Create the encryption key, apply extra hardening using the user agent string. $privateKey = JApplication::getHash(@$_SERVER['HTTP_USER_AGENT']); $key = new JCryptKey('simple', $privateKey, $privateKey); $crypt = new JCrypt(new JCryptCipherSimple(), $key); $rcookie = $crypt->encrypt(serialize($credentials)); $lifetime = time() + 365 * 24 * 60 * 60; // Use domain and path set in config for cookie if it exists. $cookie_domain = JFactory::getConfig()->get('cookie_domain', ''); $cookie_path = JFactory::getConfig()->get('cookie_path', '/'); setcookie(JApplication::getHash('JLOGIN_REMEMBER'), $rcookie, $lifetime, $cookie_path, $cookie_domain); } } // Handle redirects preg_match('/^Location: ([^\\s]+)/m', $this->head['headers'], $matches); if ($this->allow_redirects && (preg_match('/^3([0-9]+)/', $this->head['http_code']) || !empty($matches))) { $originalLocation = trim(array_pop($matches)); $location = $originalLocation; // Check for a location-override if ($this->getHeader('X-MageBridge-Location') != null) { // But only override the location, if there is no error present if (strstr($location, 'startcustomization=1') == false) { $this->debug->notice('X-MageBridge-Location = ' . $this->getHeader('X-MageBridge-Location')); $location = $this->getHeader('X-MageBridge-Location'); } } // Check for a location-override if the customer is logged in if ($this->getHeader('X-MageBridge-Location-Customer') != null && $this->getHeader('X-MageBridge-Customer') != null) { MageBridgeModelUser::getInstance()->postlogin($this->getHeader('X-MageBridge-Customer'), null, true, true); $this->debug->notice('X-MageBridge-Location-Customer = ' . $this->getHeader('X-MageBridge-Location-Customer')); $location = $this->getHeader('X-MageBridge-Location-Customer'); } // Check for the location in the CURL-information if (empty($location) && isset($this->head['info']['redirect_url'])) { $location = $this->head['info']['redirect_url']; } // No location could be found if (empty($location)) { $this->debug->trace('Redirect requested but no URL found', $this->head['headers']); return false; } // Check if the current location is the Magento homepage, and if so, override it with the Joomla!-stored referer instead $referer = $this->bridge->getHttpReferer(); if ($location == $this->bridge->getJoomlaBridgeUrl()) { if (MagebridgeModelConfig::load('use_homepage_for_homepage_redirects') == 1) { $location = JURI::base(); } elseif (MagebridgeModelConfig::load('use_referer_for_homepage_redirects') == 1 && !empty($referer) && $referer != JURI::current()) { $location = $referer; } } //$location = preg_replace('/magebridge\.php\//', '', $location); $this->debug->warning('Trying to redirect to new location ' . $location); header('X-MageBridge-Redirect: ' . $originalLocation); $this->setRedirect($location); } curl_close($handle); return $this->body; }
/** * Method used to generate the current nonce. * * @return string The current nonce. * * @since 13.1 */ public static function generateNonce() { $mt = microtime(); $rand = JCrypt::genRandomBytes(); // The md5s look nicer than numbers. return md5($mt . $rand); }
/** * * @return \JCrypt */ private static function getCrypt() { $crypt = new JCrypt(); $conf = JFactory::getConfig(); $key = new JCryptKey('simple'); $key->private = $conf->get('secret'); $key->public = $key->private; $crypt->setKey($key); return $crypt; }
/** * Generates a new set of One Time Emergency Passwords (OTEPs) for a given user. * * @param integer $user_id The user ID * @param integer $count How many OTEPs to generate? Default: 10 * * @return array The generated OTEPs * * @since 3.2 */ public function generateOteps($user_id, $count = 10) { $user_id = !empty($user_id) ? $user_id : (int) $this->getState('user.id'); // Initialise $oteps = array(); // Get the OTP configuration for the user $otpConfig = $this->getOtpConfig($user_id); // If two factor authentication is not enabled, abort if (empty($otpConfig->method) || $otpConfig->method == 'none') { return $oteps; } $salt = "0123456789"; $base = strlen($salt); $length = 16; for ($i = 0; $i < $count; $i++) { $makepass = ''; $random = JCrypt::genRandomBytes($length + 1); $shift = ord($random[0]); for ($j = 1; $j <= $length; ++$j) { $makepass .= $salt[($shift + ord($random[$j])) % $base]; $shift += ord($random[$j]); } $oteps[] = $makepass; } $otpConfig->otep = $oteps; // Save the now modified OTP configuration $this->setOtpConfig($user_id, $otpConfig); return $oteps; }
/** * Verifies a password hash * * @param string $password The password to verify. * @param string $hash The password hash to check. * * @return boolean True if the password is valid, false otherwise. * * @since 12.2 * @deprecated 4.0 Use PHP 5.5's native password hashing API */ public function verify($password, $hash) { // Check if the hash is a blowfish hash. if (substr($hash, 0, 4) == '$2a$' || substr($hash, 0, 4) == '$2y$') { $type = '$2a$'; if (JCrypt::hasStrongPasswordSupport()) { $type = '$2y$'; } $hash = $type . substr($hash, 4); return crypt($password, $hash) === $hash; } // Check if the hash is an MD5 hash. if (substr($hash, 0, 3) == '$1$') { return crypt($password, $hash) === $hash; } // Check if the hash is a Joomla hash. if (preg_match('#[a-z0-9]{32}:[A-Za-z0-9]{32}#', $hash) === 1) { return md5($password . substr($hash, 33)) === substr($hash, 0, 32); } return false; }
/** * Method to determine if script owns the path. * * @param string $path Path to check ownership. * * @return boolean True if the php script owns the path passed. * * @since 11.1 */ public static function isOwner($path) { jimport('joomla.filesystem.file'); $tmp = md5(JCrypt::genRandomBytes()); $ssp = ini_get('session.save_path'); $jtp = JPATH_SITE . '/tmp'; // Try to find a writable directory $dir = is_writable('/tmp') ? '/tmp' : false; $dir = !$dir && is_writable($ssp) ? $ssp : false; $dir = !$dir && is_writable($jtp) ? $jtp : false; if ($dir) { $fileObject = new JFilesystemWrapperFile(); $test = $dir . '/' . $tmp; // Create the test file $blank = ''; $fileObject->write($test, $blank, false); // Test ownership $return = fileowner($test) == fileowner($path); // Delete the test file $fileObject->delete($test); return $return; } return false; }
/** * Method to unlock a password protected category * * @param int $catid ID of the category to unlock * @param string $password Password of the category to check * @return boolean True on success, false otherwise * @since 3.1 */ public function unlock($catid, $password) { $query = $this->_db->getQuery(true)->select('cid, password')->from($this->_db->quoteName(_JOOM_TABLE_CATEGORIES))->where('cid = ' . (int) $catid); $this->_db->setQuery($query); if (!($category = $this->_db->loadObject())) { throw new Exception($this->_db->getErrorMsg()); } if (!$category->password) { throw new Exception('Category is not protected.'); } $match = false; if (substr($category->password, 0, 4) == '$2y$') { // BCrypt passwords are always 60 characters, but it is possible that salt is appended although non standard. $password60 = substr($category->password, 0, 60); if (JCrypt::hasStrongPasswordSupport()) { $match = password_verify($password, $password60); } } else { if (substr($category->password, 0, 8) == '{SHA256}') { // Check the password $parts = explode(':', $category->password); $crypt = $parts[0]; $salt = @$parts[1]; $testcrypt = JUserHelper::getCryptedPassword($password, $salt, 'sha256', false); if ($category->password == $testcrypt) { $match = true; } } else { // Check the password $parts = explode(':', $category->password); $crypt = $parts[0]; $salt = @$parts[1]; $testcrypt = JUserHelper::getCryptedPassword($password, $salt, 'md5-hex', false); if ($crypt == $testcrypt) { $match = true; } } } if (!$match) { throw new Exception(JText::_('COM_JOOMGALLERY_CATEGORY_WRONG_PASSWORD')); } $categories = $this->_mainframe->getUserState('joom.unlockedCategories', array(0)); $categories = array_unique(array_merge($categories, array($catid))); $this->_mainframe->setUserState('joom.unlockedCategories', $categories); return true; }
/** * Method to determine if script owns the path. * * @param string $path Path to check ownership. * * @return boolean True if the php script owns the path passed. * * @since 11.1 */ public static function isOwner($path) { $tmp = md5(JCrypt::genRandomBytes()); $ssp = ini_get('session.save_path'); $jtp = PATH_PROJECT . '/data/tmp'; // Try to find a writable directory $dir = is_writable('/tmp') ? '/tmp' : false; $dir = !$dir && is_writable($ssp) ? $ssp : false; $dir = !$dir && is_writable($jtp) ? $jtp : false; if ($dir) { $test = $dir . '/' . $tmp; // Create the test file $blank = ''; App_Filesystem_File::write($test, $blank, false); // Test ownership $return = fileowner($test) == fileowner($path); // Delete the test file App_Filesystem_File::delete($test); return $return; } return false; }
/** * This method should handle any authentication and report back to the subject * * @param array $credentials Array holding the user credentials * @param array $options Array of extra options * @param object &$response Authentication response object * * @return boolean * * @since 1.5 */ public function onUserAuthenticate($credentials, $options, &$response) { $response->type = 'Joomla'; // Joomla does not like blank passwords if (empty($credentials['password'])) { $response->status = JAuthentication::STATUS_FAILURE; $response->error_message = JText::_('JGLOBAL_AUTH_EMPTY_PASS_NOT_ALLOWED'); return false; } // Get a database object $db = JFactory::getDbo(); $query = $db->getQuery(true)->select('id, password')->from('#__users')->where('username='******'username'])); $db->setQuery($query); $result = $db->loadObject(); if ($result) { if (substr($result->password, 0, 4) == '$2y$') { // BCrypt passwords are always 60 characters, but it is possible that salt is appended although non standard. $password60 = substr($result->password, 0, 60); if (JCrypt::hasStrongPasswordSupport()) { $match = password_verify($credentials['password'], $password60); } } elseif (substr($result->password, 0, 8) == '{SHA256}') { // Check the password $parts = explode(':', $result->password); $crypt = $parts[0]; $salt = @$parts[1]; $testcrypt = JUserHelper::getCryptedPassword($credentials['password'], $salt, 'sha256', false); if ($result->password == $testcrypt) { $match = true; } } else { // Check the password $parts = explode(':', $result->password); $crypt = $parts[0]; $salt = @$parts[1]; $testcrypt = JUserHelper::getCryptedPassword($credentials['password'], $salt, 'md5-hex', false); if ($crypt == $testcrypt) { $match = true; } } if (isset($match) && $match === true) { // Bring this in line with the rest of the system $user = JUser::getInstance($result->id); $response->email = $user->email; $response->fullname = $user->name; if (JFactory::getApplication()->isAdmin()) { $response->language = $user->getParam('admin_language'); } else { $response->language = $user->getParam('language'); } $response->status = JAuthentication::STATUS_SUCCESS; $response->error_message = ''; } else { // Invalid password $response->status = JAuthentication::STATUS_FAILURE; $response->error_message = JText::_('JGLOBAL_AUTH_INVALID_PASS'); } } else { // Invalid user $response->status = JAuthentication::STATUS_FAILURE; $response->error_message = JText::_('JGLOBAL_AUTH_NO_USER'); } // Check the two factor authentication if ($response->status == JAuthentication::STATUS_SUCCESS) { require_once JPATH_ADMINISTRATOR . '/components/com_users/helpers/users.php'; $methods = UsersHelper::getTwoFactorMethods(); if (count($methods) <= 1) { // No two factor authentication method is enabled return; } require_once JPATH_ADMINISTRATOR . '/components/com_users/models/user.php'; $model = new UsersModelUser(); // Load the user's OTP (one time password, a.k.a. two factor auth) configuration if (!array_key_exists('otp_config', $options)) { $otpConfig = $model->getOtpConfig($result->id); $options['otp_config'] = $otpConfig; } else { $otpConfig = $options['otp_config']; } // Check if the user has enabled two factor authentication if (empty($otpConfig->method) || $otpConfig->method == 'none') { // Warn the user if he's using a secret code but he has not // enabed two factor auth in his account. if (!empty($credentials['secretkey'])) { try { $app = JFactory::getApplication(); $this->loadLanguage(); $app->enqueueMessage(JText::_('PLG_AUTH_JOOMLA_ERR_SECRET_CODE_WITHOUT_TFA'), 'warning'); } catch (Exception $exc) { // This happens when we are in CLI mode. In this case // no warning is issued return; } } return; } // Load the Joomla! RAD layer if (!defined('FOF_INCLUDED')) { include_once JPATH_LIBRARIES . '/fof/include.php'; } // Try to validate the OTP FOFPlatform::getInstance()->importPlugin('twofactorauth'); $otpAuthReplies = FOFPlatform::getInstance()->runPlugins('onUserTwofactorAuthenticate', array($credentials, $options)); $check = false; /* * This looks like noob code but DO NOT TOUCH IT and do not convert * to in_array(). During testing in_array() inexplicably returned * null when the OTEP begins with a zero! o_O */ if (!empty($otpAuthReplies)) { foreach ($otpAuthReplies as $authReply) { $check = $check || $authReply; } } // Fall back to one time emergency passwords if (!$check) { // Did the user use an OTEP instead? if (empty($otpConfig->otep)) { if (empty($otpConfig->method) || $otpConfig->method == 'none') { // Two factor authentication is not enabled on this account. // Any string is assumed to be a valid OTEP. return true; } else { /* * Two factor authentication enabled and no OTEPs defined. The * user has used them all up. Therefore anything he enters is * an invalid OTEP. */ return false; } } // Clean up the OTEP (remove dashes, spaces and other funny stuff // our beloved users may have unwittingly stuffed in it) $otep = $credentials['secretkey']; $otep = filter_var($otep, FILTER_SANITIZE_NUMBER_INT); $otep = str_replace('-', '', $otep); $check = false; // Did we find a valid OTEP? if (in_array($otep, $otpConfig->otep)) { // Remove the OTEP from the array $otpConfig->otep = array_diff($otpConfig->otep, array($otep)); $model->setOtpConfig($result->id, $otpConfig); // Return true; the OTEP was a valid one $check = true; } } if (!$check) { $response->status = JAuthentication::STATUS_FAILURE; $response->error_message = JText::_('JGLOBAL_AUTH_INVALID_SECRETKEY'); } } }
/** * Setups the JCrypt object with default keys if not specified then returns it. * * @param array $options Optional override options for keys. * * @return JCrypt The configured JCrypt object. * * @since 2.0 */ public static function getCrypt($options = array()) { $source = strtolower(JArrayHelper::getValue($options, 'source', 'jconfig', 'string')); if ($source === 'jconfig') { /* * If JConfig has been included then lets check whether the keys * have been imported and if not then use the secret value for now. */ if (class_exists('JConfig')) { $config = new JConfig(); if (!isset($options['key'])) { $options['key'] = $config->secret; } } } elseif ($source === 'file') { $file = JArrayHelper::getValue($options, 'file', '', 'string'); if (file_exists($file)) { $options['key'] = file_get_contents($file); } } $crypt = new JCrypt(); // Create some default options $type = JArrayHelper::getValue($options, 'type', 'simple', 'string'); $key = JArrayHelper::getValue($options, 'key', 'DEFAULTKEY', 'string'); $crypt->setKey(new JCryptKey($type, $key, $key)); return $crypt; }
public function generate(&$pack, &$order, $quantity, &$serials) { if (!isset($pack->coupongen)) { return; } parent::pluginParams($pack->coupongen); if (empty($this->plugin_params->format) || !preg_match_all('#\\\\[|\\\\]|\\[[^]]+\\]\\{.*\\}|\\[.*\\]|.#iU', $this->plugin_params->format, $matches)) { $matches = array(array('[a-zA-Z0-9]{size}')); } $config = hikaserial::config(); $fastRandom = (int) $config->get('use_fast_random', 0); for ($q = 0; $q < $quantity; $q++) { $serial = ''; $serialObj = new stdClass(); if (!HIKASHOP_J16 || $fastRandom) { $stat = @stat(__FILE__); if (empty($stat) || !is_array($stat)) { $stat = array(php_uname()); } mt_srand(crc32(microtime() . implode('|', $stat))); } else { if (empty($this->plugin_params->size) || $this->plugin_params->size == 0) { $this->plugin_params->size = 15; } $rndCpt = 1; $random = JCrypt::genRandomBytes($this->plugin_params->size + 1); $shift = ord($random[0]); } foreach ($matches[0] as $m) { if (strlen($m) == 1) { $serial .= $m; } else { $repeat = 1; $format = $m; if (strpos($m, '{') !== false) { list($format, $repeat) = explode('{', $m); $repeat = trim(trim($repeat, '}')); if (empty($repeat) || (int) $repeat == 0) { $repeat = $this->plugin_params->size; } else { $repeat = (int) $repeat; } } $format = substr($format, 1, -1); $list = ''; $l = strlen($format); for ($i = 0; $i < $l; $i++) { if ($i + 2 < $l) { if ($format[$i + 1] == '-') { $s = $format[$i]; $e = $format[$i + 2]; $s1 = $s >= 'a' && $s <= 'z'; $s2 = $s >= 'A' && $s <= 'Z'; $s3 = $s >= '0' && $s <= '9'; $e1 = $e >= 'a' && $e <= 'z'; $e2 = $e >= 'A' && $e <= 'Z'; $e3 = $e >= '0' && $e <= '9'; if (!$s1 && !$s2 && !$s3) { $list .= $s . '-'; $i++; // Skip '-' continue; } if ($s1 && $e1 || $s2 && $e2 || $s3 && $e3) { if ($s > $e) { $c = $s; $s = $e; $e = $c; } for ($c = $s; $c < $e; $c++) { $list .= $c; } $i += 2; } else { if ($s1 && $e2) { for ($c = $s; $c < 'z'; $c++) { $list .= $c; } for ($c = 'A'; $c < $e; $c++) { $list .= $c; } $i += 2; } else { $list .= $s . '-'; $i++; // Skip '-' } } } else { $list .= $format[$i]; } } else { $list .= $format[$i]; } } $base = strlen($list); if (!HIKASHOP_J16 || $fastRandom) { for ($i = 1; $i <= $repeat; $i++) { $serial .= $list[mt_rand(0, $base - 1)]; } } else { for ($i = 1; $i <= $repeat; $i++) { $serial .= $list[($shift + ord($random[$rndCpt])) % $base]; $shift += ord($random[$rndCpt++]); if ($rndCpt == $this->plugin_params->size) { $rndCpt = 1; $random = JCrypt::genRandomBytes($this->plugin_params->size + 1); $shift = ord($random[0]); } } } } } $discount_id = (int) $this->plugin_params->discount_id; $result = true; if (!$this->test && !empty($discount_id)) { $discountClass = hikaserial::get('shop.class.discount'); $data = $discountClass->get($discount_id); if ($data) { unset($data->discount_id); $data->discount_code = $serial; $data->discount_published = 1; $data->discount_used_times = 0; if (!empty($this->plugin_params->validity_period) && !empty($this->plugin_params->validity_value) && (int) $this->plugin_params->validity_value > 0) { $date_d = date("d"); $date_m = date("m"); $date_y = date("Y"); $v = (int) $this->plugin_params->validity_value; switch ($this->plugin_params->validity_period) { case 'year': $data->discount_end = mktime(0, 0, 0, $date_m, $date_d, $date_y + $v); break; case 'month': $data->discount_end = mktime(0, 0, 0, $date_m + $v, $date_d, $date_y); break; case 'day': $data->discount_end = mktime(0, 0, 0, $date_m, $date_d + $v, $date_y); break; } if (!isset($serialObj->extradata)) { $serialObj->extradata = array(); } $serialObj->extradata['discount_end'] = $data->discount_end; } if (!empty($this->plugin_params->discount_percent)) { $v = hikaserial::toFloat(trim($this->plugin_params->discount_percent)); $product_price = 0; if (!empty($order->cart->products)) { foreach ($order->cart->products as $p) { if ($p->product_id == $pack->product_id || isset($pack->order_product_id) && $p->order_product_id == $pack->order_product_id) { $product_price = hikaserial::toFloat($p->order_product_price); if (!empty($this->plugin_params->discount_percent_tax)) { $product_price += hikaserial::toFloat($p->order_product_tax); } break; } } } if (!empty($product_price)) { if (!empty($order->order_currency_id)) { $data->discount_currency_id = (int) $order->order_currency_id; } else { $data->discount_currency_id = (int) $order->old->order_currency_id; } $data->discount_flat_amount = $product_price * $v / 100; $data->discount_percent_amount = 0.0; } } if (!$discountClass->save($data)) { $result = false; } } } if (!$result) { $app = JFactory::getApplication(); $app->enqueueMessage(JText::_('ERR_CREATING_DISCOUNT_COUPON')); } if (!empty($serialObj) && !empty($serialObj->extradata)) { $serialObj->data = $serial; $serials[] = $serialObj; } else { $serials[] = $serial; } } }
/** * Generates a salt of specified length. The salt consists of characters in the set [./0-9A-Za-z]. * * @param integer $length The number of characters to return. * * @return string The string of random characters. * * @since 12.2 */ protected function getSalt($length) { $bytes = ceil($length * 6 / 8); $randomData = str_replace('+', '.', base64_encode(JCrypt::genRandomBytes($bytes))); return substr($randomData, 0, $length); }
public function check() { if ($this->container->platform->isFrontend()) { $this->user_id = $this->container->platform->getUser()->id; } $db = $this->getDbo(); // Should this be a primary or a secondary DLID? if (is_null($this->primary)) { // Do I have another primary? $query = $db->getQuery(true)->select('COUNT(*)')->from($db->qn('#__ars_dlidlabels'))->where($db->qn('user_id') . ' = ' . $db->q($this->user_id))->where($db->qn('primary') . ' = ' . $db->q(1)); if ($this->ars_dlidlabel_id) { $query->where('NOT(' . $db->qn('ars_dlidlabel_id') . ' = ' . $db->q($this->ars_dlidlabel_id) . ')'); } $hasPrimary = $db->setQuery($query)->loadResult(); $this->primary = $hasPrimary ? 0 : 1; } if ($this->primary) { // You can never disable a primary Download ID $this->enabled = 1; // The primary Download ID title is fixed $this->label = '_MAIN_'; } // Do I need to generate a download ID? if (empty($this->dlid)) { while (empty($this->dlid)) { $this->dlid = md5(\JCrypt::genRandomBytes(64)); // Do I have another primary? $query = $db->getQuery(true)->select('COUNT(*)')->from($db->qn('#__ars_dlidlabels'))->where($db->qn('dlid') . ' = ' . $db->q($this->dlid))->where($db->qn('user_id') . ' = ' . $db->q($this->user_id))->where($db->qn('primary') . ' = ' . $db->q($this->primary)); if ($this->ars_dlidlabel_id) { $query->where('NOT(' . $db->qn('ars_dlidlabel_id') . ' = ' . $db->q($this->ars_dlidlabel_id) . ')'); } $dlidColission = $db->setQuery($query)->loadResult(); if ($dlidColission) { $this->dlid = null; } } } return parent::check(); }
/** * Method to generate a new encryption key object. * * @param array $options Key generation options. * * @return JCryptKey * * @since 12.1 * @throws InvalidArgumentException */ public function generateKey(array $options = array()) { // Create the new encryption key object. $key = new JCryptKey($this->keyType); // Generate an initialisation vector based on the algorithm. $key->public = mcrypt_create_iv(mcrypt_get_iv_size($this->type, $this->mode)); // Get the salt and password setup. $salt = isset($options['salt']) ? $options['salt'] : substr(pack("h*", md5(JCrypt::genRandomBytes())), 0, 16); if (!isset($options['password'])) { throw new InvalidArgumentException('Password is not set.'); } // Generate the derived key. $key->private = $this->pbkdf2($options['password'], $salt, mcrypt_get_key_size($this->type, $this->mode)); return $key; }
/** * Verifies a password hash * * @param string $password The password to verify. * @param string $hash The password hash to check. * * @return boolean True if the password is valid, false otherwise. * * @since 12.2 * @deprecated 4.0 Use PHP 5.5's native password hashing API */ public function verify($password, $hash) { // Check if the hash is a blowfish hash. if (substr($hash, 0, 4) == '$2a$' || substr($hash, 0, 4) == '$2y$') { $type = '$2a$'; if (JCrypt::hasStrongPasswordSupport()) { $type = '$2y$'; } return password_verify($password, $hash); } // Check if the hash is an MD5 hash. if (substr($hash, 0, 3) == '$1$') { return JCrypt::timingSafeCompare(crypt($password, $hash), $hash); } // Check if the hash is a Joomla hash. if (preg_match('#[a-z0-9]{32}:[A-Za-z0-9]{32}#', $hash) === 1) { // Check the password $parts = explode(':', $hash); $salt = @$parts[1]; // Compile the hash to compare // If the salt is empty AND there is a ':' in the original hash, we must append ':' at the end $testcrypt = md5($password . $salt) . ($salt ? ':' . $salt : (strpos($hash, ':') !== false ? ':' : '')); return JCrypt::timingSafeCompare($hash, $testcrypt); } return false; }
/** * Method to determine if script owns the path. * * @param string $path Path to check ownership. * * @return boolean True if the php script owns the path passed. * * @since 11.1 */ public static function isOwner($path) { jimport('joomla.filesystem.file'); $tmp = md5(JCrypt::genRandomBytes()); $ssp = ini_get('session.save_path'); $jtp = JPATH_SITE . '/tmp'; // Try to find a writable directory $dir = false; foreach (array($jtp, $ssp, '/tmp') as $currentDir) { if (is_writable($currentDir)) { $dir = $currentDir; break; } } if ($dir) { $fileObject = new JFilesystemWrapperFile(); $test = $dir . '/' . $tmp; // Create the test file $blank = ''; $fileObject->write($test, $blank, false); // Test ownership $return = fileowner($test) == fileowner($path); // Delete the test file $fileObject->delete($test); return $return; } return false; }
/** * Generates a set of One Time Emergency Passwords (OTEPs) for a user. Technique taken from Joomla * * @since 1.3 * @access public * @param string * @return */ public static function generateOteps($otpConfig, $count = 10) { // Initialise $oteps = array(); // If two factor authentication is not enabled, abort if (empty($otpConfig->method) || $otpConfig->method == 'none') { return $oteps; } $salt = "0123456789"; $base = strlen($salt); $length = 16; for ($i = 0; $i < $count; $i++) { $makepass = ''; $random = JCrypt::genRandomBytes($length + 1); $shift = ord($random[0]); for ($j = 1; $j <= $length; ++$j) { $makepass .= $salt[($shift + ord($random[$j])) % $base]; $shift += ord($random[$j]); } $oteps[] = $makepass; } return $oteps; }
/** * Return a random 32 byte hash value. * @param string extra entropy data */ static function hash($length = 32) { require_once MODPATH . "gallery/vendor/joomla/crypt.php"; return md5(JCrypt::genRandomBytes($length)); }
/** * Encrypt a string * * @param string $s String to encrypt * * @return string * * @since 11.1 * @deprecated 12.3 Use JCrypt instead. */ public function encrypt($s) { return $this->_crypt->encrypt($s); }
/** * Generate a random password * * @param integer $length Length of the password to generate * * @return string Random Password * * @since 11.1 */ public static function genRandomPassword($length = 8) { $salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $base = strlen($salt); $makepass = ''; /* * Start with a cryptographic strength random string, then convert it to * a string with the numeric base of the salt. * Shift the base conversion on each character so the character * distribution is even, and randomize the start shift so it's not * predictable. */ $random = JCrypt::genRandomBytes($length + 1); $shift = ord($random[0]); for ($i = 1; $i <= $length; ++$i) { $makepass .= $salt[($shift + ord($random[$i])) % $base]; $shift += ord($random[$i]); } return $makepass; }
function plgSystemImproved_Ajax_Login(&$subject, $config) { parent::__construct($subject, $config); $GLOBALS['username=email'] = $this->params->get('generate', 1) < 1; if (isset($_REQUEST['ialCheck'])) { $check = JRequest::getString('ialCheck'); $json = array('error' => '', 'msg' => ''); switch ($check) { case 'ialLogin': $json['field'] = 'password'; if (JSession::checkToken()) { $user = JRequest::getVar(isset($_REQUEST['username']) ? 'username' : 'email', ''); $password = JRequest::getString('password', '', 'method', JREQUEST_ALLOWRAW); if (!empty($password)) { $result = isset($_REQUEST['username']) ? OUserHelper::getUser($user) : OUserHelper::getUserByEmail($user); if ($result) { $match = 0; if (method_exists('JUserHelper', 'verifyPassword')) { $match = JUserHelper::verifyPassword($password, $result->password, $result->id); } elseif (substr($result->password, 0, 4) == '$2y$') { $password60 = substr($result->password, 0, 60); if (JCrypt::hasStrongPasswordSupport()) { $match = password_verify($password, $password60); } } else { $parts = explode(':', $result->password); $crypt = $parts[0]; $salt = @$parts[1]; $cryptmode = substr($result->password, 0, 8) == '{SHA256}' ? 'sha256' : 'md5-hex'; $testcrypt = JUserHelper::getCryptedPassword($password, $salt, $cryptmode, false); $match = $crypt == $testcrypt || $result->password == $testcrypt; } if ($match) { $json['username'] = $result->username; } else { $json['error'] = 'JGLOBAL_AUTH_INVALID_PASS'; } } else { $json['error'] = 'JGLOBAL_AUTH_NO_USER'; } } else { $json['error'] = 'JGLOBAL_AUTH_EMPTY_PASS_NOT_ALLOWED'; } } else { $json['error'] = 'JINVALID_TOKEN'; } $json['msg'] = JText::_($json['error']); die(json_encode($json)); case 'data[register][username]': case 'jform[username]': case 'username': $username = JRequest::getString('value'); if (OUserHelper::getId($username)) { $json['error'] = 'COM_USERS_REGISTER_USERNAME_MESSAGE'; } $json['msg'] = JText::_($json['error']); die(json_encode($json)); case 'data[register][email]': case 'jform[email1]': case 'email': $email = JRequest::getString('value'); if (OUserHelper::getIdByEmail($email)) { $json['error'] = 'COM_USERS_REGISTER_EMAIL1_MESSAGE'; } $json['msg'] = JText::_($json['error']); die(json_encode($json)); case 'ialRegister': // com_users if ($jf = JRequest::getVar('jform', null, 'array')) { if (!JSession::checkToken()) { $json['error'] = 'JINVALID_TOKEN'; $json['msg'] = JText::_($json['error']); die(json_encode($json)); } if (!isset($jf['email1'])) { $json['error'] = 'JGLOBAL_EMAIL'; $json['msg'] = JText::_('JGLOBAL_EMAIL') . ' ' . JText::_('JREQUIRED'); die(json_encode($json)); } if (!isset($jf['password1'])) { $json['error'] = 'JGLOBAL_PASSWORD'; $json['msg'] = JText::_('JGLOBAL_PASSWORD') . ' ' . JText::_('JREQUIRED'); die(json_encode($json)); } if (!isset($jf['username'])) { if ($this->params->get('generate', 1) > 0) { list($jf['username']) = explode('@', $jf['email1']); if (OUserHelper::getId($jf['username'])) { $jf['username'] .= OUserHelper::getNewId(); } } else { $jf['username'] = $jf['email1']; } } if (!isset($jf['name'])) { $jf['name'] = $jf['username']; } if (!isset($jf['email2'])) { $jf['email2'] = $jf['email1']; } if (!isset($jf['password2'])) { $jf['password2'] = $jf['password1']; } JRequest::setVar('jform', $jf); JFactory::getApplication()->input->post->set('jform', $jf); } $_SESSION['ialRegister'] = $jf['username']; break; } } }
/** * Login authentication function. * * Username and encoded password are passed the onUserLogin event which * is responsible for the user validation. A successful validation updates * the current session record with the user's details. * * Username and encoded password are sent as credentials (along with other * possibilities) to each observer (authentication plugin) for user * validation. Successful validation will update the current session with * the user details. * * @param array $credentials Array('username' => string, 'password' => string) * @param array $options Array('remember' => boolean) * * @return boolean True on success. * * @since 11.1 */ public function login($credentials, $options = array()) { // Get the global JAuthentication object. jimport('joomla.user.authentication'); $authenticate = JAuthentication::getInstance(); $response = $authenticate->authenticate($credentials, $options); if ($response->status === JAuthentication::STATUS_SUCCESS) { // validate that the user should be able to login (different to being authenticated) // this permits authentication plugins blocking the user $authorisations = $authenticate->authorise($response, $options); foreach ($authorisations as $authorisation) { $denied_states = array(JAuthentication::STATUS_EXPIRED, JAuthentication::STATUS_DENIED); if (in_array($authorisation->status, $denied_states)) { // Trigger onUserAuthorisationFailure Event. $this->triggerEvent('onUserAuthorisationFailure', array((array) $authorisation)); // If silent is set, just return false. if (isset($options['silent']) && $options['silent']) { return false; } // Return the error. switch ($authorisation->status) { case JAuthentication::STATUS_EXPIRED: return JError::raiseWarning('102002', JText::_('JLIB_LOGIN_EXPIRED')); break; case JAuthentication::STATUS_DENIED: return JError::raiseWarning('102003', JText::_('JLIB_LOGIN_DENIED')); break; default: return JError::raiseWarning('102004', JText::_('JLIB_LOGIN_AUTHORISATION')); break; } } } // Import the user plugin group. JPluginHelper::importPlugin('user'); // OK, the credentials are authenticated and user is authorised. Lets fire the onLogin event. $results = $this->triggerEvent('onUserLogin', array((array) $response, $options)); /* * If any of the user plugins did not successfully complete the login routine * then the whole method fails. * * Any errors raised should be done in the plugin as this provides the ability * to provide much more information about why the routine may have failed. */ if (!in_array(false, $results, true)) { // Set the remember me cookie if enabled. if (isset($options['remember']) && $options['remember']) { // Create the encryption key, apply extra hardening using the user agent string. $privateKey = self::getHash(@$_SERVER['HTTP_USER_AGENT']); $key = new JCryptKey('simple', $privateKey, $privateKey); $crypt = new JCrypt(new JCryptCipherSimple(), $key); $rcookie = $crypt->encrypt(json_encode($credentials)); $lifetime = time() + 365 * 24 * 60 * 60; // Use domain and path set in config for cookie if it exists. $cookie_domain = $this->getCfg('cookie_domain', ''); $cookie_path = $this->getCfg('cookie_path', '/'); // Check for SSL connection $secure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' || getenv('SSL_PROTOCOL_VERSION'); setcookie(self::getHash('JLOGIN_REMEMBER'), $rcookie, $lifetime, $cookie_path, $cookie_domain, $secure, true); } return true; } } // Trigger onUserLoginFailure Event. $this->triggerEvent('onUserLoginFailure', array((array) $response)); // If silent is set, just return false. if (isset($options['silent']) && $options['silent']) { return false; } // If status is success, any error will have been raised by the user plugin if ($response->status !== JAuthentication::STATUS_SUCCESS) { JError::raiseWarning('102001', $response->error_message); } return false; }
/** * Method to create the root user for the site * * @param object $options The session options * * @return boolean True on success * * @since 3.1 */ private function _createRootUser($options) { // Get the application /* @var InstallationApplicationWeb $app */ $app = JFactory::getApplication(); // Get a database object. try { $db = InstallationHelperDatabase::getDBO($options->db_type, $options->db_host, $options->db_user, $options->db_pass, $options->db_name, $options->db_prefix); } catch (RuntimeException $e) { $app->enqueueMessage(JText::sprintf('INSTL_ERROR_CONNECT_DB', $e->getMessage()), 'notice'); return false; } $useStrongPasswords = JCrypt::hasStrongPasswordSupport(); if ($useStrongPasswords) { $cryptpass = JUserHelper::getCryptedPassword($options->admin_password); } else { $salt = JUserHelper::genRandomPassword(16); //$cryptpass = JUserHelper::getCryptedPassword($options->admin_password, $salt, 'sha256') . ':' . $salt; $cryptpass = JUserHelper::getCryptedPassword($options->admin_password, $salt, 'sha256'); } // Take the admin user id $userId = InstallationModelDatabase::getUserId(); // We don't need the randUserId in the session any longer, let's remove it InstallationModelDatabase::resetRandUserId(); // Create the admin user date_default_timezone_set('UTC'); $installdate = date('Y-m-d H:i:s'); $nullDate = $db->getNullDate(); // Sqlsrv change $query = $db->getQuery(true)->select($db->quoteName('id'))->from($db->quoteName('#__users'))->where($db->quoteName('id') . ' = ' . $db->quote($userId)); $db->setQuery($query); if ($db->loadResult()) { $query->clear()->update($db->quoteName('#__users'))->set($db->quoteName('name') . ' = ' . $db->quote('Super User'))->set($db->quoteName('username') . ' = ' . $db->quote($options->admin_user))->set($db->quoteName('email') . ' = ' . $db->quote($options->admin_email))->set($db->quoteName('password') . ' = ' . $db->quote($cryptpass))->set($db->quoteName('block') . ' = 0')->set($db->quoteName('sendEmail') . ' = 1')->set($db->quoteName('registerDate') . ' = ' . $db->quote($installdate))->set($db->quoteName('lastvisitDate') . ' = ' . $db->quote($nullDate))->set($db->quoteName('activation') . ' = ' . $db->quote('0'))->set($db->quoteName('params') . ' = ' . $db->quote(''))->where($db->quoteName('id') . ' = ' . $db->quote($userId)); } else { $columns = array($db->quoteName('id'), $db->quoteName('name'), $db->quoteName('username'), $db->quoteName('email'), $db->quoteName('password'), $db->quoteName('block'), $db->quoteName('sendEmail'), $db->quoteName('registerDate'), $db->quoteName('lastvisitDate'), $db->quoteName('activation'), $db->quoteName('params')); $query->clear()->insert('#__users', true)->columns($columns)->values($db->quote($userId) . ', ' . $db->quote('Super User') . ', ' . $db->quote($options->admin_user) . ', ' . $db->quote($options->admin_email) . ', ' . $db->quote($cryptpass) . ', ' . $db->quote('0') . ', ' . $db->quote('1') . ', ' . $db->quote($installdate) . ', ' . $db->quote($nullDate) . ', ' . $db->quote('0') . ', ' . $db->quote('')); } $db->setQuery($query); try { $db->execute(); } catch (RuntimeException $e) { $app->enqueueMessage($e->getMessage(), 'notice'); return false; } // Map the super admin to the Super Admin Group $query->clear()->select($db->quoteName('user_id'))->from($db->quoteName('#__user_usergroup_map'))->where($db->quoteName('user_id') . ' = ' . $db->quote($userId)); $db->setQuery($query); if ($db->loadResult()) { $query->clear()->update($db->quoteName('#__user_usergroup_map'))->set($db->quoteName('user_id') . ' = ' . $db->quote($userId))->set($db->quoteName('group_id') . ' = 8'); } else { $query->clear()->insert($db->quoteName('#__user_usergroup_map'), false)->columns(array($db->quoteName('user_id'), $db->quoteName('group_id')))->values($db->quote($userId) . ', 8'); } $db->setQuery($query); try { $db->execute(); } catch (RuntimeException $e) { $app->enqueueMessage($e->getMessage(), 'notice'); return false; } return true; }