protected function connection()
 {
     if ($this->connection === null) {
         $this->connection = ResourceFactory::create($this->settings['resource']);
     }
     return $this->connection;
 }
Example #2
0
 /**
  * Create a new monitoring backend
  */
 public function createbackendAction()
 {
     $form = new BackendConfigForm();
     $form->setRedirectUrl('monitoring/config');
     $form->setTitle($this->translate('Create New Monitoring Backend'));
     $form->setIniConfig($this->Config('backends'));
     try {
         $form->setResourceConfig(ResourceFactory::getResourceConfigs());
     } catch (ConfigurationError $e) {
         if ($this->hasPermission('config/application/resources')) {
             Notification::error($e->getMessage());
             $this->redirectNow('config/createresource');
         }
         throw $e;
         // No permission for resource configuration, show the error
     }
     $form->setOnSuccess(function (BackendConfigForm $form) {
         try {
             $form->add(array_filter($form->getValues()));
         } catch (Exception $e) {
             $form->error($e->getMessage());
             return false;
         }
         if ($form->save()) {
             Notification::success(t('Monitoring backend successfully created'));
             return true;
         }
         return false;
     });
     $form->handleRequest();
     $this->view->form = $form;
     $this->render('form');
 }
Example #3
0
 /**
  * Set the resource configuration to use
  *
  * @param   array   $config
  *
  * @return  $this
  */
 public function setResourceConfig(array $config)
 {
     $resourceConfig = new Config();
     $resourceConfig->setSection($config['name'], $config);
     ResourceFactory::setConfig($resourceConfig);
     $this->config = $config;
     return $this;
 }
Example #4
0
 /**
  * Validate the resource configuration by trying to connect with it
  *
  * @param   Form    $form   The form to fetch the configuration values from
  *
  * @return  bool            Whether validation succeeded or not
  */
 public static function isValidResource(Form $form)
 {
     $result = ResourceFactory::createResource(new ConfigObject($form->getValues()))->inspect();
     if ($result->hasError()) {
         $form->addError(sprintf('%s (%s)', $form->translate('Connectivity validation failed, connection to the given resource not possible.'), $result->getError()));
     }
     // TODO: display diagnostics in $result->toArray() to the user
     return !$result->hasError();
 }
 /**
  * Return the names of all configured database resources
  *
  * @return  array
  */
 protected function getDatabaseResourceNames()
 {
     $names = array();
     foreach (ResourceFactory::getResourceConfigs() as $name => $config) {
         if (strtolower($config->type) === 'db') {
             $names[] = $name;
         }
     }
     return $names;
 }
Example #6
0
 protected static function enumResources($type)
 {
     $resources = array();
     foreach (ResourceFactory::getResourceConfigs() as $name => $resource) {
         if ($resource->type === $type && self::resourceIsAllowed($name)) {
             $resources[$name] = $name;
         }
     }
     return $resources;
 }
Example #7
0
 /**
  * Check whether ssh identity resources exists or not
  *
  * @return boolean
  */
 public function hasResources()
 {
     $resourceConfig = ResourceFactory::getResourceConfigs();
     foreach ($resourceConfig as $name => $resource) {
         if ($resource->type === 'ssh') {
             return true;
         }
     }
     return false;
 }
Example #8
0
 /**
  * Display a form to create a new backend
  */
 public function createbackendAction()
 {
     $form = new BackendConfigForm();
     $form->setTitle($this->translate('Add New Backend'));
     $form->setIniConfig($this->Config('backends'));
     $form->setResourceConfig(ResourceFactory::getResourceConfigs());
     $form->setRedirectUrl('monitoring/config');
     $form->handleRequest();
     $this->view->form = $form;
 }
Example #9
0
 /**
  * Validate the resource configuration by trying to connect with it
  *
  * @param   Form    $form   The form to fetch the configuration values from
  *
  * @return  bool            Whether validation succeeded or not
  */
 public static function isValidResource(Form $form)
 {
     try {
         $resource = ResourceFactory::createResource(new ConfigObject($form->getValues()));
         $resource->getConnection()->getConnection();
     } catch (Exception $e) {
         $form->addError($form->translate('Connectivity validation failed, connection to the given resource not possible.'));
         return false;
     }
     return true;
 }
 protected function createAccount()
 {
     try {
         $backend = new DbUserBackend(ResourceFactory::createResource(new ConfigObject($this->data['adminAccountData']['resourceConfig'])));
         if ($backend->select()->where('user_name', $this->data['adminAccountData']['username'])->count() === 0) {
             $backend->insert('user', array('user_name' => $this->data['adminAccountData']['username'], 'password' => $this->data['adminAccountData']['password'], 'is_active' => true));
         }
     } catch (Exception $e) {
         $this->dbError = $e;
         return false;
     }
     $this->dbError = false;
     return true;
 }
Example #11
0
 /**
  * @see Form::createElements()
  */
 public function createElements(array $formData)
 {
     $this->addElement('text', 'global_module_path', array('label' => $this->translate('Module Path'), 'required' => true, 'value' => implode(':', Icinga::app()->getModuleManager()->getModuleDirs()), 'description' => $this->translate('Contains the directories that will be searched for available modules, separated by ' . 'colons. Modules that don\'t exist in these directories can still be symlinked in ' . 'the module folder, but won\'t show up in the list of disabled modules.')));
     $this->addElement('select', 'preferences_store', array('required' => true, 'autosubmit' => true, 'label' => $this->translate('User Preference Storage Type'), 'multiOptions' => array('ini' => $this->translate('File System (INI Files)'), 'db' => $this->translate('Database'), 'none' => $this->translate('Don\'t Store Preferences'))));
     if (isset($formData['preferences_store']) && $formData['preferences_store'] === 'db') {
         $backends = array();
         foreach (ResourceFactory::getResourceConfigs()->toArray() as $name => $resource) {
             if ($resource['type'] === 'db') {
                 $backends[$name] = $name;
             }
         }
         $this->addElement('select', 'preferences_resource', array('required' => true, 'multiOptions' => $backends, 'label' => $this->translate('Database Connection')));
     }
     return $this;
 }
 /**
  * Load all available ssh identity resources
  *
  * @return $this
  *
  * @throws \Icinga\Exception\ConfigurationError
  */
 public function loadResources()
 {
     $resourceConfig = ResourceFactory::getResourceConfigs();
     $resources = array();
     foreach ($resourceConfig as $name => $resource) {
         if ($resource->type === 'ssh') {
             $resources['ssh'][$name] = $name;
         }
     }
     if (empty($resources)) {
         throw new ConfigurationError($this->translate('Could not find any valid monitoring instance resources'));
     }
     $this->resources = $resources;
     return $this;
 }
Example #13
0
 /**
  * Validate the resource configuration by trying to connect with it
  *
  * @param   Form    $form   The form to fetch the configuration values from
  *
  * @return  bool            Whether validation succeeded or not
  */
 public static function isValidResource(Form $form)
 {
     try {
         $resource = ResourceFactory::createResource(new ConfigObject($form->getValues()));
         $resource->bind();
     } catch (Exception $e) {
         $msg = $form->translate('Connectivity validation failed, connection to the given resource not possible.');
         if ($error = $e->getMessage()) {
             $msg .= ' (' . $error . ')';
         }
         $form->addError($msg);
         return false;
     }
     return true;
 }
Example #14
0
 protected function createMembership()
 {
     try {
         $backend = new DbUserGroupBackend(ResourceFactory::createResource(new ConfigObject($this->data['resourceConfig'])));
         $groupName = mt('setup', 'Administrators', 'setup.role.name');
         $userName = $this->data['username'];
         if ($backend->select()->from('group_membership')->where('group_name', $groupName)->where('user_name', $userName)->count() === 0) {
             $backend->insert('group_membership', array('group_name' => $groupName, 'user_name' => $userName));
             $this->memberError = false;
         }
     } catch (Exception $e) {
         $this->memberError = $e;
         return false;
     }
     return true;
 }
 /**
  * @see Form::createElements()
  */
 public function createElements(array $formData)
 {
     $this->addElement('checkbox', 'global_show_stacktraces', array('required' => true, 'value' => true, 'label' => $this->translate('Show Stacktraces'), 'description' => $this->translate('Set whether to show an exception\'s stacktrace by default. This can also' . ' be set in a user\'s preferences with the appropriate permission.')));
     $this->addElement('text', 'global_module_path', array('label' => $this->translate('Module Path'), 'required' => true, 'value' => implode(':', Icinga::app()->getModuleManager()->getModuleDirs()), 'description' => $this->translate('Contains the directories that will be searched for available modules, separated by ' . 'colons. Modules that don\'t exist in these directories can still be symlinked in ' . 'the module folder, but won\'t show up in the list of disabled modules.')));
     $this->addElement('select', 'global_config_backend', array('required' => true, 'autosubmit' => true, 'label' => $this->translate('User Preference Storage Type'), 'multiOptions' => array('ini' => $this->translate('File System (INI Files)'), 'db' => $this->translate('Database'), 'none' => $this->translate('Don\'t Store Preferences'))));
     if (isset($formData['global_config_backend']) && $formData['global_config_backend'] === 'db') {
         $backends = array();
         foreach (ResourceFactory::getResourceConfigs()->toArray() as $name => $resource) {
             if ($resource['type'] === 'db') {
                 $backends[$name] = $name;
             }
         }
         $this->addElement('select', 'global_config_resource', array('required' => true, 'multiOptions' => $backends, 'label' => $this->translate('Database Connection')));
     }
     $this->addElement('text', 'datetime_format', array('label' => $this->translate('Datetime format'), 'required' => true, 'value' => $this->translate('Y-m-d H:i:s'), 'description' => $this->translate('Datetime format for use when displaying timestamps in history views. Uses PHP ' . 'date() format, see PHP documentation for syntax.')));
     return $this;
 }
Example #16
0
 /**
  * Create and add elements to this form
  *
  * @param   array   $formData
  */
 public function createElements(array $formData)
 {
     $isAd = isset($formData['type']) ? $formData['type'] === 'msldap' : false;
     $this->addElement('text', 'name', array('required' => true, 'label' => $this->translate('Backend Name'), 'description' => $this->translate('The name of this authentication provider that is used to differentiate it from others.')));
     $this->addElement('select', 'resource', array('required' => true, 'label' => $this->translate('LDAP Connection'), 'description' => $this->translate('The LDAP connection to use for authenticating with this provider.'), 'multiOptions' => !empty($this->resources) ? array_combine($this->resources, $this->resources) : array()));
     $baseDn = null;
     $hasAdOid = false;
     if (!$isAd && !empty($this->resources)) {
         $this->addElement('button', 'discovery_btn', array('type' => 'submit', 'value' => 'discovery_btn', 'label' => $this->translate('Discover', 'A button to discover LDAP capabilities'), 'title' => $this->translate('Push to fill in the chosen connection\'s default settings.'), 'decorators' => array(array('ViewHelper', array('separator' => '')), array('HtmlTag', array('tag' => 'div', 'class' => 'element'))), 'formnovalidate' => 'formnovalidate'));
         $this->addDisplayGroup(array('resource', 'discovery_btn'), 'connection_discovery', array('decorators' => array('FormElements', array('HtmlTag', array('tag' => 'div', 'class' => 'control-group')))));
         if ($this->getElement('discovery_btn')->isChecked()) {
             $connection = ResourceFactory::create(isset($formData['resource']) ? $formData['resource'] : reset($this->resources));
             try {
                 $capabilities = $connection->bind()->getCapabilities();
                 $baseDn = $capabilities->getDefaultNamingContext();
                 $hasAdOid = $capabilities->isActiveDirectory();
             } catch (Exception $e) {
                 $this->warning(sprintf($this->translate('Failed to discover the chosen LDAP connection: %s'), $e->getMessage()));
             }
         }
     }
     if ($isAd || $hasAdOid) {
         // ActiveDirectory defaults
         $userClass = 'user';
         $filter = '!(objectClass=computer)';
         $userNameAttribute = 'sAMAccountName';
     } else {
         // OpenLDAP defaults
         $userClass = 'inetOrgPerson';
         $filter = null;
         $userNameAttribute = 'uid';
     }
     $this->addElement('text', 'user_class', array('preserveDefault' => true, 'required' => !$isAd, 'ignore' => $isAd, 'disabled' => $isAd ?: null, 'label' => $this->translate('LDAP User Object Class'), 'description' => $this->translate('The object class used for storing users on the LDAP server.'), 'value' => $userClass));
     $this->addElement('text', 'filter', array('preserveDefault' => true, 'allowEmpty' => true, 'value' => $filter, 'label' => $this->translate('LDAP Filter'), 'description' => $this->translate('An additional filter to use when looking up users using the specified connection. ' . 'Leave empty to not to use any additional filter rules.'), 'requirement' => $this->translate('The filter needs to be expressed as standard LDAP expression.' . ' (e.g. &(foo=bar)(bar=foo) or foo=bar)'), 'validators' => array(array('Callback', false, array('callback' => function ($v) {
         // This is not meant to be a full syntax check. It will just
         // ensure that we can safely strip unnecessary parentheses.
         $v = trim($v);
         return !$v || $v[0] !== '(' || (strpos($v, ')(') !== false ? substr($v, -2) === '))' : substr($v, -1) === ')');
     }, 'messages' => array('callbackValue' => $this->translate('The filter is invalid. Please check your syntax.')))))));
     $this->addElement('text', 'user_name_attribute', array('preserveDefault' => true, 'required' => !$isAd, 'ignore' => $isAd, 'disabled' => $isAd ?: null, 'label' => $this->translate('LDAP User Name Attribute'), 'description' => $this->translate('The attribute name used for storing the user name on the LDAP server.'), 'value' => $userNameAttribute));
     $this->addElement('hidden', 'backend', array('disabled' => true, 'value' => $isAd ? 'msldap' : 'ldap'));
     $this->addElement('text', 'base_dn', array('preserveDefault' => true, 'required' => false, 'label' => $this->translate('LDAP Base DN'), 'description' => $this->translate('The path where users can be found on the LDAP server. Leave ' . 'empty to select all users available using the specified connection.'), 'value' => $baseDn));
 }
 /**
  * Get this backend's internal resource
  *
  * @return mixed
  */
 public function getResource()
 {
     if ($this->resource === null) {
         $this->resource = ResourceFactory::create($this->config->get('resource'));
         if ($this->is('ido') && $this->resource->getDbType() !== 'oracle') {
             // TODO(el): The resource should set the table prefix
             $this->resource->setTablePrefix('icinga_');
         }
     }
     return $this->resource;
 }
Example #18
0
 /**
  * Create a resource by using the given form's values and return its inspection results
  *
  * @param   Form    $form
  *
  * @return  Inspection
  */
 public static function inspectResource(Form $form)
 {
     if ($form->getValue('type') !== 'ssh') {
         $resource = ResourceFactory::createResource(new ConfigObject($form->getValues()));
         if ($resource instanceof Inspectable) {
             return $resource->inspect();
         }
     }
 }
 /**
  * Return the configuration for the chosen resource
  *
  * @return  ConfigObject
  */
 public function getResourceConfig()
 {
     return ResourceFactory::getResourceConfig($this->getValue('resource'));
 }
Example #20
0
 protected function enumResources()
 {
     $resources = array();
     $allowed = array('mysql', 'pgsql');
     foreach (ResourceFactory::getResourceConfigs() as $name => $resource) {
         if ($resource->type === 'db' && in_array($resource->db, $allowed)) {
             $resources[$name] = $name;
         }
     }
     return $resources;
 }
 /**
  * Return the names of all configured LDAP user backends
  *
  * @param   LdapConnection  $resource
  *
  * @return  array
  */
 protected function getLdapUserBackendNames(LdapConnection $resource)
 {
     $names = array();
     foreach (UserBackend::getBackendConfigs() as $name => $config) {
         if (in_array(strtolower($config->backend), array('ldap', 'msldap'))) {
             $backendResource = ResourceFactory::create($config->resource);
             if ($backendResource->getHostname() === $resource->getHostname() && $backendResource->getPort() === $resource->getPort()) {
                 $names[] = $name;
             }
         }
     }
     return $names;
 }
Example #22
0
 /**
  * Creates an array of Icinga\Data\Db\DbConnection
  *
  * @param   string $name
  *
  * @return  array
  */
 protected function createDbConnectionFor($name)
 {
     try {
         $conn = ResourceFactory::createResource($this->createDbConfigFor($name));
     } catch (Exception $e) {
         $conn = $e->getMessage();
     }
     return array(array($conn));
 }
 /**
  * Create and add elements to this form
  *
  * @param   array   $formData
  */
 public function createElements(array $formData)
 {
     // LdapUserGroupBackendForm requires these factories to provide valid configurations
     ResourceFactory::setConfig($this->createResourceConfiguration());
     UserBackend::setConfig($this->createBackendConfiguration());
     $backendForm = new LdapUserGroupBackendForm();
     $formData['type'] = 'ldap';
     $backendForm->create($formData);
     $backendForm->getElement('name')->setValue('icingaweb2');
     $this->addSubForm($backendForm, 'backend_form');
     $backendForm->addElement('hidden', 'resource', array('required' => true, 'value' => $this->resourceConfig['name'], 'decorators' => array('ViewHelper')));
     $backendForm->addElement('hidden', 'user_backend', array('required' => true, 'value' => $this->backendConfig['name'], 'decorators' => array('ViewHelper')));
 }
Example #24
0
 /**
  * Use a given resource to set the user and the key
  *
  * @param string
  *
  * @throws ConfigurationError
  */
 public function setResource($resource = null)
 {
     $config = ResourceFactory::getResourceConfig($resource);
     if (!isset($config->user)) {
         throw new ConfigurationError(t("Can't send external Icinga Command. Remote user is missing"));
     }
     if (!isset($config->private_key)) {
         throw new ConfigurationError(t("Can't send external Icinga Command. The private key for the remote user is missing"));
     }
     $this->setUser($config->user);
     $this->setPrivateKey($config->private_key);
 }
Example #25
0
 /**
  * Action for editing user backends
  */
 public function edituserbackendAction()
 {
     $this->assertPermission('config/application/userbackend');
     $form = new UserBackendConfigForm();
     $form->setTitle($this->translate('Edit User Backend'));
     $form->setIniConfig(Config::app('authentication'));
     $form->setResourceConfig(ResourceFactory::getResourceConfigs());
     $form->setRedirectUrl('config/userbackend');
     $form->setAction(Url::fromRequest());
     $form->handleRequest();
     $this->view->form = $form;
     $this->render('userbackend/modify');
 }
Example #26
0
 public static function fromResourceName($name)
 {
     return new static(ResourceFactory::getResourceConfig($name));
 }
Example #27
0
 /**
  * Create and return a user backend with the given name and given configuration applied to it
  *
  * @param   string          $name
  * @param   ConfigObject    $backendConfig
  *
  * @return  UserBackendInterface
  *
  * @throws  ConfigurationError
  */
 public static function create($name, ConfigObject $backendConfig = null)
 {
     if ($backendConfig === null) {
         self::assertBackendsExist();
         if (self::$backends->hasSection($name)) {
             $backendConfig = self::$backends->getSection($name);
         } else {
             throw new ConfigurationError('User backend "%s" does not exist', $name);
         }
     }
     if ($backendConfig->name !== null) {
         $name = $backendConfig->name;
     }
     if (!($backendType = strtolower($backendConfig->backend))) {
         throw new ConfigurationError('Authentication configuration for user backend "%s" is missing the \'backend\' directive', $name);
     }
     if ($backendType === 'external') {
         $backend = new ExternalBackend($backendConfig);
         $backend->setName($name);
         return $backend;
     }
     if (in_array($backendType, static::$defaultBackends)) {
         // The default backend check is the first one because of performance reasons:
         // Do not attempt to load a custom user backend unless it's actually required
     } elseif (($customClass = static::getCustomUserBackend($backendType)) !== null) {
         $backend = new $customClass($backendConfig);
         if (!is_a($backend, 'Icinga\\Authentication\\User\\UserBackendInterface')) {
             throw new ConfigurationError('Cannot utilize user backend of type "%s". Class "%s" does not implement UserBackendInterface', $backendType, $customClass);
         }
         $backend->setName($name);
         return $backend;
     } else {
         throw new ConfigurationError('Authentication configuration for user backend "%s" defines an invalid backend type.' . ' Backend type "%s" is not supported', $name, $backendType);
     }
     if ($backendConfig->resource === null) {
         throw new ConfigurationError('Authentication configuration for user backend "%s" is missing the \'resource\' directive', $name);
     }
     $resource = ResourceFactory::create($backendConfig->resource);
     switch ($backendType) {
         case 'db':
             $backend = new DbUserBackend($resource);
             break;
         case 'msldap':
             $backend = new LdapUserBackend($resource);
             $backend->setBaseDn($backendConfig->base_dn);
             $backend->setUserClass($backendConfig->get('user_class', 'user'));
             $backend->setUserNameAttribute($backendConfig->get('user_name_attribute', 'sAMAccountName'));
             $backend->setFilter($backendConfig->filter);
             break;
         case 'ldap':
             $backend = new LdapUserBackend($resource);
             $backend->setBaseDn($backendConfig->base_dn);
             $backend->setUserClass($backendConfig->get('user_class', 'inetOrgPerson'));
             $backend->setUserNameAttribute($backendConfig->get('user_name_attribute', 'uid'));
             $backend->setFilter($backendConfig->filter);
             break;
     }
     $backend->setName($name);
     return $backend;
 }
Example #28
0
 /**
  * Return whether a single icinga instance is writing to the given resource
  *
  * @param   Form            $form
  * @param   ConfigObject    $resourceConfig
  *
  * @return  bool                                True if it's a single instance, false if none
  *                                              or multiple instances are writing to it
  */
 public static function isValidIdoInstance(Form $form, ConfigObject $resourceConfig)
 {
     $db = ResourceFactory::createResource($resourceConfig);
     $rowCount = $db->select()->from('icinga_instances')->count();
     if ($rowCount === 0) {
         $form->warning($form->translate('There is currently no icinga instance writing to the IDO. Make sure ' . 'that a icinga instance is configured and able to write to the IDO.'));
         return false;
     } elseif ($rowCount > 1) {
         $form->warning($form->translate('There is currently more than one icinga instance writing to the IDO. You\'ll see all objects from all' . ' instances without any differentation. If this is not desired, consider setting up a separate IDO' . ' for each instance.'));
         return false;
     }
     return true;
 }
 /**
  * Edit a user backend
  */
 public function edituserbackendAction()
 {
     $this->assertPermission('config/application/userbackend');
     $backendName = $this->params->getRequired('backend');
     $form = new UserBackendConfigForm();
     $form->setRedirectUrl('config/userbackend');
     $form->setIniConfig(Config::app('authentication'));
     $form->setOnSuccess(function (UserBackendConfigForm $form) use($backendName) {
         try {
             $form->edit($backendName, array_map(function ($v) {
                 return $v !== '' ? $v : null;
             }, $form->getValues()));
         } catch (Exception $e) {
             $form->error($e->getMessage());
             return false;
         }
         if ($form->save()) {
             Notification::success(sprintf(t('User backend "%s" successfully updated'), $backendName));
             return true;
         }
         return false;
     });
     try {
         $form->load($backendName);
         $form->setResourceConfig(ResourceFactory::getResourceConfigs());
         $form->handleRequest();
     } catch (NotFoundError $_) {
         $this->httpNotFound(sprintf($this->translate('User backend "%s" not found'), $backendName));
     }
     $this->renderForm($form, $this->translate('Update User Backend'));
 }
 /**
  * Set up the resource factory
  *
  * @return $this
  */
 protected function setupResourceFactory()
 {
     try {
         $config = Config::app('resources');
         ResourceFactory::setConfig($config);
     } catch (NotReadableError $e) {
         Logger::error(new IcingaException('Cannot load resource configuration. An exception was thrown:', $e));
     }
     return $this;
 }