Beispiel #1
0
 /**
  * Migrar los perfiles con formato anterior a v1.2
  *
  * @return bool
  */
 public static function migrateProfiles()
 {
     $query = 'SELECT userprofile_id AS id,' . 'userprofile_name AS name,' . 'BIN(userProfile_pView) AS pView,' . 'BIN(userProfile_pViewPass) AS pViewPass,' . 'BIN(userProfile_pViewHistory) AS pViewHistory,' . 'BIN(userProfile_pEdit) AS pEdit,' . 'BIN(userProfile_pEditPass) AS pEditPass,' . 'BIN(userProfile_pAdd) AS pAdd,' . 'BIN(userProfile_pDelete) AS pDelete,' . 'BIN(userProfile_pFiles) AS pFiles,' . 'BIN(userProfile_pConfig) AS pConfig,' . 'BIN(userProfile_pConfigMasterPass) AS pConfigMasterPass,' . 'BIN(userProfile_pConfigBackup) AS pConfigBackup,' . 'BIN(userProfile_pAppMgmtCategories) AS pAppMgmtCategories,' . 'BIN(userProfile_pAppMgmtCustomers) AS pAppMgmtCustomers,' . 'BIN(userProfile_pUsers) AS pUsers,' . 'BIN(userProfile_pGroups) AS pGroups,' . 'BIN(userProfile_pProfiles) AS pProfiles,' . 'BIN(userProfile_pEventlog) AS pEventlog ' . 'FROM usrProfiles';
     DB::setReturnArray();
     $queryRes = DB::getResults($query, __FUNCTION__);
     if ($queryRes === false) {
         Log::writeNewLog(_('Migrar Perfiles'), _('Error al obtener perfiles'));
         return false;
     }
     foreach ($queryRes as $oldProfile) {
         $profile = new Profile();
         $profile->setId($oldProfile->id);
         $profile->setName($oldProfile->name);
         $profile->setAccAdd($oldProfile->pAdd);
         $profile->setAccView($oldProfile->pView);
         $profile->setAccViewPass($oldProfile->pViewPass);
         $profile->setAccViewHistory($oldProfile->pViewHistory);
         $profile->setAccEdit($oldProfile->pEdit);
         $profile->setAccEditPass($oldProfile->pEditPass);
         $profile->setAccDelete($oldProfile->pDelete);
         $profile->setConfigGeneral($oldProfile->pConfig);
         $profile->setConfigEncryption($oldProfile->pConfigMasterPass);
         $profile->setConfigBackup($oldProfile->pConfigBackup);
         $profile->setMgmCategories($oldProfile->pAppMgmtCategories);
         $profile->setMgmCustomers($oldProfile->pAppMgmtCustomers);
         $profile->setMgmUsers($oldProfile->pUsers);
         $profile->setMgmGroups($oldProfile->pGroups);
         $profile->setMgmProfiles($oldProfile->pProfiles);
         $profile->setEvl($oldProfile->pEventlog);
         if ($profile->profileUpdate() === false) {
             return false;
         }
     }
     $query = 'ALTER TABLE usrProfiles ' . 'DROP COLUMN userProfile_pAppMgmtCustomers,' . 'DROP COLUMN userProfile_pAppMgmtCategories,' . 'DROP COLUMN userProfile_pAppMgmtMenu,' . 'DROP COLUMN userProfile_pUsersMenu,' . 'DROP COLUMN userProfile_pConfigMenu,' . 'DROP COLUMN userProfile_pFiles,' . 'DROP COLUMN userProfile_pViewHistory,' . 'DROP COLUMN userProfile_pEventlog,' . 'DROP COLUMN userProfile_pEditPass,' . 'DROP COLUMN userProfile_pViewPass,' . 'DROP COLUMN userProfile_pDelete,' . 'DROP COLUMN userProfile_pProfiles,' . 'DROP COLUMN userProfile_pGroups,' . 'DROP COLUMN userProfile_pUsers,' . 'DROP COLUMN userProfile_pConfigBackup,' . 'DROP COLUMN userProfile_pConfigMasterPass,' . 'DROP COLUMN userProfile_pConfig,' . 'DROP COLUMN userProfile_pAdd,' . 'DROP COLUMN userProfile_pEdit,' . 'DROP COLUMN userProfile_pView';
     $queryRes = DB::getQuery($query, __FUNCTION__);
     $log = new Log(_('Migrar Perfiles'));
     if ($queryRes) {
         $log->addDescription(_('Operación realizada correctamente'));
     } else {
         $log->addDescription(_('Migrar Perfiles'), _('Fallo al realizar la operación'));
     }
     $log->writeLog();
     Email::sendEmail($log);
     return $queryRes;
 }
Beispiel #2
0
 /**
  * Iniciar la importación desde XML.
  *
  * @throws SPException
  * @return bool
  */
 public function doImport()
 {
     $import = null;
     $format = $this->detectXMLFormat();
     switch ($format) {
         case 'syspass':
             $import = new SyspassImport($this->_file);
             break;
         case 'keepass':
             $import = new KeepassImport($this->_file);
             break;
         case 'keepassx':
             $import = new KeepassXImport($this->_file);
             break;
     }
     if (is_object($import)) {
         Log::writeNewLog(_('Importar Cuentas'), _('Inicio'));
         Log::writeNewLog(_('Importar Cuentas'), _('Formato detectado') . ': ' . strtoupper($format));
         $import->setUserId($this->getUserId());
         $import->setUserGroupId($this->getUserGroupId());
         $import->setImportPass($this->getImportPass());
         $import->doImport();
     }
 }
Beispiel #3
0
 /**
  * Migrar valores de configuración.
  *
  * @param int $version El número de versión
  * @return bool
  */
 public static function upgradeConfig($version)
 {
     $mapParams = array('files_allowed_exts' => 'allowed_exts', 'files_allowed_size' => 'allowed_size', 'demo_enabled' => 'demoenabled', 'files_enabled' => 'filesenabled', 'ldap_base' => 'ldapbase', 'ldap_bindpass' => 'ldapbindpass', 'ldap_binduser' => 'ldapbinduser', 'ldap_enabled' => 'ldapenabled', 'ldap_group' => 'ldapgroup', 'ldap_server' => 'ldapserver', 'log_enabled' => 'logenabled', 'mail_enabled' => 'mailenabled', 'mail_from' => 'mailfrom', 'mail_pass' => 'mailpass', 'mail_port' => 'mailport', 'mail_requestsenabled' => 'mailrequestsenabled', 'mail_security' => 'mailsecurity', 'mail_server' => 'mailserver', 'mail_user' => 'mailuser', 'wiki_enabled' => 'wikienabled', 'wiki_filter' => 'wikifilter', 'wiki_pageurl' => 'wikipageurl', 'wiki_searchurl' => 'wikisearchurl');
     $currData = Config::getKeys(true);
     foreach ($mapParams as $newParam => $oldParam) {
         if (array_key_exists($oldParam, $currData)) {
             Config::setValue($newParam, $currData[$oldParam]);
             Config::deleteParam($oldParam);
         }
     }
     Log::writeNewLog(_('Actualizar Configuración'), _('Actualización de la Configuración realizada correctamente.') . ' (v' . $version . ')');
     return true;
 }
Beispiel #4
0
 /**
  * Crear el documento XML y guardarlo
  *
  * @return bool
  */
 public function makeXML()
 {
     try {
         $this->checkExportDir();
         $this->createRoot();
         $this->createMeta();
         $this->createCategories();
         $this->createCustomers();
         $this->createAccounts();
         $this->createHash();
         $this->writeXML();
     } catch (SPException $e) {
         Log::writeNewLog(_('Exportar XML'), sprintf('%s (%s)', $e->getMessage(), $e->getHint()));
         return false;
     }
     return true;
 }
Beispiel #5
0
 /**
  * Comprobar el hash de una clave.
  *
  * @param string $pwd          con la clave a comprobar
  * @param string $checkedHash con el hash a comprobar
  * @param bool   $isMPass      si es la clave maestra
  * @return bool
  */
 public static function checkHashPass($pwd, $checkedHash, $isMPass = false)
 {
     // Obtenemos el salt de la clave
     $salt = substr($checkedHash, 0, 72);
     // Obtenemos el hash SHA256
     $validHash = substr($checkedHash, 72);
     // Re-hash de la clave a comprobar
     $testHash = crypt($pwd, $salt);
     // Comprobar si el hash está en formato anterior a 12002
     if ($isMPass && strlen($checkedHash) === 128) {
         $check = hash("sha256", substr($checkedHash, 0, 64) . $pwd) == substr($checkedHash, 64, 64);
         if ($check) {
             ConfigDB::setValue('masterPwd', self::mkHashPassword($pwd));
             Log::writeNewLog(_('Aviso'), _('Se ha regenerado el HASH de clave maestra. No es necesaria ninguna acción.'));
         }
         return $check;
     }
     // Si los hashes son idénticos, la clave es válida
     return $testHash == $validHash;
 }
Beispiel #6
0
 /**
  * Obtener datos desde una URL usando CURL
  *
  * @param $url string La URL
  * @return bool|string
  */
 public static function getDataFromUrl($url)
 {
     if (!self::curlIsAvailable()) {
         return false;
     }
     $ch = curl_init($url);
     if (Config::getValue('proxy_enabled')) {
         curl_setopt($ch, CURLOPT_PROXY, Config::getValue('proxy_server'));
         curl_setopt($ch, CURLOPT_PROXYPORT, Config::getValue('proxy_port'));
         curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
         $proxyUser = Config::getValue('proxy_user');
         if ($proxyUser) {
             $proxyAuth = $proxyUser . ':' . Config::getValue('proxy_pass');
             curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyAuth);
         }
     }
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_HEADER, 0);
     curl_setopt($ch, CURLOPT_USERAGENT, "sysPass-App");
     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
     curl_setopt($ch, CURLOPT_TIMEOUT, 60);
     $data = curl_exec($ch);
     if ($data === false) {
         Log::writeNewLog(__FUNCTION__, curl_error($ch));
         return false;
     }
     return $data;
 }
 /**
  * Obtener los datos de las entradas de sysPass y crearlas
  *
  * @throws SPException
  */
 protected function processAccounts()
 {
     $line = 0;
     $lines = $this->_file->getFileContent();
     foreach ($lines as $data) {
         $line++;
         $fields = explode($this->_fieldDelimiter, $data);
         $numfields = count($fields);
         // Comprobar el número de campos de la línea
         if ($numfields !== $this->_numFields) {
             throw new SPException(SPException::SP_CRITICAL, sprintf(_('El número de campos es incorrecto (%d)'), $numfields), sprintf(_('Compruebe el formato del archivo CSV en línea %s'), $line));
         }
         // Eliminar las " del principio/fin de los campos
         array_walk($fields, function (&$value, $key) {
             $value = trim($value, '"');
         });
         // Asignar los valores del array a variables
         list($accountName, $customerName, $categoryName, $url, $login, $password, $notes) = $fields;
         // Obtener los ids de cliente, categoría y la clave encriptada
         $customerId = Customer::addCustomerReturnId($customerName);
         $categoryId = Category::addCategoryReturnId($categoryName);
         $pass = Crypt::encryptData($password);
         // Crear la nueva cuenta
         $this->setAccountName($accountName);
         $this->setAccountLogin($login);
         $this->setCategoryId($categoryId);
         $this->setCustomerId($customerId);
         $this->setAccountNotes($notes);
         $this->setAccountUrl($url);
         $this->setAccountPass($pass['data']);
         $this->setAccountPassIV($pass['iv']);
         if (!$this->addAccount()) {
             $log = new Log(_('Importar Cuentas'));
             $log->addDescription(_('Error importando cuenta'));
             $log->addDescription(sprintf(_('Error procesando línea %s'), $line));
             $log->writeLog();
         } else {
             Log::writeNewLog(_('Importar Cuentas'), sprintf(_('Cuenta importada: %s'), $accountName));
         }
     }
 }
Beispiel #8
0
 /**
  * Iniciar la importación de cuentas.
  *
  * @param array  $fileData  Los datos del archivo
  * @return array resultado del proceso
  */
 public static function doImport(&$fileData)
 {
     try {
         $file = new FileImport($fileData);
         switch ($file->getFileType()) {
             case 'text/csv':
             case 'application/vnd.ms-excel':
                 $import = new CsvImport($file);
                 $import->setFieldDelimiter(self::$csvDelimiter);
                 break;
             case 'text/xml':
                 $import = new XmlImport($file);
                 $import->setImportPass(self::$importPwd);
                 break;
             default:
                 throw new SPException(SPException::SP_WARNING, _('Tipo mime no soportado'), _('Compruebe el formato del archivo'));
         }
         $import->setUserId(self::$defUser);
         $import->setUserGroupId(self::$defGroup);
         $import->doImport();
     } catch (SPException $e) {
         Log::writeNewLog(_('Importar Cuentas'), $e->getMessage() . ';;' . $e->getHint());
         $result['error'] = array('description' => $e->getMessage(), 'hint' => $e->getHint());
         return $result;
     }
     Log::writeNewLog(_('Importar Cuentas'), _('Importación finalizada'));
     $result['ok'] = array(_('Importación finalizada'), _('Revise el registro de eventos para más detalles'));
     return $result;
 }
Beispiel #9
0
 /**
  * Migrar el grupo de los usuarios a la nueva tabla
  */
 public static function migrateUsersGroup()
 {
     $query = 'SELECT user_id, user_groupId FROM usrData';
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     if ($queryRes === false) {
         return false;
     }
     foreach ($queryRes as $user) {
         if (!Groups::addUsersForGroup(array($user->user_groupId), $user->user_id)) {
             Log::writeNewLog(_('Migrar Grupos'), sprintf('%s (%s)'), _('Error al migrar grupo del usuario'), $user->user_id);
         }
     }
     return true;
 }
Beispiel #10
0
 /**
  * Comprobar los permisos de acceso del usuario a los módulos de la aplicación.
  * Esta función comprueba los permisos del usuario para realizar una acción.
  * Si los permisos ya han sido obtenidos desde la BBDD, se utiliza el objeto creado
  * en la variable de sesión.
  *
  * @param string $action con el nombre de la acción
  * @param int    $userId opcional, con el Id del usuario
  * @return bool
  */
 public static function checkUserAccess($action, $userId = 0)
 {
     // Comprobamos si la cache de permisos está inicializada
     if (!is_object(Session::getUserProfile())) {
         //            error_log('ACL_CACHE_MISS');
         return false;
     }
     $curUserIsAdminApp = Session::getUserIsAdminApp();
     $curUserIsAdminAcc = Session::getUserIsAdminAcc();
     $curUserProfile = Session::getUserProfile();
     $curUserId = Session::getUserId();
     switch ($action) {
         case self::ACTION_ACC_VIEW:
             return $curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->isAccView() || $curUserProfile->isAccEdit();
         case self::ACTION_ACC_VIEW_PASS:
             return $curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->isAccViewPass();
         case self::ACTION_ACC_VIEW_HISTORY:
             return $curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->isAccViewHistory();
         case self::ACTION_ACC_EDIT:
             return $curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->isAccEdit();
         case self::ACTION_ACC_EDIT_PASS:
             return $curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->isAccEditPass();
         case self::ACTION_ACC_NEW:
             return $curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->isAccAdd();
         case self::ACTION_ACC_COPY:
             return $curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->isAccAdd() && $curUserProfile->isAccView();
         case self::ACTION_ACC_DELETE:
             return $curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->isAccDelete();
         case self::ACTION_ACC_FILES:
             return $curUserIsAdminApp || $curUserIsAdminAcc || $curUserProfile->isAccFiles();
         case self::ACTION_MGM:
             return $curUserIsAdminApp || $curUserProfile->isMgmCategories() || $curUserProfile->isMgmCustomers();
         case self::ACTION_CFG:
             return $curUserIsAdminApp || $curUserProfile->isConfigGeneral() || $curUserProfile->isConfigEncryption() || $curUserProfile->isConfigBackup() || $curUserProfile->isConfigImport();
         case self::ACTION_CFG_GENERAL:
             return $curUserIsAdminApp || $curUserProfile->isConfigGeneral();
         case self::ACTION_CFG_IMPORT:
             return $curUserIsAdminApp || $curUserProfile->isConfigImport();
         case self::ACTION_MGM_CATEGORIES:
             return $curUserIsAdminApp || $curUserProfile->isMgmCategories();
         case self::ACTION_MGM_CUSTOMERS:
             return $curUserIsAdminApp || $curUserProfile->isMgmCustomers();
         case self::ACTION_MGM_CUSTOMFIELDS:
             return $curUserIsAdminApp || $curUserProfile->isMgmCustomFields();
         case self::ACTION_CFG_ENCRYPTION:
             return $curUserIsAdminApp || $curUserProfile->isConfigEncryption();
         case self::ACTION_CFG_BACKUP:
             return $curUserIsAdminApp || $curUserProfile->isConfigBackup();
         case self::ACTION_USR:
             return $curUserIsAdminApp || $curUserProfile->isMgmUsers() || $curUserProfile->isMgmGroups() || $curUserProfile->isMgmProfiles();
         case self::ACTION_USR_USERS:
             return $curUserIsAdminApp || $curUserProfile->isMgmUsers();
         case self::ACTION_USR_USERS_EDITPASS:
             return $userId == $curUserId || $curUserIsAdminApp || $curUserProfile->isMgmUsers();
         case self::ACTION_USR_GROUPS:
             return $curUserIsAdminApp || $curUserProfile->isMgmGroups();
         case self::ACTION_USR_PROFILES:
             return $curUserIsAdminApp || $curUserProfile->isMgmProfiles();
         case self::ACTION_MGM_APITOKENS:
             return $curUserIsAdminApp || $curUserProfile->isMgmApiTokens();
         case self::ACTION_EVL:
             return $curUserIsAdminApp || $curUserProfile->isEvl();
     }
     Log::writeNewLog(__FUNCTION__, sprintf('%s \'%s\'', _('Denegado acceso a'), self::getActionName($action)));
     return false;
 }
Beispiel #11
0
 /**
  * Comprobar si los parámetros necesario de LDAP están establecidos.
  *
  * @return bool
  */
 public static function checkLDAPParams()
 {
     self::$_isADS = Config::getValue('ldap_ads', false);
     self::$_searchBase = Config::getValue('ldap_base');
     self::$_ldapServer = !self::$_isADS ? Config::getValue('ldap_server') : LdapADS::getADServer(Config::getValue('ldap_server'));
     self::$_bindDN = Config::getValue('ldap_binduser');
     self::$_bindPass = Config::getValue('ldap_bindpass');
     self::$_ldapGroup = Config::getValue('ldap_group', '*');
     if (!self::$_searchBase || !self::$_ldapServer || !self::$_bindDN || !self::$_bindPass) {
         Log::writeNewLog(__FUNCTION__, _('Los parámetros de LDAP no están configurados'));
         return false;
     }
     return true;
 }