예제 #1
0
 /**
  * This test is to check and make sure that the nonce system is typecast tolerant.
  *
  * This causes issue because Core models are not strict in their datatypes.
  * ie: an int may be 123 or "123", and to Core they're both the same.
  */
 public function testStrictTypecastTolerance()
 {
     $d1 = ['something' => '123'];
     $d2 = ['something' => 123];
     $nonce = NonceModel::Generate('12 seconds', $d1);
     $this->assertTrue(NonceModel::ValidateAndUse($nonce, $d2));
 }
	/**
	 * Form Handler for logging in.
	 *
	 * @static
	 *
	 * @param \Form $form
	 *
	 * @return bool|null|string
	 */
	public static function LoginHandler(\Form $form){
		/** @var \FormElement $e */
		$e = $form->getElement('email');
		/** @var \FormElement $p */
		$p = $form->getElement('pass');


		/** @var \UserModel $u */
		$u = \UserModel::Find(array('email' => $e->get('value')), 1);

		if(!$u){
			// Log this as a login attempt!
			$logmsg = 'Failed Login. Email not registered' . "\n" . 'Email: ' . $e->get('value') . "\n";
			\SystemLogModel::LogSecurityEvent('/user/login', $logmsg);
			$e->setError('t:MESSAGE_ERROR_USER_LOGIN_EMAIL_NOT_FOUND');
			return false;
		}

		if($u->get('active') == 0){
			// The model provides a quick cut-off for active/inactive users.
			// This is the control managed with in the admin.
			$logmsg = 'Failed Login. User tried to login before account activation' . "\n" . 'User: '******'email') . "\n";
			\SystemLogModel::LogSecurityEvent('/user/login', $logmsg, null, $u->get('id'));
			$e->setError('t:MESSAGE_ERROR_USER_LOGIN_ACCOUNT_NOT_ACTIVE');
			return false;
		}
		elseif($u->get('active') == -1){
			// The model provides a quick cut-off for active/inactive users.
			// This is the control managed with in the admin.
			$logmsg = 'Failed Login. User tried to login after account deactivation.' . "\n" . 'User: '******'email') . "\n";
			\SystemLogModel::LogSecurityEvent('/user/login', $logmsg, null, $u->get('id'));
			$e->setError('t:MESSAGE_ERROR_USER_LOGIN_ACCOUNT_DEACTIVATED');
			return false;
		}

		try{
			/** @var \Core\User\AuthDrivers\datastore $auth */
			$auth = $u->getAuthDriver('datastore');
		}
		catch(Exception $e){
			$e->setError('t:MESSAGE_ERROR_USER_LOGIN_PASSWORD_AUTH_DISABLED');
			return false;
		}


		// This is a special case if the password isn't set yet.
		// It can happen with imported users or if a password is invalidated.
		if($u->get('password') == ''){
			// Use the Nonce system to generate a one-time key with this user's data.
			$nonce = \NonceModel::Generate(
				'20 minutes',
				['type' => 'password-reset', 'user' => $u->get('id')]
			);

			$link = '/datastoreauth/forgotpassword?e=' . urlencode($u->get('email')) . '&n=' . $nonce;

			$email = new \Email();
			$email->setSubject('Initial Password Request');
			$email->to($u->get('email'));
			$email->assign('link', \Core\resolve_link($link));
			$email->assign('ip', REMOTE_IP);
			$email->templatename = 'emails/user/initialpassword.tpl';
			try{
				$email->send();
				\SystemLogModel::LogSecurityEvent('/user/initialpassword/send', 'Initial password request sent successfully', null, $u->get('id'));

				\Core\set_message('t:MESSAGE_INFO_USER_LOGIN_MUST_SET_NEW_PASSWORD_INSTRUCTIONS_HAVE_BEEN_EMAILED');
				return true;
			}
			catch(\Exception $e){
				\Core\ErrorManagement\exception_handler($e);
				\Core\set_message('t:MESSAGE_ERROR_USER_LOGIN_MUST_SET_NEW_PASSWORD_UNABLE_TO_SEND_EMAIL');
				return false;
			}
		}


		if(!$auth->checkPassword($p->get('value'))){

			// Log this as a login attempt!
			$logmsg = 'Failed Login. Invalid password' . "\n" . 'Email: ' . $e->get('value') . "\n";
			\SystemLogModel::LogSecurityEvent('/user/login/failed_password', $logmsg, null, $u->get('id'));

			// Also, I want to look up and see how many login attempts there have been in the past couple minutes.
			// If there are too many, I need to start slowing the attempts.
			$time = new \CoreDateTime();
			$time->modify('-5 minutes');

			$securityfactory = new \ModelFactory('SystemLogModel');
			$securityfactory->where('code = /user/login/failed_password');
			$securityfactory->where('datetime > ' . $time->getFormatted(\Time::FORMAT_EPOCH, \Time::TIMEZONE_GMT));
			$securityfactory->where('ip_addr = ' . REMOTE_IP);

			$attempts = $securityfactory->count();
			if($attempts > 4){
				// Start slowing down the response.  This should help deter brute force attempts.
				// (x+((x-7)/4)^3)-4
				sleep( ($attempts+(($attempts-7)/4)^3)-4 );
				// This makes a nice little curve with the following delays:
				// 5th  attempt: 0.85
				// 6th  attempt: 2.05
				// 7th  attempt: 3.02
				// 8th  attempt: 4.05
				// 9th  attempt: 5.15
				// 10th attempt: 6.52
				// 11th attempt: 8.10
				// 12th attempt: 10.05
			}

			$e->setError('t:MESSAGE_ERROR_USER_LOGIN_INCORRECT_PASSWORD');
			$p->set('value', '');
			return false;
		}


		if($form->getElementValue('redirect')){
			// The page was set via client-side javascript on the login page.
			// This is the most reliable option.
			$url = $form->getElementValue('redirect');
		}
		elseif(REL_REQUEST_PATH == '/user/login'){
			// If the user came from the registration page, get the page before that.
			$url = $form->referrer;
		}
		else{
			// else the registration link is now on the same page as the 403 handler.
			$url = REL_REQUEST_PATH;
		}

		// Well, record this too!
		\SystemLogModel::LogSecurityEvent('/user/login', 'Login successful (via password)', null, $u->get('id'));

		// yay...
		$u->set('last_login', \CoreDateTime::Now('U', \Time::TIMEZONE_GMT));
		$u->save();
		\Core\Session::SetUser($u);

		// Allow an external script to override the redirecting URL.
		$overrideurl = \HookHandler::DispatchHook('/user/postlogin/getredirecturl');
		if($overrideurl){
			$url = $overrideurl;
		}

		return $url;
	}
예제 #3
0
 /**
  * Shorthand function to lookup a nonce from the database.
  *
  * @param $key
  * @return NonceModel|null
  */
 public static function LookupKey($key)
 {
     $key = strtolower($key);
     $search = NonceModel::Find(['key' => $key], 1);
     return $search;
 }
예제 #4
0
 /**
  * Page to enable Facebook logins for user accounts.
  *
  * @return int|null|string
  */
 public function enable()
 {
     $request = $this->getPageRequest();
     $auths = \Core\User\Helper::GetEnabledAuthDrivers();
     if (!isset($auths['facebook'])) {
         // Facebook isn't enabled, simply redirect to the home page.
         \Core\redirect('/');
     }
     if (!FACEBOOK_APP_ID) {
         \Core\redirect('/');
     }
     if (!FACEBOOK_APP_SECRET) {
         \Core\redirect('/');
     }
     // If it was a POST, then it should be the first page.
     if ($request->isPost()) {
         $facebook = new Facebook(['appId' => FACEBOOK_APP_ID, 'secret' => FACEBOOK_APP_SECRET]);
         // Did the user submit the facebook login request?
         if (isset($_POST['login-method']) && $_POST['login-method'] == 'facebook' && $_POST['access-token']) {
             try {
                 $facebook->setAccessToken($_POST['access-token']);
                 /** @var int $fbid The user ID from facebook */
                 $fbid = $facebook->getUser();
                 /** @var array $user_profile The array of user data from Facebook */
                 $user_profile = $facebook->api('/me');
             } catch (Exception $e) {
                 \Core\set_message($e->getMessage(), 'error');
                 \Core\go_back();
                 return null;
             }
             // If the user is logged in, then the verification logic is slightly different.
             if (\Core\user()->exists()) {
                 // Logged in users, the email must match.
                 if (\Core\user()->get('email') != $user_profile['email']) {
                     \Core\set_message('Your Facebook email is ' . $user_profile['email'] . ', which does not match your account email!  Unable to link accounts.', 'error');
                     \Core\go_back();
                     return null;
                 }
                 $user = \Core\user();
             } else {
                 /** @var \UserModel|null $user */
                 $user = UserModel::Find(['email' => $user_profile['email']], 1);
                 if (!$user) {
                     \Core\set_message('No local account found with the email ' . $user_profile['email'] . ', please <a href="' . \Core\resolve_link('/user/register') . '"create an account</a> instead.', 'error');
                     \Core\go_back();
                     return null;
                 }
             }
             // Send an email with a nonce link that will do the actual activation.
             // This is a security feature so just anyone can't link another user's account.
             $nonce = NonceModel::Generate('20 minutes', null, ['user' => $user, 'access_token' => $_POST['access-token']]);
             $email = new Email();
             $email->to($user->get('email'));
             $email->setSubject('Facebook Activation Request');
             $email->templatename = 'emails/facebook/enable_confirmation.tpl';
             $email->assign('link', \Core\resolve_link('/facebook/enable/' . $nonce));
             if ($email->send()) {
                 \Core\set_message('An email has been sent to your account with a link enclosed.  Please click on that to complete activation within twenty minutes.', 'success');
                 \Core\go_back();
                 return null;
             } else {
                 \Core\set_message('Unable to send a confirmation email, please try again later.', 'error');
                 \Core\go_back();
                 return null;
             }
         }
     }
     // If there is a nonce enclosed, then it should be the second confirmation page.
     // This is the one that actually performs the action.
     if ($request->getParameter(0)) {
         /** @var NonceModel $nonce */
         $nonce = NonceModel::Construct($request->getParameter(0));
         if (!$nonce->isValid()) {
             \Core\set_message('Invalid key requested.', 'error');
             \Core\redirect('/');
             return null;
         }
         $nonce->decryptData();
         $data = $nonce->get('data');
         /** @var UserModel $user */
         $user = $data['user'];
         try {
             $facebook = new Facebook(['appId' => FACEBOOK_APP_ID, 'secret' => FACEBOOK_APP_SECRET]);
             $facebook->setAccessToken($data['access_token']);
             $facebook->getUser();
             $facebook->api('/me');
         } catch (Exception $e) {
             \Core\set_message($e->getMessage(), 'error');
             \Core\redirect('/');
             return null;
         }
         $user->enableAuthDriver('facebook');
         /** @var \Facebook\UserAuth $auth */
         $auth = $user->getAuthDriver('facebook');
         $auth->syncUser($data['access_token']);
         \Core\set_message('Linked Facebook successfully!', 'success');
         // And log the user in!
         if (!\Core\user()->exists()) {
             $user->set('last_login', \CoreDateTime::Now('U', \Time::TIMEZONE_GMT));
             $user->save();
             \Core\Session::SetUser($user);
         }
         \Core\redirect('/');
         return null;
     }
 }
예제 #5
0
	/**
	 * Simple controller to activate a user account.
	 * Meant to be called with json only.
	 */
	public function activate(){
		$req    = $this->getPageRequest();
		$view   = $this->getView();
		$userid = $req->getPost('user') ? $req->getPost('user') : $req->getParameter('user');
		$active = ($req->getPost('status') !== null) ? $req->getPost('status') : $req->getParameter('status');
		if($active === '') $active = 1; // default.


		if(!\Core\user()->checkAccess('p:/user/users/manage')){
			return View::ERROR_ACCESSDENIED;
		}

		if(!$req->isPost()){
			return View::ERROR_BADREQUEST;
		}

		if(!$userid){
			return View::ERROR_BADREQUEST;
		}


		$user = UserModel::Construct($userid);

		if(!$user->exists()){
			return View::ERROR_NOTFOUND;
		}

		$user->set('active', $active);
		$user->save();

		// Send an activation notice email to the user if the active flag is set to true.
		if($active){
			try{
				$email = new Email();

				if(!$user->get('password')){
					// Generate a Nonce for this user with the password reset.
					// Use the Nonce system to generate a one-time key with this user's data.
					$nonce = NonceModel::Generate(
						'1 week',
						['type' => 'password-reset', 'user' => $user->get('id')]
					);
					$setpasswordlink = \Core\resolve_link('/datastoreauth/forgotpassword?e=' . urlencode($user->get('email')) . '&n=' . $nonce);
				}
				else{
					$setpasswordlink = null;
				}

				$email->templatename = 'emails/user/activation.tpl';
				$email->assign('user', $user);
				$email->assign('sitename', SITENAME);
				$email->assign('rooturl', ROOT_URL);
				$email->assign('loginurl', \Core\resolve_link('/user/login'));
				$email->assign('setpasswordlink', $setpasswordlink);
				$email->setSubject('Welcome to ' . SITENAME);
				$email->to($user->get('email'));

				// TESTING
				//error_log($email->renderBody());
				$email->send();
			}
			catch(\Exception $e){
				\Core\ErrorManagement\exception_handler($e);
			}
		}

		if($req->isJSON()){
			$view->mode = View::MODE_AJAX;
			$view->contenttype = View::CTYPE_JSON;

			$view->jsondata = array(
				'userid' => $user->get('id'),
				'active' => $user->get('active'),
			);
		}
		else{
			\Core\go_back();
		}
	}
예제 #6
0
	/**
	 * Validate the verification email, part 2 of confirmation.
	 *
	 * @param string $nonce
	 * @param string $signature
	 *
	 * @return bool|string
	 */
	public static function ValidateVerificationResponse($nonce, $signature) {
		/** @var \NonceModel $nonce */
		$nonce = \NonceModel::Construct($nonce);

		if(!$nonce->isValid()){
			\SystemLogModel::LogSecurityEvent('/user/gpg/verified', 'FAILED to verify key (Invalid NONCE)', null);
			return 'Invalid nonce provided!';
		}

		// Now is where the real fun begins.

		$nonce->decryptData();

		$data = $nonce->get('data');

		/** @var \UserModel $user */
		$user   = \UserModel::Construct($data['user']);
		$gpg    = new \Core\GPG\GPG();
		$key    = $data['key'];
		$pubKey = $gpg->getKey($key);

		try{
			$sig = $gpg->verifyDataSignature($signature, $data['sentence']);
		}
		catch(\Exception $e){
			\SystemLogModel::LogSecurityEvent('/user/gpg/verified', 'FAILED to verify key ' . $key, null, $user->get('id'));
			return 'Invalid signature';
		}

		$fpr = str_replace(' ', '', $sig->fingerprint); // Trim spaces.
		if($key != $fpr && $key != $sig->keyID){
			// They must match!
			\SystemLogModel::LogSecurityEvent('/user/gpg/verified', 'FAILED to verify key ' . $key, null, $user->get('id'));
			return 'Invalid signature';
		}

		// Otherwise?
		$user->enableAuthDriver('gpg');
		$user->set('gpgauth_pubkey', $fpr);

		// Was there a photo attached to this public key?
		if(sizeof($pubKey->getPhotos()) > 0){
			$p = $pubKey->getPhotos();
			// I just want the first.
			/** @var \Core\Filestore\File $p */
			$p = $p[0];

			$localFile = \Core\Filestore\Factory::File('public/user/avatar/' . $pubKey->fingerprint . '.' . $p->getExtension());
			$p->copyTo($localFile);
			$user->set('avatar', $localFile->getFilename(false));
		}
		
		$user->save();

		$nonce->markUsed();

		\SystemLogModel::LogSecurityEvent('/user/gpg/verified', 'Verified key ' . $fpr, null, $user->get('id'));

		return true;
	}