Ejemplo n.º 1
0
 /**
  * Apply permissions, restrictions and roles to the given user
  *
  * @param   User    $user
  */
 public function applyRoles(User $user)
 {
     $username = $user->getUsername();
     try {
         $roles = Config::app('roles');
     } catch (NotReadableError $e) {
         Logger::error('Can\'t get permissions and restrictions for user \'%s\'. An exception was thrown:', $username, $e);
         return;
     }
     $userGroups = $user->getGroups();
     $permissions = array();
     $restrictions = array();
     $roleObjs = array();
     foreach ($roles as $roleName => $role) {
         if ($this->match($username, $userGroups, $role)) {
             $permissionsFromRole = StringHelper::trimSplit($role->permissions);
             $permissions = array_merge($permissions, array_diff($permissionsFromRole, $permissions));
             $restrictionsFromRole = $role->toArray();
             unset($restrictionsFromRole['users']);
             unset($restrictionsFromRole['groups']);
             unset($restrictionsFromRole['permissions']);
             foreach ($restrictionsFromRole as $name => $restriction) {
                 if (!isset($restrictions[$name])) {
                     $restrictions[$name] = array();
                 }
                 $restrictions[$name][] = $restriction;
             }
             $roleObj = new Role();
             $roleObjs[] = $roleObj->setName($roleName)->setPermissions($permissionsFromRole)->setRestrictions($restrictionsFromRole);
         }
     }
     $user->setPermissions($permissions);
     $user->setRestrictions($restrictions);
     $user->setRoles($roleObjs);
 }
Ejemplo n.º 2
0
 /**
  * Append the given log entry and fail this inspection with the given error
  *
  * @param   $entry  string|Inspection   A log entry or nested inspection
  *
  * @throws  ProgrammingError            When called multiple times
  *
  * @return  this                        fluent interface
  */
 public function error($entry)
 {
     if (isset($this->error)) {
         throw new ProgrammingError('Inspection object used after error');
     }
     Logger::error($entry);
     $this->log[] = $entry;
     $this->error = $entry;
     return $this;
 }
Ejemplo n.º 3
0
 /**
  * Display exception
  */
 public function errorAction()
 {
     $error = $this->_getParam('error_handler');
     $exception = $error->exception;
     /** @var \Exception $exception */
     Logger::error($exception);
     Logger::error('Stacktrace: %s', $exception->getTraceAsString());
     switch ($error->type) {
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
             $modules = Icinga::app()->getModuleManager();
             $path = ltrim($this->_request->get('PATH_INFO'), '/');
             $path = preg_split('~/~', $path);
             $path = array_shift($path);
             $this->getResponse()->setHttpResponseCode(404);
             $this->view->message = $this->translate('Page not found.');
             if ($this->Auth()->isAuthenticated() && $modules->hasInstalled($path) && !$modules->hasEnabled($path)) {
                 $this->view->message .= ' ' . sprintf($this->translate('Enabling the "%s" module might help!'), $path);
             }
             break;
         default:
             switch (true) {
                 case $exception instanceof HttpMethodNotAllowedException:
                     $this->getResponse()->setHttpResponseCode(405);
                     $this->getResponse()->setHeader('Allow', $exception->getAllowedMethods());
                     break;
                 case $exception instanceof HttpNotFoundException:
                     $this->getResponse()->setHttpResponseCode(404);
                     break;
                 case $exception instanceof MissingParameterException:
                     $this->getResponse()->setHttpResponseCode(400);
                     $this->getResponse()->setHeader('X-Status-Reason', 'Missing parameter ' . $exception->getParameter());
                     break;
                 case $exception instanceof HttpBadRequestException:
                     $this->getResponse()->setHttpResponseCode(400);
                     break;
                 case $exception instanceof SecurityException:
                     $this->getResponse()->setHttpResponseCode(403);
                     break;
                 default:
                     $this->getResponse()->setHttpResponseCode(500);
                     break;
             }
             $this->view->message = $exception->getMessage();
             if ($this->getInvokeArg('displayExceptions')) {
                 $this->view->stackTrace = $exception->getTraceAsString();
             }
             break;
     }
     if ($this->getRequest()->isApiRequest()) {
         $this->getResponse()->json()->setErrorMessage($this->view->message)->sendResponse();
     }
     $this->view->request = $error->request;
 }
Ejemplo n.º 4
0
 /**
  * Parse the given query text and returns the json as expected by the semantic search box
  *
  * @param  String $text     The query to parse
  * @return array            The result structure to be returned in json format
  */
 private function parse($text, $target)
 {
     try {
         $queryTree = $this->registry->createQueryTreeForFilter($text);
         $registry = $this->moduleRegistry;
         return array('state' => 'success', 'proposals' => $this->registry->getProposalsForQuery($text), 'urlParam' => $registry::getUrlForTarget($target, $queryTree), 'valid' => count($this->registry->getIgnoredQueryParts()) === 0);
     } catch (\Exception $exc) {
         Logger::error($exc);
         $this->getResponse()->setHttpResponseCode(500);
         return array('state' => 'error', 'message' => 'Search service is currently not available');
     }
 }
Ejemplo n.º 5
0
 public function setAuthenticated(User $user, $persist = true)
 {
     $username = $user->getUsername();
     try {
         $config = Config::app();
     } catch (NotReadableError $e) {
         Logger::error(new IcingaException('Cannot load preferences for user "%s". An exception was thrown: %s', $username, $e));
         $config = new Config();
     }
     if ($config->get('preferences', 'store', 'ini') !== 'none') {
         $preferencesConfig = $config->getSection('preferences');
         try {
             $preferencesStore = PreferencesStore::create($preferencesConfig, $user);
             $preferences = new Preferences($preferencesStore->load());
         } catch (Exception $e) {
             Logger::error(new IcingaException('Cannot load preferences for user "%s". An exception was thrown: %s', $username, $e));
             $preferences = new Preferences();
         }
     } else {
         $preferences = new Preferences();
     }
     $user->setPreferences($preferences);
     $groups = $user->getGroups();
     foreach (Config::app('groups') as $name => $config) {
         try {
             $groupBackend = UserGroupBackend::create($name, $config);
             $groupsFromBackend = $groupBackend->getMemberships($user);
         } catch (Exception $e) {
             Logger::error('Can\'t get group memberships for user \'%s\' from backend \'%s\'. An exception was thrown: %s', $username, $name, $e);
             continue;
         }
         if (empty($groupsFromBackend)) {
             continue;
         }
         $groupsFromBackend = array_values($groupsFromBackend);
         $groups = array_merge($groups, array_combine($groupsFromBackend, $groupsFromBackend));
     }
     $user->setGroups($groups);
     $admissionLoader = new AdmissionLoader();
     list($permissions, $restrictions) = $admissionLoader->getPermissionsAndRestrictions($user);
     $user->setPermissions($permissions);
     $user->setRestrictions($restrictions);
     $this->user = $user;
     if ($persist) {
         $this->persistCurrentUser();
     }
 }
Ejemplo n.º 6
0
 protected function addMessage($message, $type = 'info')
 {
     if (!in_array($type, array('info', 'error', 'warning', 'success'))) {
         throw new ProgrammingError('"%s" is not a valid notification type', $type);
     }
     if ($this->isCli) {
         $msg = sprintf('[%s] %s', $type, $message);
         switch ($type) {
             case 'info':
             case 'success':
                 Logger::info($msg);
                 break;
             case 'warning':
                 Logger::warn($msg);
                 break;
             case 'error':
                 Logger::error($msg);
                 break;
         }
         return;
     }
     $this->messages[] = (object) array('type' => $type, 'message' => $message);
 }
Ejemplo n.º 7
0
 /**
  * Set up internationalization using gettext
  *
  * @return $this
  */
 protected final function setupInternationalization()
 {
     if ($this->hasLocales()) {
         Translator::registerDomain(Translator::DEFAULT_DOMAIN, $this->getLocaleDir());
     }
     $locale = $this->detectLocale();
     if ($locale === null) {
         $locale = Translator::DEFAULT_LOCALE;
     }
     try {
         Translator::setupLocale($locale);
     } catch (Exception $error) {
         Logger::error($error);
     }
     return $this;
 }
Ejemplo n.º 8
0
 /**
  * Return a javascript file from the application's or the module's public folder
  */
 public function javascriptAction()
 {
     $module = $this->_getParam('module_name');
     $file = $this->_getParam('file');
     if ($module == 'app') {
         $basedir = Icinga::app()->getApplicationDir('../public/js/icinga/components/');
         $filePath = $basedir . $file;
     } else {
         if (!Icinga::app()->getModuleManager()->hasEnabled($module)) {
             Logger::error('Non-existing frontend component "' . $module . '/' . $file . '" was requested. The module "' . $module . '" does not exist or is not active.');
             echo "/** Module not enabled **/";
             return;
         }
         $basedir = Icinga::app()->getModuleManager()->getModule($module)->getBaseDir();
         $filePath = $basedir . '/public/js/' . $file;
     }
     if (!file_exists($filePath)) {
         Logger::error('Non-existing frontend component "' . $module . '/' . $file . '" was requested, which would resolve to the the path: ' . $filePath);
         echo '/** Module has no js files **/';
         return;
     }
     $response = $this->getResponse();
     $response->setHeader('Content-Type', 'text/javascript');
     $this->setCacheHeader();
     $response->setHeader('Last-Modified', gmdate('D, d M Y H:i:s', filemtime($filePath)) . ' GMT');
     readfile($filePath);
 }
Ejemplo n.º 9
0
 /**
  * {@inheritdoc}
  */
 public function authenticate(User $user, $password = null)
 {
     list($username, $field) = static::getRemoteUserInformation();
     if ($username !== null) {
         $user->setExternalUserInformation($username, $field);
         if ($this->stripUsernameRegexp) {
             $stripped = @preg_replace($this->stripUsernameRegexp, '', $username);
             if ($stripped === false) {
                 Logger::error('Failed to strip external username. The configured regular expression is invalid.');
                 return false;
             }
             $username = $stripped;
         }
         $user->setUsername($username);
         return true;
     }
     return false;
 }
Ejemplo n.º 10
0
 /**
  * Render the stylesheet
  *
  * @return  string
  */
 public function __toString()
 {
     try {
         return $this->render();
     } catch (Exception $e) {
         Logger::error($e);
         return IcingaException::describe($e);
     }
 }
Ejemplo n.º 11
0
 /**
  * Fetch and return the given user's groups from all user group backends
  *
  * @param   User    $user
  *
  * @return  ArrayDatasource
  */
 protected function loadMemberships(User $user)
 {
     $groups = $alreadySeen = array();
     foreach ($this->loadUserGroupBackends() as $backend) {
         try {
             foreach ($backend->getMemberships($user) as $groupName) {
                 if (array_key_exists($groupName, $alreadySeen)) {
                     continue;
                     // Ignore duplicate memberships
                 }
                 $alreadySeen[$groupName] = null;
                 $groups[] = (object) array('group_name' => $groupName, 'backend' => $backend);
             }
         } catch (Exception $e) {
             Logger::error($e);
             Notification::warning(sprintf($this->translate('Failed to fetch memberships from backend %s. Please check your log'), $backend->getName()));
         }
     }
     return new ArrayDatasource($groups);
 }
Ejemplo n.º 12
0
 /**
  * Add a notification message
  *
  * @param   string $message
  * @param   string $type
  */
 protected function addMessage($message, $type = self::INFO)
 {
     if ($this->isCli) {
         $msg = sprintf('[%s] %s', $type, $message);
         switch ($type) {
             case self::INFO:
             case self::SUCCESS:
                 Logger::info($msg);
                 break;
             case self::ERROR:
                 Logger::error($msg);
                 break;
             case self::WARNING:
                 Logger::warning($msg);
                 break;
         }
     } else {
         $this->messages[] = (object) array('type' => $type, 'message' => $message);
     }
 }
Ejemplo n.º 13
0
 /**
  * Send the given command over an appropriate Icinga command transport
  *
  * This will try one configured transport after another until the command has been successfully sent.
  *
  * @param   IcingaCommand   $command    The command to send
  * @param   int|null        $now        Timestamp of the command or null for now
  *
  * @throws  CommandTransportException   If sending the Icinga command failed
  */
 public function send(IcingaCommand $command, $now = null)
 {
     $errors = array();
     foreach (static::getConfig() as $name => $transportConfig) {
         $transport = static::createTransport($transportConfig);
         if ($this->transferPossible($command, $transport)) {
             try {
                 $transport->send($command, $now);
             } catch (CommandTransportException $e) {
                 Logger::error($e);
                 $errors[] = sprintf('%s: %s.', $name, rtrim($e->getMessage(), '.'));
                 continue;
                 // Try the next transport
             }
             return;
             // The command was successfully sent
         }
     }
     if (!empty($errors)) {
         throw new CommandTransportException(implode("\n", $errors));
     }
     throw new CommandTransportException(mt('monitoring', 'Failed to send external Icinga command. No transport has been configured' . ' for this instance. Please contact your Icinga Web administrator.'));
 }
Ejemplo n.º 14
0
 /**
  * Send the given command over an appropriate Icinga command transport
  *
  * This will try one configured transport after another until the command has been successfully sent.
  *
  * @param   IcingaCommand   $command    The command to send
  * @param   int|null        $now        Timestamp of the command or null for now
  *
  * @throws  CommandTransportException   If sending the Icinga command failed
  */
 public function send(IcingaCommand $command, $now = null)
 {
     $tries = 0;
     foreach (static::getConfig() as $transportConfig) {
         $transport = static::createTransport($transportConfig);
         if ($this->transferPossible($command, $transport)) {
             try {
                 $transport->send($command, $now);
             } catch (CommandTransportException $e) {
                 Logger::error($e);
                 $tries += 1;
                 continue;
                 // Try the next transport
             }
             return;
             // The command was successfully sent
         }
     }
     if ($tries > 0) {
         throw new CommandTransportException(mt('monitoring', 'Failed to send external Icinga command. None of the configured transports' . ' was able to transfer the command. Please see the log for more details.'));
     }
     throw new CommandTransportException(mt('monitoring', 'Failed to send external Icinga command. No transport has been configured' . ' for this instance. Please contact your Icinga Web administrator.'));
 }
Ejemplo n.º 15
0
 /**
  * Check whether the current user backend is valid, i.e. it's enabled, not an external user backend and whether its
  * config is valid
  *
  * @return bool
  */
 public function valid()
 {
     if (!$this->config->valid()) {
         // Stop when there are no more backends to check
         return false;
     }
     $backendConfig = $this->config->current();
     if ((bool) $backendConfig->get('disabled', false)) {
         $this->next();
         return $this->valid();
     }
     $name = $this->key();
     try {
         $backend = UserBackend::create($name, $backendConfig);
     } catch (ConfigurationError $e) {
         Logger::error(new ConfigurationError('Can\'t create authentication backend "%s". An exception was thrown:', $name, $e));
         $this->next();
         return $this->valid();
     }
     if ($this->getSkipExternalBackends() && $backend instanceof ExternalBackend) {
         $this->next();
         return $this->valid();
     }
     $this->currentBackend = $backend;
     return true;
 }
Ejemplo n.º 16
0
 /**
  * Render the given child
  *
  * @param   Menu    $child      The menu's child to render
  *
  * @return  string              The child rendered as html
  */
 public function renderChild(Menu $child)
 {
     if ($child->getRenderer() !== null && $this->useCustomRenderer) {
         try {
             return $child->getRenderer()->render($child);
         } catch (Exception $e) {
             Logger::error('Could not invoke custom renderer. Exception: ' . $e->getMessage());
         }
     }
     return $this->defaultRenderer->render($child);
 }
Ejemplo n.º 17
0
 /**
  * Set the path to the LESS theme
  *
  * @param   string  $theme  Path to the LESS theme
  *
  * @return  $this
  */
 public function setTheme($theme)
 {
     if (is_file($theme) && is_readable($theme)) {
         $this->theme = $theme;
     } else {
         Logger::error('Can\\t load theme %s. Make sure that the theme exists and is readable', $theme);
     }
     return $this;
 }
Ejemplo n.º 18
0
 /**
  * Adjust preferences and persist them
  *
  * @see Form::onSuccess()
  */
 public function onSuccess()
 {
     $this->preferences = new Preferences($this->store ? $this->store->load() : array());
     $oldTheme = $this->preferences->getValue('icingaweb', 'theme');
     $webPreferences = $this->preferences->get('icingaweb', array());
     foreach ($this->getValues() as $key => $value) {
         if ($value === '' || $value === 'autodetect' || $key === 'theme' && $value === Config::app()->get('themes', 'default', StyleSheet::DEFAULT_THEME)) {
             if (isset($webPreferences[$key])) {
                 unset($webPreferences[$key]);
             }
         } else {
             $webPreferences[$key] = $value;
         }
     }
     $this->preferences->icingaweb = $webPreferences;
     Session::getSession()->user->setPreferences($this->preferences);
     if (($theme = $this->getElement('theme')) !== null && ($theme = $theme->getValue()) !== $oldTheme) {
         $this->getResponse()->setReloadCss(true);
     }
     try {
         if ($this->store && $this->getElement('btn_submit_preferences')->isChecked()) {
             $this->save();
             Notification::success($this->translate('Preferences successfully saved'));
         } else {
             Notification::success($this->translate('Preferences successfully saved for the current session'));
         }
     } catch (Exception $e) {
         Logger::error($e);
         Notification::error($e->getMessage());
     }
 }
Ejemplo n.º 19
0
 /**
  * Prepare and establish a connection with the LDAP server
  *
  * @return  resource        A LDAP link identifier
  *
  * @throws  LdapException   In case the connection is not possible
  */
 protected function prepareNewConnection()
 {
     if ($this->encryption === static::STARTTLS || $this->encryption === static::LDAPS) {
         $this->prepareTlsEnvironment();
     }
     $hostname = $this->hostname;
     if ($this->encryption === static::LDAPS) {
         $hostname = 'ldaps://' . $hostname;
     }
     $ds = ldap_connect($hostname, $this->port);
     // Usage of ldap_rename, setting LDAP_OPT_REFERRALS to 0 or using STARTTLS requires LDAPv3.
     // If this does not work we're probably not in a PHP 5.3+ environment as it is VERY
     // unlikely that the server complains about it by itself prior to a bind request
     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
     // Not setting this results in "Operations error" on AD when using the whole domain as search base
     ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
     if ($this->encryption === static::STARTTLS) {
         if ($this->encryptionSuccess = @ldap_start_tls($ds)) {
             Logger::debug('LDAP STARTTLS succeeded');
         } else {
             Logger::error('LDAP STARTTLS failed: %s', ldap_error($ds));
             // ldap_start_tls seems to corrupt the connection though if I understand
             // https://tools.ietf.org/html/rfc4511#section-4.14.2 correctly, this shouldn't happen
             $ds = ldap_connect($hostname, $this->port);
             ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
             ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
         }
     } elseif ($this->encryption === static::LDAPS) {
         $this->encryptionSuccess = true;
     }
     return $ds;
 }
Ejemplo n.º 20
0
 /**
  * Fetch and return all users from all user backends
  *
  * @return  ArrayDatasource
  */
 protected function fetchUsers()
 {
     $users = array();
     foreach ($this->loadUserBackends('Icinga\\Data\\Selectable') as $backend) {
         try {
             foreach ($backend->select(array('user_name')) as $row) {
                 $users[] = $row;
             }
         } catch (Exception $e) {
             Logger::error($e);
             Notification::warning(sprintf($this->translate('Failed to fetch any users from backend %s. Please check your log'), $backend->getName()));
         }
     }
     return new ArrayDatasource($users);
 }
Ejemplo n.º 21
0
 /**
  * Create and return a data source to fetch all groups from all backends where the user is not already a member of
  *
  * @return  ArrayDatasource
  */
 protected function createDataSource()
 {
     $groups = $failures = array();
     foreach ($this->backends as $backend) {
         try {
             $memberships = $backend->select()->from('group_membership', array('group_name'))->where('user_name', $this->userName)->fetchColumn();
             foreach ($backend->select(array('group_name')) as $row) {
                 if (!in_array($row->group_name, $memberships)) {
                     // TODO(jom): Apply this as native query filter
                     $row->backend_name = $backend->getName();
                     $groups[] = $row;
                 }
             }
         } catch (Exception $e) {
             $failures[] = array($backend->getName(), $e);
         }
     }
     if (empty($groups) && !empty($failures)) {
         // In case there are only failures, throw the very first exception again
         throw $failures[0][1];
     } elseif (!empty($failures)) {
         foreach ($failures as $failure) {
             Logger::error($failure[1]);
             Notification::warning(sprintf($this->translate('Failed to fetch any groups from backend %s. Please check your log'), $failure[0]));
         }
     }
     return new ArrayDatasource($groups);
 }
Ejemplo n.º 22
0
 /**
  * Render the given child
  *
  * @param   Menu    $child      The menu's child to render
  *
  * @return  string              The child rendered as html
  */
 public function renderChild(Menu $child)
 {
     if ($child->getRenderer() !== null && $this->useCustomRenderer) {
         try {
             return $child->getRenderer()->render($child);
         } catch (Exception $e) {
             Logger::error('Could not invoke custom menu renderer. %s in %s:%d with message: %s', get_class($e), $e->getFile(), $e->getLine(), $e->getMessage());
         }
     }
     return $this->defaultRenderer->render($child);
 }
Ejemplo n.º 23
0
 /**
  * Adjust preferences and persist them
  *
  * @see Form::onSuccess()
  */
 public function onSuccess()
 {
     $this->preferences = new Preferences($this->store ? $this->store->load() : array());
     $webPreferences = $this->preferences->get('icingaweb', array());
     foreach ($this->getValues() as $key => $value) {
         if ($value === null || $value === 'autodetect') {
             if (isset($webPreferences[$key])) {
                 unset($webPreferences[$key]);
             }
         } else {
             $webPreferences[$key] = $value;
         }
     }
     $this->preferences->icingaweb = $webPreferences;
     Session::getSession()->user->setPreferences($this->preferences);
     try {
         if ($this->store && $this->getElement('btn_submit_preferences')->isChecked()) {
             $this->save();
             Notification::success($this->translate('Preferences successfully saved'));
         } else {
             Notification::success($this->translate('Preferences successfully saved for the current session'));
         }
     } catch (Exception $e) {
         Logger::error($e);
         Notification::error($e->getMessage());
     }
 }
Ejemplo n.º 24
0
 /**
  * Detect installed modules from every path provided in modulePaths
  *
  * @param   array   $availableDirs      Installed modules location
  *
  * @return $this
  */
 public function detectInstalledModules(array $availableDirs = null)
 {
     $modulePaths = $availableDirs !== null ? $availableDirs : $this->modulePaths;
     foreach ($modulePaths as $basedir) {
         $canonical = realpath($basedir);
         if ($canonical === false) {
             Logger::warning('Module path "%s" does not exist', $basedir);
             continue;
         }
         if (!is_dir($canonical)) {
             Logger::error('Module path "%s" is not a directory', $canonical);
             continue;
         }
         if (!is_readable($canonical)) {
             Logger::error('Module path "%s" is not readable', $canonical);
             continue;
         }
         if (($dh = opendir($canonical)) !== false) {
             while (($file = readdir($dh)) !== false) {
                 if ($file[0] === '.') {
                     continue;
                 }
                 if (is_dir($canonical . '/' . $file)) {
                     if (!array_key_exists($file, $this->installedBaseDirs)) {
                         $this->installedBaseDirs[$file] = $canonical . '/' . $file;
                     } else {
                         Logger::debug('Module "%s" already exists in installation path "%s" and is ignored.', $canonical . '/' . $file, $this->installedBaseDirs[$file]);
                     }
                 }
             }
             closedir($dh);
         }
     }
     ksort($this->installedBaseDirs);
     return $this;
 }
 /**
  * Log into the application
  */
 public function loginAction()
 {
     $icinga = Icinga::app();
     if ($icinga->setupTokenExists() && $icinga->requiresSetup()) {
         $this->redirectNow(Url::fromPath('setup'));
     }
     $triedOnlyExternalAuth = null;
     $auth = $this->Auth();
     $this->view->form = $form = new LoginForm();
     $this->view->title = $this->translate('Icingaweb Login');
     try {
         $redirectUrl = $this->view->form->getValue('redirect');
         if ($redirectUrl) {
             $redirectUrl = Url::fromPath($redirectUrl);
         } else {
             $redirectUrl = Url::fromPath('dashboard');
         }
         if ($auth->isAuthenticated()) {
             $this->rerenderLayout()->redirectNow($redirectUrl);
         }
         try {
             $config = Config::app('authentication');
         } catch (NotReadableError $e) {
             throw new ConfigurationError($this->translate('Could not read your authentication.ini, no authentication methods are available.'), 0, $e);
         }
         $chain = new AuthChain($config);
         $request = $this->getRequest();
         if ($request->isPost() && $this->view->form->isValid($request->getPost())) {
             $user = new User($this->view->form->getValue('username'));
             $password = $this->view->form->getValue('password');
             $backendsTried = 0;
             $backendsWithError = 0;
             $redirectUrl = $form->getValue('redirect');
             if ($redirectUrl) {
                 $redirectUrl = Url::fromPath($redirectUrl);
             } else {
                 $redirectUrl = Url::fromPath('dashboard');
             }
             foreach ($chain as $backend) {
                 if ($backend instanceof ExternalBackend) {
                     continue;
                 }
                 ++$backendsTried;
                 try {
                     $authenticated = $backend->authenticate($user, $password);
                 } catch (AuthenticationException $e) {
                     Logger::error($e);
                     ++$backendsWithError;
                     continue;
                 }
                 if ($authenticated === true) {
                     $auth->setAuthenticated($user);
                     $this->rerenderLayout()->redirectNow($redirectUrl);
                 }
             }
             if ($backendsTried === 0) {
                 $this->view->form->addError($this->translate('No authentication methods available. Did you create' . ' authentication.ini when setting up Icinga Web 2?'));
             } else {
                 if ($backendsTried === $backendsWithError) {
                     $this->view->form->addError($this->translate('All configured authentication methods failed.' . ' Please check the system log or Icinga Web 2 log for more information.'));
                 } elseif ($backendsWithError) {
                     $this->view->form->addError($this->translate('Please note that not all authentication methods were available.' . ' Check the system log or Icinga Web 2 log for more information.'));
                 }
             }
             if ($backendsTried > 0 && $backendsTried !== $backendsWithError) {
                 $this->view->form->getElement('password')->addError($this->translate('Incorrect username or password'));
             }
         } elseif ($request->isGet()) {
             $user = new User('');
             foreach ($chain as $backend) {
                 $triedOnlyExternalAuth = $triedOnlyExternalAuth === null;
                 if ($backend instanceof ExternalBackend) {
                     $authenticated = $backend->authenticate($user);
                     if ($authenticated === true) {
                         $auth->setAuthenticated($user);
                         $this->rerenderLayout()->redirectNow(Url::fromPath(Url::fromRequest()->getParam('redirect', 'dashboard')));
                     }
                 } else {
                     $triedOnlyExternalAuth = false;
                 }
             }
         }
     } catch (Exception $e) {
         $this->view->form->addError($e->getMessage());
     }
     $this->view->requiresExternalAuth = $triedOnlyExternalAuth && !$auth->isAuthenticated();
     $this->view->requiresSetup = Icinga::app()->requiresSetup();
 }
Ejemplo n.º 26
0
 public function setAuthenticated(User $user, $persist = true)
 {
     $username = $user->getUsername();
     try {
         $config = Config::app();
     } catch (NotReadableError $e) {
         Logger::error(new IcingaException('Cannot load preferences for user "%s". An exception was thrown: %s', $username, $e));
         $config = new Config();
     }
     if ($config->get('global', 'config_backend', 'ini') !== 'none') {
         $preferencesConfig = new ConfigObject(array('store' => $config->get('global', 'config_backend', 'ini'), 'resource' => $config->get('global', 'config_resource')));
         try {
             $preferencesStore = PreferencesStore::create($preferencesConfig, $user);
             $preferences = new Preferences($preferencesStore->load());
         } catch (Exception $e) {
             Logger::error(new IcingaException('Cannot load preferences for user "%s". An exception was thrown: %s', $username, $e));
             $preferences = new Preferences();
         }
     } else {
         $preferences = new Preferences();
     }
     // TODO(el): Quick-fix for #10957. Only reload CSS if the theme changed.
     $this->getResponse()->setReloadCss(true);
     $user->setPreferences($preferences);
     $groups = $user->getGroups();
     foreach (Config::app('groups') as $name => $config) {
         try {
             $groupBackend = UserGroupBackend::create($name, $config);
             $groupsFromBackend = $groupBackend->getMemberships($user);
         } catch (Exception $e) {
             Logger::error('Can\'t get group memberships for user \'%s\' from backend \'%s\'. An exception was thrown: %s', $username, $name, $e);
             continue;
         }
         if (empty($groupsFromBackend)) {
             continue;
         }
         $groupsFromBackend = array_values($groupsFromBackend);
         $groups = array_merge($groups, array_combine($groupsFromBackend, $groupsFromBackend));
     }
     $user->setGroups($groups);
     $admissionLoader = new AdmissionLoader();
     $admissionLoader->applyRoles($user);
     $this->user = $user;
     if ($persist) {
         $this->persistCurrentUser();
     }
 }
Ejemplo n.º 27
0
 /**
  * Return this item rendered to HTML
  *
  * @return  string
  */
 public function render()
 {
     try {
         return $this->getRenderer()->setItem($this)->render();
     } catch (Exception $e) {
         Logger::error('Could not invoke custom navigation item renderer. %s in %s:%d with message: %s', get_class($e), $e->getFile(), $e->getLine(), $e->getMessage());
         $renderer = new NavigationItemRenderer();
         return $renderer->render($this);
     }
 }
Ejemplo n.º 28
0
 /**
  * Prepare and establish a connection with the LDAP server
  *
  * @return  resource        A positive LDAP link identifier
  *
  * @throws  LdapException   In case the connection is not possible
  */
 protected function prepareNewConnection()
 {
     if ($this->encryption === static::STARTTLS || $this->encryption === static::LDAPS) {
         $this->prepareTlsEnvironment();
     }
     $hostname = $this->hostname;
     if ($this->encryption === static::LDAPS) {
         $hostname = 'ldaps://' . $hostname;
     }
     $ds = ldap_connect($hostname, $this->port);
     try {
         $this->capabilities = $this->discoverCapabilities($ds);
         $this->discoverySuccess = true;
     } catch (LdapException $e) {
         Logger::debug($e);
         Logger::warning('LADP discovery failed, assuming default LDAP capabilities.');
         $this->capabilities = new Capability();
         // create empty default capabilities
         $this->discoverySuccess = false;
     }
     if ($this->encryption === static::STARTTLS) {
         $force_tls = false;
         if ($this->capabilities->hasStartTls()) {
             if (@ldap_start_tls($ds)) {
                 Logger::debug('LDAP STARTTLS succeeded');
             } else {
                 Logger::error('LDAP STARTTLS failed: %s', ldap_error($ds));
                 throw new LdapException('LDAP STARTTLS failed: %s', ldap_error($ds));
             }
         } elseif ($force_tls) {
             throw new LdapException('STARTTLS is required but not announced by %s', $this->hostname);
         } else {
             Logger::warning('LDAP STARTTLS enabled but not announced');
         }
     }
     // ldap_rename requires LDAPv3:
     if ($this->capabilities->hasLdapV3()) {
         if (!ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
             throw new LdapException('LDAPv3 is required');
         }
     } else {
         // TODO: remove this -> FORCING v3 for now
         ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
         Logger::warning('No LDAPv3 support detected');
     }
     // Not setting this results in "Operations error" on AD when using the whole domain as search base
     ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
     // ldap_set_option($ds, LDAP_OPT_DEREF, LDAP_DEREF_NEVER);
     return $ds;
 }