public function run($request) { $algo = Security::config()->password_encryption_algorithm; if ($algo == 'none') { $this->debugMessage('Password encryption disabled'); return; } // Are there members with a clear text password? $members = Member::get()->where(array('"Member"."PasswordEncryption"' => 'none', '"Member"."Password" IS NOT NULL')); if (!$members) { $this->debugMessage('No passwords to encrypt'); return; } // Encrypt the passwords... $this->debugMessage('Encrypting all passwords'); $this->debugMessage(sprintf('The passwords will be encrypted using the %s algorithm', $algo)); foreach ($members as $member) { // Force the update of the member record, as new passwords get // automatically encrypted according to the settings, this will do all // the work for us $member->PasswordEncryption = $algo; $member->forceChange(); $member->write(); $this->debugMessage(sprintf('Encrypted credentials for member #%d;', $member->ID)); } }
public function testCleartextPasswordsAreHashedWithDefaultAlgo() { $loader = new MemberCsvBulkLoader(); $results = $loader->load($this->getCurrentRelativePath() . '/MemberCsvBulkLoaderTest_cleartextpws.csv'); $member = $results->Created()->First(); $memberID = $member->ID; DataObject::flush_and_destroy_cache(); $member = DataObject::get_by_id('SilverStripe\\Security\\Member', $memberID); // TODO Direct getter doesn't work, wtf! $this->assertEquals(Security::config()->password_encryption_algorithm, $member->getField('PasswordEncryption')); $result = $member->checkPassword('mypassword'); $this->assertTrue($result->valid()); }
public function __construct(Controller $controller, $name) { // Set default fields $fields = new FieldList(HiddenField::create("AuthenticationMethod", null, $this->authenticator_class, $this), HiddenField::create('tempid', null, $controller->getRequest()->requestVar('tempid')), PasswordField::create("Password", _t('Member.PASSWORD', 'Password')), LiteralField::create('forgotPassword', sprintf('<p id="ForgotPassword"><a href="%s" target="_top">%s</a></p>', $this->getExternalLink('lostpassword'), _t('CMSMemberLoginForm.BUTTONFORGOTPASSWORD', "Forgot password?")))); if (Security::config()->autologin_enabled) { $fields->push(CheckboxField::create("Remember", _t('Member.REMEMBERME', "Remember me next time?"))); } // Determine returnurl to redirect to parent page $logoutLink = $this->getExternalLink('logout'); if ($returnURL = $controller->getRequest()->requestVar('BackURL')) { $logoutLink = Controller::join_links($logoutLink, '?BackURL=' . urlencode($returnURL)); } // Make actions $actions = new FieldList(FormAction::create('dologin', _t('CMSMemberLoginForm.BUTTONLOGIN', "Log back in")), LiteralField::create('doLogout', sprintf('<p id="doLogout"><a href="%s" target="_top">%s</a></p>', $logoutLink, _t('CMSMemberLoginForm.BUTTONLOGOUT', "Log out")))); parent::__construct($controller, $name, $fields, $actions); }
/** * Log login attempt * TODO We could handle this with an extension * * @param array $data * @param Member $member * @param bool $success */ protected static function record_login_attempt($data, $member, $success) { if (!Security::config()->login_recording) { return; } // Check email is valid $email = isset($data['Email']) ? $data['Email'] : null; if (is_array($email)) { throw new InvalidArgumentException("Bad email passed to MemberAuthenticator::authenticate(): {$email}"); } $attempt = new LoginAttempt(); if ($success) { // successful login (member is existing with matching password) $attempt->MemberID = $member->ID; $attempt->Status = 'Success'; // Audit logging hook $member->extend('authenticated'); } else { // Failed login - we're trying to see if a user exists with this email (disregarding wrong passwords) $attempt->Status = 'Failure'; if ($member) { // Audit logging hook $attempt->MemberID = $member->ID; $member->extend('authenticationFailed'); } else { // Audit logging hook Member::singleton()->extend('authenticationFailedUnknownUser', $data); } } $attempt->Email = $email; $attempt->IP = Controller::curr()->getRequest()->getIP(); $attempt->write(); }
DB::connect($databaseConfig); } // Check if a token is requesting a redirect if (!$reloadToken) { return; } // Otherwise, we start up the session if needed if (!isset($_SESSION) && Session::request_contains_session_id()) { Session::start(); } // Next, check if we're in dev mode, or the database doesn't have any security data, or we are admin if (Director::isDev() || !Security::database_is_ready() || Permission::check('ADMIN')) { return $reloadToken->reloadWithToken(); } // Fail and redirect the user to the login page $loginPage = Director::absoluteURL(Security::config()->login_url); $loginPage .= "?BackURL=" . urlencode($_SERVER['REQUEST_URI']); header('location: ' . $loginPage, true, 302); die; })->thenIfErrored(function () use($reloadToken) { if ($reloadToken) { $reloadToken->reloadWithToken(); } })->execute(); global $databaseConfig; // Redirect to the installer if no database is selected if (!isset($databaseConfig) || !isset($databaseConfig['database']) || !$databaseConfig['database']) { if (!file_exists(BASE_PATH . '/install.php')) { header($_SERVER['SERVER_PROTOCOL'] . " 500 Server Error"); die('SilverStripe Framework requires a $databaseConfig defined.'); }
public function testSuccessfulLoginAttempts() { Security::config()->login_recording = true; /* SUCCESSFUL ATTEMPTS ARE LOGGED */ $this->doTestLoginForm('*****@*****.**', '1nitialPassword'); $attempt = DataObject::get_one('SilverStripe\\Security\\LoginAttempt', array('"LoginAttempt"."Email"' => '*****@*****.**')); $member = DataObject::get_one('SilverStripe\\Security\\Member', array('"Member"."Email"' => '*****@*****.**')); $this->assertTrue(is_object($attempt)); $this->assertEquals($attempt->Status, 'Success'); $this->assertEquals($attempt->Email, '*****@*****.**'); $this->assertEquals($attempt->Member()->toMap(), $member->toMap()); }
/** * Event handler called before writing to the database. */ public function onBeforeWrite() { if ($this->SetPassword) { $this->Password = $this->SetPassword; } // If a member with the same "unique identifier" already exists with a different ID, don't allow merging. // Note: This does not a full replacement for safeguards in the controller layer (e.g. in a registration form), // but rather a last line of defense against data inconsistencies. $identifierField = Member::config()->unique_identifier_field; if ($this->{$identifierField}) { // Note: Same logic as Member_Validator class $filter = array("\"{$identifierField}\"" => $this->{$identifierField}); if ($this->ID) { $filter[] = array('"Member"."ID" <> ?' => $this->ID); } $existingRecord = DataObject::get_one('SilverStripe\\Security\\Member', $filter); if ($existingRecord) { throw new ValidationException(ValidationResult::create(false, _t('Member.ValidationIdentifierFailed', 'Can\'t overwrite existing member #{id} with identical identifier ({name} = {value}))', 'Values in brackets show "fieldname = value", usually denoting an existing email address', array('id' => $existingRecord->ID, 'name' => $identifierField, 'value' => $this->{$identifierField})))); } } // We don't send emails out on dev/tests sites to prevent accidentally spamming users. // However, if TestMailer is in use this isn't a risk. if ((Director::isLive() || Email::mailer() instanceof TestMailer) && $this->isChanged('Password') && $this->record['Password'] && $this->config()->notify_password_change) { /** @var Email $e */ $e = Email::create(); $e->setSubject(_t('Member.SUBJECTPASSWORDCHANGED', "Your password has been changed", 'Email subject')); $e->setTemplate('ChangePasswordEmail'); $e->populateTemplate($this); $e->setTo($this->Email); $e->send(); } // The test on $this->ID is used for when records are initially created. // Note that this only works with cleartext passwords, as we can't rehash // existing passwords. if (!$this->ID && $this->Password || $this->isChanged('Password')) { // Password was changed: encrypt the password according the settings $encryption_details = Security::encrypt_password($this->Password, $this->Salt, $this->PasswordEncryption ? $this->PasswordEncryption : Security::config()->password_encryption_algorithm, $this); // Overwrite the Password property with the hashed value $this->Password = $encryption_details['password']; $this->Salt = $encryption_details['salt']; $this->PasswordEncryption = $encryption_details['algorithm']; // If we haven't manually set a password expiry if (!$this->isChanged('PasswordExpiry')) { // then set it for us if (self::config()->password_expiry_days) { $this->PasswordExpiry = date('Y-m-d', time() + 86400 * self::config()->password_expiry_days); } else { $this->PasswordExpiry = null; } } } // save locale if (!$this->Locale) { $this->Locale = i18n::get_locale(); } parent::onBeforeWrite(); }
/** * Login in the user and figure out where to redirect the browser. * * The $data has this format * array( * 'AuthenticationMethod' => 'MemberAuthenticator', * 'Email' => '*****@*****.**', * 'Password' => '1nitialPassword', * 'BackURL' => 'test/link', * [Optional: 'Remember' => 1 ] * ) * * @param array $data * @return SS_HTTPResponse */ protected function logInUserAndRedirect($data) { Session::clear('SessionForms.MemberLoginForm.Email'); Session::clear('SessionForms.MemberLoginForm.Remember'); if (Member::currentUser()->isPasswordExpired()) { if (isset($_REQUEST['BackURL']) && ($backURL = $_REQUEST['BackURL'])) { Session::set('BackURL', $backURL); } $cp = ChangePasswordForm::create($this->controller, 'SilverStripe\\Security\\ChangePasswordForm'); $cp->sessionMessage(_t('Member.PASSWORDEXPIRED', 'Your password has expired. Please choose a new one.'), 'good'); return $this->controller->redirect('Security/changepassword'); } // Absolute redirection URLs may cause spoofing if (!empty($_REQUEST['BackURL'])) { $url = $_REQUEST['BackURL']; if (Director::is_site_url($url)) { $url = Director::absoluteURL($url); } else { // Spoofing attack, redirect to homepage instead of spoofing url $url = Director::absoluteBaseURL(); } return $this->controller->redirect($url); } // If a default login dest has been set, redirect to that. if ($url = Security::config()->default_login_dest) { $url = Controller::join_links(Director::absoluteBaseURL(), $url); return $this->controller->redirect($url); } // Redirect the user to the page where they came from $member = Member::currentUser(); if ($member) { $firstname = Convert::raw2xml($member->FirstName); if (!empty($data['Remember'])) { Session::set('SessionForms.MemberLoginForm.Remember', '1'); $member->logIn(true); } else { $member->logIn(); } Session::set('Security.Message.message', _t('Member.WELCOMEBACK', "Welcome Back, {firstname}", array('firstname' => $firstname))); Session::set("Security.Message.type", "good"); } Controller::curr()->redirectBack(); }
public function testDefaultPasswordEncryptionDoesntChangeExistingMembers() { $member = new Member(); $member->Password = '******'; $member->PasswordEncryption = 'sha1_v2.4'; $member->write(); $origAlgo = Security::config()->password_encryption_algorithm; Security::config()->password_encryption_algorithm = 'none'; $member->Password = '******'; $member->write(); $this->assertEquals($member->PasswordEncryption, 'sha1_v2.4'); $result = $member->checkPassword('mynewpassword'); $this->assertTrue($result->valid()); Security::config()->password_encryption_algorithm = $origAlgo; }
public function install($config) { ?> <html> <head> <meta charset="utf-8"/> <title>Installing SilverStripe...</title> <link rel="stylesheet" type="text/css" href="<?php echo FRAMEWORK_NAME; ?> /src/Dev/Install/client/dist/styles/install.css"/> <script src="//code.jquery.com/jquery-1.7.2.min.js"></script> </head> <body> <div class="install-header"> <div class="inner"> <div class="brand"> <span class="logo"></span> <h1>SilverStripe</h1> </div> </div> </div> <div id="Navigation"> </div> <div class="clear"><!-- --></div> <div class="main"> <div class="inner"> <h2>Installing SilverStripe...</h2> <p>I am now running through the installation steps (this should take about 30 seconds)</p> <p>If you receive a fatal error, refresh this page to continue the installation</p> <ul> <?php $webserver = $this->findWebserver(); $isIIS = $this->isIIS(); $isApache = $this->isApache(); flush(); if (isset($config['stats'])) { if (file_exists(FRAMEWORK_NAME . '/silverstripe_version')) { $silverstripe_version = file_get_contents(FRAMEWORK_NAME . '/silverstripe_version'); } else { $silverstripe_version = "unknown"; } $phpVersion = urlencode(phpversion()); $encWebserver = urlencode($webserver); $dbType = $config['db']['type']; // Try to determine the database version from the helper $databaseVersion = $config['db']['type']; $helper = $this->getDatabaseConfigurationHelper($dbType); if ($helper && method_exists($helper, 'getDatabaseVersion')) { $versionConfig = $config['db'][$dbType]; $versionConfig['type'] = $dbType; $databaseVersion = urlencode($dbType . ': ' . $helper->getDatabaseVersion($versionConfig)); } $url = "http://ss2stat.silverstripe.com/Installation/add?SilverStripe={$silverstripe_version}&PHP={$phpVersion}&Database={$databaseVersion}&WebServer={$encWebserver}"; if (isset($_SESSION['StatsID']) && $_SESSION['StatsID']) { $url .= '&ID=' . $_SESSION['StatsID']; } @($_SESSION['StatsID'] = file_get_contents($url)); } if (file_exists('mysite/_config.php')) { // Truncate the contents of _config instead of deleting it - we can't re-create it because Windows handles permissions slightly // differently to UNIX based filesystems - it takes the permissions from the parent directory instead of retaining them $fh = fopen('mysite/_config.php', 'wb'); fclose($fh); } // Escape user input for safe insertion into PHP file $theme = isset($_POST['template']) ? addcslashes($_POST['template'], "\\'") : 'simple'; $locale = isset($_POST['locale']) ? addcslashes($_POST['locale'], "\\'") : 'en_US'; $type = addcslashes($config['db']['type'], "\\'"); $dbConfig = $config['db'][$type]; $dbConfig = array_map(create_function('$v', 'return addcslashes($v, "\\\'");'), $dbConfig); if (!isset($dbConfig['path'])) { $dbConfig['path'] = ''; } if (!$dbConfig) { echo "<p style=\"color: red\">Bad config submitted</p><pre>"; print_r($config); echo "</pre>"; die; } // Write the config file global $usingEnv; if ($usingEnv) { $this->statusMessage("Setting up 'mysite/_config.php' for use with _ss_environment.php..."); $this->writeToFile("mysite/_config.php", <<<PHP <?php global \$project; \$project = 'mysite'; global \$database; \$database = '{$dbConfig['database']}'; require_once('conf/ConfigureFromEnv.php'); PHP ); } else { $this->statusMessage("Setting up 'mysite/_config.php'..."); // Create databaseConfig $lines = array($lines[] = "\t'type' => '{$type}'"); foreach ($dbConfig as $key => $value) { $lines[] = "\t'{$key}' => '{$value}'"; } $databaseConfigContent = implode(",\n", $lines); $this->writeToFile("mysite/_config.php", <<<PHP <?php global \$project; \$project = 'mysite'; global \$databaseConfig; \$databaseConfig = array( {$databaseConfigContent} ); PHP ); } $this->statusMessage("Setting up 'mysite/_config/config.yml'"); $this->writeToFile("mysite/_config/config.yml", <<<YML --- Name: mysite After: - 'framework/*' - 'cms/*' --- # YAML configuration for SilverStripe # See http://doc.silverstripe.org/framework/en/topics/configuration # Caution: Indentation through two spaces, not tabs SilverStripe\\View\\SSViewer: themes: - '{$theme}' - '\$default' SilverStripe\\i18n\\i18n: default_locale: '{$locale}' YML ); if (!$this->checkModuleExists('cms')) { $this->writeToFile("mysite/code/RootURLController.php", <<<PHP <?php use SilverStripe\\Control\\Controller; class RootURLController extends Controller { \tpublic function index() { \t\techo "<html>Your site is now set up. Start adding controllers to mysite to get started.</html>"; \t} } PHP ); } // Write the appropriate web server configuration file for rewriting support if ($this->hasRewritingCapability()) { if ($isApache) { $this->statusMessage("Setting up '.htaccess' file..."); $this->createHtaccess(); } elseif ($isIIS) { $this->statusMessage("Setting up 'web.config' file..."); $this->createWebConfig(); } } // Load the SilverStripe runtime $_SERVER['SCRIPT_FILENAME'] = dirname(realpath($_SERVER['SCRIPT_FILENAME'])) . '/' . FRAMEWORK_NAME . '/main.php'; chdir(FRAMEWORK_NAME); // Rebuild the manifest $_GET['flush'] = true; // Show errors as if you're in development mode $_SESSION['isDev'] = 1; $this->statusMessage("Building database schema..."); require_once 'Core/Core.php'; // Build database $con = new Controller(); $con->pushCurrent(); global $databaseConfig; DB::connect($databaseConfig); $dbAdmin = new DatabaseAdmin(); $dbAdmin->doInit(); $dbAdmin->doBuild(true); // Create default administrator user and group in database // (not using Security::setDefaultAdmin()) $adminMember = Security::findAnAdministrator(); $adminMember->Email = $config['admin']['username']; $adminMember->Password = $config['admin']['password']; $adminMember->PasswordEncryption = Security::config()->encryption_algorithm; try { $this->statusMessage('Creating default CMS admin account...'); $adminMember->write(); } catch (Exception $e) { $this->statusMessage(sprintf('Warning: Default CMS admin account could not be created (error: %s)', $e->getMessage())); } $_SESSION['username'] = $config['admin']['username']; $_SESSION['password'] = $config['admin']['password']; if (!$this->errors) { if (isset($_SERVER['HTTP_HOST']) && $this->hasRewritingCapability()) { $this->statusMessage("Checking that friendly URLs work..."); $this->checkRewrite(); } else { require_once 'Core/Startup/ParameterConfirmationToken.php'; $token = new ParameterConfirmationToken('flush'); $params = http_build_query($token->params()); $destinationURL = 'index.php/' . ($this->checkModuleExists('cms') ? "home/successfullyinstalled?{$params}" : "?{$params}"); echo <<<HTML \t\t\t\t<li>SilverStripe successfully installed; I am now redirecting you to your SilverStripe site...</li> \t\t\t\t<script> \t\t\t\t\tsetTimeout(function() { \t\t\t\t\t\twindow.location = "{$destinationURL}"; \t\t\t\t\t}, 2000); \t\t\t\t</script> \t\t\t\t<noscript> \t\t\t\t<li><a href="{$destinationURL}">Click here to access your site.</a></li> \t\t\t\t</noscript> HTML; } } return $this->errors; }