Beispiel #1
0
 /**
  * Renew session
  */
 public function action_renew()
 {
     $input = request::input(null, true, true);
     $result = ['success' => false, 'error' => []];
     if (!empty($input['token'])) {
         $crypt = new crypt();
         $token_data = $crypt->token_validate($input['token'], ['skip_time_validation' => true]);
         if (!($token_data === false || $token_data['id'] !== 'general')) {
             $result['success'] = true;
         }
     }
     layout::render_as($result, 'application/json');
 }
Beispiel #2
0
 /**
  * This would process error message sent from frontend
  */
 public function action_index()
 {
     $input = request::input();
     if (!empty($input['token'])) {
         $crypt = new crypt();
         $token_data = $crypt->token_validate($input['token'], ['skip_time_validation' => true]);
         if (!($token_data === false || $token_data['id'] !== 'general')) {
             $input['data'] = json_decode($input['data'], true);
             error_base::error_handler('javascript', $input['data']['message'], $input['data']['file'], $input['data']['line']);
         }
     }
     // rendering
     layout::render_as(file_get_contents(__DIR__ . '/error.png'), 'image/png');
 }
 public static function init()
 {
     $username = get('username');
     $password = get('password');
     if (!$username) {
         exit('Пожалуйста, укажите имя для пользователя.');
     }
     if (!$password) {
         exit('Пожалуйста, укажите пароль пользователю.');
     }
     if (string::length($password) < 6) {
         exit('Ваш пароль не может быть менее 6 символов.');
     }
     $user = users::get_by_name($username);
     if (!$user) {
         exit('Данного пользователя не существует.');
     }
     if (!crypt::is_valid($password, $user->hash, $user->salt)) {
         exit('Указанный вами пароль не совпадает с тем, что был указан при регистрации.');
     }
     $is_authorized = template_session::login($user->id);
     if (!$is_authorized) {
         exit('Нарушение логической цепи: авторизация не произведена.');
     }
 }
 public static function is_valid($password, $hash, $salt)
 {
     list($tmp_hash, $tmp_salt) = crypt::password($password, $salt);
     if ($tmp_hash === $hash and $tmp_salt === $salt) {
         return true;
     }
     return false;
 }
 public static function add($name, $password, $role_id)
 {
     list($hash, $salt) = crypt::password($password);
     $q = new cquery(RUDE_DATABASE_TABLE_USERS);
     $q->add(RUDE_DATABASE_FIELD_NAME, $name);
     $q->add(RUDE_DATABASE_FIELD_HASH, $hash);
     $q->add(RUDE_DATABASE_FIELD_SALT, $salt);
     $q->add(RUDE_DATABASE_FIELD_ROLE_ID, $role_id);
     $q->query();
     return $q->get_id();
 }
 function testPasswordEncryption()
 {
     global $opt;
     $opt['logic']['password_hash'] = false;
     $plain_text = 'very important data';
     $md5HashedPassword = crypt::encryptPassword($plain_text);
     $this->assertEquals('c75ac45eabed45d667359462b6a8e93e', $md5HashedPassword);
     $opt['logic']['password_hash'] = true;
     $opt['logic']['password_salt'] = '?S<,XyB1Y[y_Gz>b';
     $encryptedPassword = crypt::encryptPassword($plain_text);
     $this->assertEquals('8b1d376a76e6430738d8322a6e3f4ebd5e8632f67052de7b74c8ca745bda6f11c7ea05db7de0c14bb097d3033557eb81d7fae21de988efc5353ed2f77dab504b', $encryptedPassword);
 }
function AddManager($username, $password, $bd)
{
    include dirname(__FILE__) . "/ressources/settings.inc";
    $password = crypt::hmac('artica', $password);
    $date = date('Y-m-d H:i:s');
    $sql = "SELECT user_pwd FROM dotclear_user WHERE user_id='{$uid}'";
    $ligne = @mysql_fetch_array(zQUERY_SQL($bd, $sql));
    if ($ligne["user_pwd"] == null) {
        $sql = "INSERT INTO `dotclear_user` (`user_id`, `user_super`, `user_status`, `user_pwd`, `user_recover_key`,\n \t\t\t\t`user_name`, `user_firstname`, `user_displayname`, `user_email`, `user_url`,\n  \t\t\t\t`user_desc`, `user_default_blog`, `user_options`, `user_lang`, `user_tz`,\n   \t\t\t\t`user_post_status`, `user_creadt`,\n    \t\t\t`user_upddt`) VALUES\n\t\t\t\t('{$username}', 1, 1, '{$password}', NULL, '{$username}', '{$username}', NULL, '*****@*****.**', \n\t\t\t\tNULL, NULL, NULL, 'a:3:{s:9:\"edit_size\";i:24;s:14:\"enable_wysiwyg\";b:1;s:11:\"post_format\";s:4:\"wiki\";}', 'en',\n\t\t\t\t 'Europe/Berlin', -2, '{$date}', '{$date}');";
        zQUERY_SQL($bd, $sql);
    } else {
        $sql = "UPDATE `artica_backup`.`dotclear_user` SET `user_pwd` = '{$password}' WHERE `dotclear_user`.`user_id` = '{$username}' LIMIT 1 ;";
        zQUERY_SQL($bd, $sql);
    }
}
Beispiel #8
0
 public function login()
 {
     $this->pass = parent::encrypt($this->pass);
     $select = DataBase::connect()->prepare("select * from client where login=:login and pass=:pass");
     $ex = $select->execute(array('login' => $this->login, 'pass' => $this->pass));
     $e = $select->rowCount();
     if ($e > 0) {
         while ($line = $select->fetch(PDO::FETCH_OBJ)) {
             $this->id = $line->id_client;
         }
         session_start();
         $_SESSION["login"] = $this->login;
         $_SESSION["pass"] = $this->pass;
         $_SESSION["id"] = $this->id;
         header('location:compte.php');
     } else {
         return false;
     }
 }
Beispiel #9
0
function addUserSignup($user_id, $user_fullname, $user_email, $password, $lang, $token)
{
    global $core;
    # Clean Up user_id
    $user_id = preg_replace("( )", "_", $user_id);
    $user_id = cleanString($user_id);
    # Check if user's information already exist in not pending users
    $rs1 = $core->con->select("SELECT user_id, user_fullname, user_email\n\t\tFROM " . $core->prefix . "user\n\t\tWHERE lower(user_id) = '" . strtolower($user_id) . "'\n\t\tOR lower(user_fullname) = '" . strtolower($user_fullname) . "'\n\t\tOR lower(user_email) = '" . strtolower($user_email) . "'");
    if ($rs1->count() > 0) {
        if ($rs1->f('user_id') == $user_id) {
            $error[] = sprintf(T_('The user %s already exists'), $user_id);
        }
        if ($rs1->f('user_fullname') == $user_fullname) {
            $error[] = sprintf(T_('The user %s already exists'), $user_fullname);
        }
        if ($rs1->f('user_email') == $user_email) {
            $error[] = sprintf(T_('The email address %s is already in use'), $user_email);
        }
    } else {
        # Check if website is already in use
        $rs2 = $core->con->select("SELECT " . $core->prefix . "user.user_id\n\t\t\tFROM " . $core->prefix . "user, " . $core->prefix . "site\n\t\t\tWHERE " . $core->prefix . "site.user_id = " . $core->prefix . "user.user_id\n\t\t\tAND site_url = '" . $url . "'");
        if ($rs2->count() > 0) {
            $error[] = sprintf(T_('The website %s is already assigned to the user %s'), $url, $user_id);
        }
    }
    # All OK
    if (empty($error)) {
        $cur = $core->con->openCursor($core->prefix . 'user');
        $cur->user_id = $user_id;
        $cur->user_fullname = $user_fullname;
        $cur->user_email = $user_email;
        $cur->user_pwd = crypt::hmac('BP_MASTER_KEY', $password);
        $cur->user_token = $token;
        $cur->user_status = 0;
        $cur->user_lang = $lang;
        $cur->created = array(' NOW() ');
        $cur->modified = array(' NOW() ');
        $cur->insert();
    }
    return $error;
}
Beispiel #10
0
foreach ($core->getFormaters() as $v) {
    $formaters_combo[$v] = $v;
}
foreach ($core->blog->getAllPostStatus() as $k => $v) {
    $status_combo[$v] = $k;
}
# Language codes
$langs = l10n::getISOcodes(1, 1);
foreach ($langs as $k => $v) {
    $lang_avail = $v == 'en' || is_dir(DC_L10N_ROOT . '/' . $v);
    $lang_combo[] = new formSelectOption($k, $v, $lang_avail ? 'avail10n' : '');
}
# Add or update user
if (isset($_POST['user_name'])) {
    try {
        $pwd_check = !empty($_POST['cur_pwd']) && $core->auth->checkPassword(crypt::hmac(DC_MASTER_KEY, $_POST['cur_pwd']));
        if ($core->auth->allowPassChange() && !$pwd_check && $user_email != $_POST['user_email']) {
            throw new Exception(__('If you want to change your email or password you must provide your current password.'));
        }
        $cur = $core->con->openCursor($core->prefix . 'user');
        $cur->user_name = $user_name = $_POST['user_name'];
        $cur->user_firstname = $user_firstname = $_POST['user_firstname'];
        $cur->user_displayname = $user_displayname = $_POST['user_displayname'];
        $cur->user_email = $user_email = $_POST['user_email'];
        $cur->user_url = $user_url = $_POST['user_url'];
        $cur->user_lang = $user_lang = $_POST['user_lang'];
        $cur->user_tz = $user_tz = $_POST['user_tz'];
        $cur->user_post_status = $user_post_status = $_POST['user_post_status'];
        $user_options['edit_size'] = (int) $_POST['user_edit_size'];
        if ($user_options['edit_size'] < 1) {
            $user_options['edit_size'] = 10;
     $sql = "SELECT user_id, user_fullname, user_email FROM " . $core->prefix . "user\n\t\t\t\tWHERE lower(user_id) != '" . strtolower($user_id) . "'\n\t\t\t\tAND (lower(user_fullname) = '" . strtolower($new_fullname['value']) . "'\n\t\t\t\tOR lower(user_email) = '" . strtolower($new_email['value']) . "')";
     $rs1 = $core->con->select($sql);
     if ($rs1->count() > 0) {
         if ($rs1->f('user_fullname') == $new_fullname['value']) {
             $error[] = sprintf(T_('The user %s already exists'), $new_fullname['value']);
         }
         if ($rs1->f('user_email') == $new_email['value']) {
             $error[] = sprintf(T_('The email address %s is already in use by %s'), $new_email['value'], $rs1->f('user_id'));
         }
     }
     if (empty($error)) {
         $cur = $core->con->openCursor($core->prefix . 'user');
         $cur->user_fullname = $new_fullname['value'];
         $cur->user_email = $new_email['value'];
         if (!empty($new_password['value'])) {
             $cur->user_pwd = crypt::hmac('BP_MASTER_KEY', $new_password['value']);
         }
         $cur->modified = array(' NOW() ');
         $cur->update("WHERE user_id = '{$user_id}'");
         $user_perms = $core->getUserRolePermissions($user_id);
         if ($user_perms->{'role'} == "god") {
             $blog_settings->put('author_mail', $new_email['value'], "string");
             $blog_settings->put('author', $new_fullname['value'], "string");
         }
         $output = sprintf(T_("User %s successfully updated"), $new_id['value']);
     }
 } else {
     if (!$new_fullname['success']) {
         $error[] = $new_fullname['error'];
     }
     if (!$new_email['success']) {
Beispiel #12
0
 protected function importUsers()
 {
     $db = $this->db();
     $prefix = $this->vars['db_prefix'];
     $rs = $db->select('SELECT * FROM ' . $prefix . 'user');
     try {
         $this->con->begin();
         while ($rs->fetch()) {
             if (!$this->core->userExists($rs->user_id)) {
                 $cur = $this->con->openCursor($this->prefix . 'user');
                 $cur->user_id = $rs->user_id;
                 $cur->user_name = $rs->user_nom;
                 $cur->user_firstname = $rs->user_prenom;
                 $cur->user_displayname = $rs->user_pseudo;
                 $cur->user_pwd = crypt::createPassword();
                 $cur->user_email = $rs->user_email;
                 $cur->user_lang = $rs->user_lang;
                 $cur->user_tz = $this->core->blog->settings->system->blog_timezone;
                 $cur->user_post_status = $rs->user_post_pub ? 1 : -2;
                 $cur->user_options = new ArrayObject(array('edit_size' => (int) $rs->user_edit_size, 'post_format' => $rs->user_post_format));
                 $permissions = array();
                 switch ($rs->user_level) {
                     case '0':
                         $cur->user_status = 0;
                         break;
                     case '1':
                         # editor
                         $permissions['usage'] = true;
                         break;
                     case '5':
                         # advanced editor
                         $permissions['contentadmin'] = true;
                         $permissions['categories'] = true;
                         $permissions['media_admin'] = true;
                         break;
                     case '9':
                         # admin
                         $permissions['admin'] = true;
                         break;
                 }
                 $this->core->addUser($cur);
                 $this->core->setUserBlogPermissions($rs->user_id, $this->blog_id, $permissions);
             }
         }
         $this->con->commit();
         $db->close();
     } catch (Exception $e) {
         $this->con->rollback();
         $db->close();
         throw $e;
     }
 }
Beispiel #13
0
 /**
  * Client unique ID
  *
  * Returns a "almost" safe client unique ID.
  *
  * @param string	$key		HMAC key
  * @return string
  */
 public static function browserUID($key)
 {
     $uid = '';
     $uid .= isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
     $uid .= isset($_SERVER['HTTP_ACCEPT_ENCODING']) ? $_SERVER['HTTP_ACCEPT_ENCODING'] : '';
     $uid .= isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : '';
     $uid .= isset($_SERVER['HTTP_ACCEPT_CHARSET']) ? $_SERVER['HTTP_ACCEPT_CHARSET'] : '';
     return crypt::hmac($key, $uid);
 }
     if ($rs0->f('nb') > 0) {
         $flash['error'][] = T_("Two users have the same name, impossible to import. Please try again. Username : "******"user");
     $cur->user_id = $user_id;
     $cur->user_fullname = $nom_membre;
     $cur->user_email = $email_membre;
     $cur->user_status = $statut_membre;
     $cur->user_lang = $blog_settings->get('planet_lang');
     $cur->created = array('NOW()');
     $cur->modified = array('NOW()');
     if ($user_id == $author_id) {
         $cur->update("WHERE user_id == '" . $author_id . "'");
     } else {
         $cur->user_pwd = crypt::hmac($user_id, $email_membre);
         $cur->insert();
     }
     $rs3 = $core->con->select('SELECT MAX(site_id) ' . 'FROM ' . $core->prefix . 'site ');
     $next_site_id = (int) $rs3->f(0) + 1;
     $cur = $core->con->openCursor($core->prefix . 'site');
     $cur->site_id = $next_site_id;
     $cur->user_id = $user_id;
     $cur->site_name = '';
     $cur->site_url = $site_membre;
     $cur->site_status = 1;
     $cur->created = array(' NOW() ');
     $cur->modified = array(' NOW() ');
     $cur->insert();
 }
 break;
Beispiel #15
0
 private function set_cookie_crypt()
 {
     $crypt_type = $this->get_config()->cookie->crypt->type;
     if ($crypt_type) {
         http_cookie::set_crypt(crypt::get($crypt_type));
     }
 }
Beispiel #16
0
        try {
            $ret_code = dc_lang_install($dest);
        } catch (Exception $e) {
            @unlink($dest);
            throw $e;
        }
        @unlink($dest);
        http::redirect('langs.php?added=' . $ret_code);
    } catch (Exception $e) {
        $core->error->add($e->getMessage());
    }
}
# Upload a language pack
if ($is_writable && !empty($_POST['upload_pkg'])) {
    try {
        if (empty($_POST['your_pwd']) || !$core->auth->checkPassword(crypt::hmac(DC_MASTER_KEY, $_POST['your_pwd']))) {
            throw new Exception(__('Password verification failed'));
        }
        files::uploadStatus($_FILES['pkg_file']);
        $dest = DC_L10N_ROOT . '/' . $_FILES['pkg_file']['name'];
        if (!move_uploaded_file($_FILES['pkg_file']['tmp_name'], $dest)) {
            throw new Exception(__('Unable to move uploaded file.'));
        }
        try {
            $ret_code = dc_lang_install($dest);
        } catch (Exception $e) {
            @unlink($dest);
            throw $e;
        }
        @unlink($dest);
        http::redirect('langs.php?added=' . $ret_code);
Beispiel #17
0
 /**
  * Send an email
  *
  * @param array $options
  * @return array
  */
 public function send($options)
 {
     $result = ['success' => false, 'error' => [], 'unique_id' => null];
     // see if we need to validate
     if (empty($options['validated'])) {
         $temp = $this->validate($options);
         if (!$temp['success']) {
             return $temp;
         } else {
             if (!empty($temp['data']['requires_fetching'])) {
                 // we error if we require fetching from database
                 $result['error'][] = 'Fetching of email addresses is required!';
                 return $result;
             } else {
                 $options = $temp['data'];
             }
         }
     }
     // to, cc, bcc
     $recepients = [];
     foreach (['to', 'cc', 'bcc'] as $r) {
         $recepients[$r] = [];
         foreach ($options[$r] as $v) {
             // todo: add recepient name here
             $recepients[$r][] = $v['email'];
         }
         $recepients[$r] = implode(',', $recepients[$r]);
     }
     // crypt object
     $crypt = new crypt();
     // todo: use unique id for tracking
     $result['unique_id'] = $crypt->hash([$recepients, $options['subject'], microtime()]);
     // generating header
     if (isset($options['header'])) {
         $header = $options['header'];
     } else {
         $header = '';
     }
     if (isset($options['from']['name'])) {
         $header .= "From: {$options['from']['name']} <{$options['from']['email']}>\n";
         $header .= "Organization: {$options['from']['name']}\n";
     } else {
         $header .= "From: {$options['from']['email']}\n";
     }
     if (!empty($recepients['bcc'])) {
         $header .= "Bcc: " . $recepients['bcc'] . "\n";
     }
     if (!empty($recepients['cc'])) {
         $header .= "Cc: " . $recepients['cc'] . "\n";
     }
     $header .= "Reply-To: {$options['from']['email']}\n";
     $header .= "Errors-To: {$options['from']['email']}\n";
     $header .= "MIME-Version: 1.0\n";
     $header .= "X-Mailer: PHP/" . phpversion() . "\n";
     // generating body for no attachment and a single message
     if (empty($options['attachments']) && count($options['message']) == 1) {
         $part = reset($options['message']);
         $header .= "Content-Type: {$part['type']};\n charset=\"{$part['charset']}\"\n";
         $header .= "Content-Transfer-Encoding: {$part['encoding']}\n";
         $body = $part['data'];
     } else {
         // has attachments or multiple messages
         $body_text = "";
         $unique_hash = $crypt->hash(mt_rand());
         $body_boundary = "boundary." . $unique_hash;
         $body_header = "";
         $body_header .= "Content-Type: multipart/alternative; boundary=\"{$body_boundary}\"\n";
         $body_header .= "Content-Transfer-Encoding: 7bit\n";
         $body_header .= "Content-Disposition: inline\n";
         // going though messages
         foreach ($options['message'] as $part) {
             $body_text .= "--{$body_boundary}\n";
             $body_text .= "Content-Type: {$part['type']}; charset=\"{$part['charset']}\"\n";
             $body_text .= "Content-Transfer-Encoding: {$part['encoding']}\n\n";
             $body_text .= $this->encode_part($part) . "\n\n";
         }
         $body_text .= "\n--{$body_boundary}--\n";
         // if we have attachments
         $text_part = "\nThis is a multi-part message in MIME format.\n\n";
         if (!empty($options['attachments'])) {
             $attachment_boundary = "boundary." . $unique_hash . ".attachments";
             $header .= "Content-Type: multipart/mixed; boundary=\"{$attachment_boundary}\"";
             $text_part .= "--{$attachment_boundary}\n";
             $text_part .= "{$body_header}\n";
             $text_part .= $body_text;
             // going though them
             foreach ($options['attachments'] as $v) {
                 $text_part .= "--{$attachment_boundary}\n";
                 $text_part .= "Content-Type: {$v['type']}; name=\"{$v['name']}\"\n";
                 $text_part .= "Content-Transfer-Encoding: base64\n";
                 $text_part .= "Content-Disposition: attachment; filename=\"{$v['name']}\"\n\n";
                 $text_part .= $this->encode_part(['data' => $v['data'], 'encoding' => 'base64']);
             }
             $text_part .= "\n--{$attachment_boundary}--\n";
         } else {
             $header .= $body_header;
             $text_part .= $body_text;
         }
         $body = $text_part;
     }
     // trying to deliver
     if (mail($recepients['to'], $options['subject'], $body, $header)) {
         $result['success'] = true;
     } else {
         $result['error'][] = 'Could not deliver mail!';
     }
     return $result;
 }
Beispiel #18
0
 public static function checkUserCode($core, $code)
 {
     $code = pack('H*', $code);
     $user_id = trim(@pack('a32', substr($code, 0, 32)));
     $pwd = @unpack('H40hex', substr($code, 32, 40));
     if ($user_id === false || $pwd === false) {
         return false;
     }
     $pwd = $pwd['hex'];
     $strReq = 'SELECT user_id, user_pwd ' . 'FROM ' . $core->prefix . 'user ' . "WHERE user_id = '" . $core->con->escape($user_id) . "' ";
     $rs = $core->con->select($strReq);
     if ($rs->isEmpty()) {
         return false;
     }
     if (crypt::hmac(DC_MASTER_KEY, $rs->user_pwd) != $pwd) {
         return false;
     }
     return $rs->user_id;
 }
Beispiel #19
0
                 $default_tz = $_tz;
             }
         }
         unset($_tz);
     }
 }
 # Create schema
 $_s = new dbStruct($core->con, $core->prefix);
 require dirname(__FILE__) . '/../../inc/dbschema/db-schema.php';
 $si = new dbStruct($core->con, $core->prefix);
 $changes = $si->synchronize($_s);
 # Create user
 $cur = $core->con->openCursor($core->prefix . 'user');
 $cur->user_id = $u_login;
 $cur->user_super = 1;
 $cur->user_pwd = crypt::hmac(DC_MASTER_KEY, $u_pwd);
 $cur->user_name = (string) $u_name;
 $cur->user_firstname = (string) $u_firstname;
 $cur->user_email = (string) $u_email;
 $cur->user_lang = $dlang;
 $cur->user_tz = $default_tz;
 $cur->user_creadt = array('NOW()');
 $cur->user_upddt = array('NOW()');
 $cur->user_options = serialize($core->userDefaults());
 $cur->insert();
 $core->auth->checkUser($u_login);
 $admin_url = preg_replace('%install/index.php$%', '', $_SERVER['REQUEST_URI']);
 $root_url = preg_replace('%/admin/install/index.php$%', '', $_SERVER['REQUEST_URI']);
 # Create blog
 $cur = $core->con->openCursor($core->prefix . 'blog');
 $cur->blog_id = 'default';
Beispiel #20
0
     * @throws \RuntimeException raised on missing mcrypt
     * @throws \InvalidArgumentException raised on decrypting failed
     * @param string $cipher encrypted message
     * @return string decrypted message
     */
    public function decrypt($cipher)
    {
        // test for tag on cipher and pass back provided cipher as is if tag is missing
        if (substr($cipher, 0, 8) !== 'TXF!CIPH') {
            log::warning('actually not decrypting since cipher is not properly encrypted');
            return $cipher;
        }
        if (!is_callable('mcrypt_module_open')) {
            throw new \RuntimeException('missing mcrypt');
        }
        // actually decrypt provided cipher
        mcrypt_generic_init($this->cryptModule, $this->preparedKey(), $this->preparedIV());
        $decrypted = mdecrypt_generic($this->cryptModule, substr($cipher, 8));
        mcrypt_generic_deinit($this->cryptModule);
        // check integrity of decrypted message
        $cleartext = substr($decrypted, 20);
        $hash = substr($decrypted, 0, 20);
        if (sha1($cleartext, true) !== $hash) {
            log::error('decryption failed');
            throw new \InvalidArgumentException('decryption failed');
        }
        return $cleartext;
    }
}
crypt::init();
Beispiel #21
0
 /**
  * Restores variable space from current snapshot made to be storable in
  * session.
  */
 protected final function makeUsable()
 {
     if (trim($this->storable)) {
         if (data::autoType(config::get('session.encrypt', false), 'boolean')) {
             try {
                 $space = unserialize(crypt::create()->decrypt($this->storable));
             } catch (\InvalidArgumentException $e) {
                 log::warning('session lost due to failed decryption, might be okay if browser lost cookie in between');
                 $space = array();
             }
         } else {
             $space = unserialize($this->storable);
         }
         if (is_array($space)) {
             $this->usable = $space;
         }
         $this->storable = null;
     }
     if (!is_array($this->usable)) {
         $this->usable = array();
     }
 }
Beispiel #22
0
 protected function importUsers()
 {
     $db = $this->db();
     $prefix = $this->vars['db_prefix'];
     $rs = $db->select('SELECT * FROM ' . $prefix . 'users');
     try {
         $this->con->begin();
         while ($rs->fetch()) {
             $user_login = preg_replace('/[^A-Za-z0-9@._-]/', '-', $rs->user_login);
             $this->vars['user_ids'][$rs->ID] = $user_login;
             if (!$this->core->userExists($user_login)) {
                 $cur = $this->con->openCursor($this->prefix . 'user');
                 $cur->user_id = $user_login;
                 $cur->user_pwd = crypt::createPassword();
                 $cur->user_displayname = $rs->user_nicename;
                 $cur->user_email = $rs->user_email;
                 $cur->user_url = $rs->user_url;
                 $cur->user_creadt = $rs->user_registered;
                 $cur->user_lang = $this->core->blog->settings->lang;
                 $cur->user_tz = $this->core->blog->settings->blog_timezone;
                 $permissions = array();
                 $rs_meta = $db->select('SELECT * FROM ' . $prefix . 'usermeta WHERE user_id = ' . $rs->ID);
                 while ($rs_meta->fetch()) {
                     switch ($rs_meta->meta_key) {
                         case 'first_name':
                             $cur->user_firstname = $this->cleanStr($rs_meta->meta_value);
                             break;
                         case 'last_name':
                             $cur->user_name = $this->cleanStr($rs_meta->meta_value);
                             break;
                         case 'description':
                             $cur->user_desc = $this->cleanStr($rs_meta->meta_value);
                             break;
                         case 'rich_editing':
                             $cur->user_options = new ArrayObject(array('enable_wysiwyg' => $rs_meta->meta_value == 'true' ? true : false));
                             break;
                         case 'wp_user_level':
                             switch ($rs_meta->meta_value) {
                                 case '0':
                                     # Subscriber
                                     $cur->user_status = 0;
                                     break;
                                 case '1':
                                     # Contributor
                                     $permissions['usage'] = true;
                                     $permissions['publish'] = true;
                                     $permissions['delete'] = true;
                                     break;
                                 case '2':
                                     # Author
                                 # Author
                                 case '3':
                                 case '4':
                                     $permissions['contentadmin'] = true;
                                     $permissions['media'] = true;
                                     break;
                                 case '5':
                                     # Editor
                                 # Editor
                                 case '6':
                                 case '7':
                                     $permissions['contentadmin'] = true;
                                     $permissions['categories'] = true;
                                     $permissions['media_admin'] = true;
                                     $permissions['pages'] = true;
                                     $permissions['blogroll'] = true;
                                     break;
                                 case '8':
                                     # Administrator
                                 # Administrator
                                 case '9':
                                 case '10':
                                     $permissions['admin'] = true;
                                     break;
                             }
                             break;
                     }
                 }
                 $this->core->addUser($cur);
                 $this->core->setUserBlogPermissions($cur->user_id, $this->blog_id, $permissions);
             }
         }
         $this->con->commit();
         $db->close();
     } catch (Exception $e) {
         $this->con->rollback();
         $db->close();
         throw $e;
     }
 }
 /**
  * Pre render processing
  */
 public static function pre_render()
 {
     $crypt_class = new crypt();
     $token = urldecode($crypt_class->token_create('general'));
     layout::js_data(['token' => $token, 'controller_full' => application::get(['mvc', 'full']), 'flag' => ['global' => ['format' => format::$options]], 'object_data_domains' => ['data' => object_data_domains::get_static()]]);
 }
Beispiel #24
0
$blog_id = '';
if (!empty($_POST['blog_id'])) {
    try {
        $rs = $core->getBlog($_POST['blog_id']);
    } catch (Exception $e) {
        $core->error->add($e->getMessage());
    }
    if ($rs->isEmpty()) {
        $core->error->add(__('No such blog ID'));
    } else {
        $blog_id = $rs->blog_id;
    }
}
# Delete the blog
if (!$core->error->flag() && $blog_id && !empty($_POST['del'])) {
    if (!$core->auth->checkPassword(crypt::hmac(DC_MASTER_KEY, $_POST['pwd']))) {
        $core->error->add(__('Password verification failed'));
    } else {
        try {
            $core->delBlog($blog_id);
            http::redirect('blogs.php?del=1');
        } catch (Exception $e) {
            $core->error->add($e->getMessage());
        }
    }
}
dcPage::open('Delete a blog');
if (!$core->error->flag()) {
    echo '<h2>' . __('Delete a blog') . '</h2>' . '<p class="message">' . __('Warning') . '</p>' . '<p>' . sprintf(__('You are about to delete the blog %s. Every entry, comment and category will be deleted.'), '<strong>' . $blog_id . '</strong>') . '</p>' . '<p>' . __('Please give your password to confirm the blog deletion.') . '</p>';
    echo '<form action="blog_del.php" method="post">' . '<div>' . $core->formNonce() . '</div>' . '<p><label>' . __('Your password:'******' ' . form::password('pwd', 20, 255) . '</label></p>' . '<p><input type="submit" name="del" value="' . __('Delete this blog') . '" />' . form::hidden('blog_id', $blog_id) . '</p>' . '</form>';
}
 private function getUserCursor(&$cur)
 {
     if ($cur->isField('user_id') && !preg_match('/^[A-Za-z0-9@._-]{2,}$/', $cur->user_id)) {
         throw new Exception(T_('User ID must contain at least 2 characters using letters, numbers or symbols.'));
     }
     if ($cur->user_url !== null && $cur->user_url != '') {
         if (!preg_match('|^http(s?)://|', $cur->user_url)) {
             $cur->user_url = 'http://' . $cur->user_url;
         }
     }
     if ($cur->isField('user_pwd')) {
         if (strlen($cur->user_pwd) < 6) {
             throw new Exception(T_('Password must contain at least 6 characters.'));
         }
         $cur->user_pwd = crypt::hmac('BP_MASTER_KEY', $cur->user_pwd);
     }
     if ($cur->user_lang !== null && !preg_match('/^[a-z]{2}(-[a-z]{2})?$/', $cur->user_lang)) {
         throw new Exception(T_('Invalid user language code'));
     }
     if ($cur->user_upddt === null) {
         $cur->user_upddt = array('NOW()');
     }
     if ($cur->user_options !== null) {
         $cur->user_options = serialize((array) $cur->user_options);
     }
 }
Beispiel #26
0
 public function try_login($user, $password, $permanent)
 {
     if ($password == '') {
         return LOGIN_EMPTY_USERPASSWORD;
     }
     $encryptedPassword = crypt::encryptPassword($password);
     return $this->try_login_encrypted($user, $encryptedPassword, $permanent);
 }
 public function process($do)
 {
     if ($do == 'single' || $do == 'full') {
         $this->status = $do;
         return;
     }
     $to_unlink = false;
     # Single blog import
     $files = $this->getPublicFiles();
     $single_upl = null;
     if (!empty($_POST['public_single_file']) && in_array($_POST['public_single_file'], $files)) {
         $single_upl = false;
     } elseif (!empty($_FILES['up_single_file'])) {
         $single_upl = true;
     }
     if ($single_upl !== null) {
         if ($single_upl) {
             files::uploadStatus($_FILES['up_single_file']);
             $file = DC_TPL_CACHE . '/' . md5(uniqid());
             if (!move_uploaded_file($_FILES['up_single_file']['tmp_name'], $file)) {
                 throw new Exception(__('Unable to move uploaded file.'));
             }
             $to_unlink = true;
         } else {
             $file = $_POST['public_single_file'];
         }
         try {
             $bk = new dcImport($this->core, $file);
             $bk->importSingle();
         } catch (Exception $e) {
             if ($to_unlink) {
                 @unlink($file);
             }
             throw $e;
         }
         if ($to_unlink) {
             @unlink($file);
         }
         http::redirect($this->getURL() . '&do=single');
     }
     # Full import
     $full_upl = null;
     if (!empty($_POST['public_full_file']) && in_array($_POST['public_full_file'], $files)) {
         $full_upl = false;
     } elseif (!empty($_FILES['up_full_file'])) {
         $full_upl = true;
     }
     if ($full_upl !== null && $this->core->auth->isSuperAdmin()) {
         if (empty($_POST['your_pwd']) || !$this->core->auth->checkPassword(crypt::hmac(DC_MASTER_KEY, $_POST['your_pwd']))) {
             throw new Exception(__('Password verification failed'));
         }
         if ($full_upl) {
             files::uploadStatus($_FILES['up_full_file']);
             $file = DC_TPL_CACHE . '/' . md5(uniqid());
             if (!move_uploaded_file($_FILES['up_full_file']['tmp_name'], $file)) {
                 throw new Exception(__('Unable to move uploaded file.'));
             }
             $to_unlink = true;
         } else {
             $file = $_POST['public_full_file'];
         }
         try {
             $bk = new dcImport($this->core, $file);
             $bk->importFull();
         } catch (Exception $e) {
             if ($to_unlink) {
                 @unlink($file);
             }
             throw $e;
         }
         if ($to_unlink) {
             @unlink($file);
         }
         http::redirect($this->getURL() . '&do=full');
     }
     header('content-type:text/plain');
     var_dump($_POST);
     exit;
     $this->status = true;
 }
Beispiel #28
0
 public static function encryptPassword($password)
 {
     // Calls the password encryption chained
     $pwmd5 = crypt::firstStagePasswordEncryption($password);
     return crypt::secondStagePasswordEncryption($pwmd5);
 }
Beispiel #29
0
 /**
  * Sets up user folders and keys for serverside encryption
  *
  * @param string $passphrase to encrypt server-stored private key with
  * @return bool
  */
 public function setupServerSide($passphrase = null)
 {
     // Set directories to check / create
     $setUpDirs = array($this->userDir, $this->publicKeyDir, $this->encryptionDir, $this->keysPath);
     // Check / create all necessary dirs
     foreach ($setUpDirs as $dirPath) {
         if (!$this->view->file_exists($dirPath)) {
             $this->view->mkdir($dirPath);
         }
     }
     // Create user keypair
     // we should never override a keyfile
     if (!$this->view->file_exists($this->publicKeyPath) && !$this->view->file_exists($this->privateKeyPath)) {
         // Generate keypair
         $keypair = Crypt::createKeypair();
         if ($keypair) {
             \OC_FileProxy::$enabled = false;
             // Encrypt private key with user pwd as passphrase
             $encryptedPrivateKey = Crypt::symmetricEncryptFileContent($keypair['privateKey'], $passphrase, Helper::getCipher());
             // Save key-pair
             if ($encryptedPrivateKey) {
                 $header = crypt::generateHeader();
                 $this->view->file_put_contents($this->privateKeyPath, $header . $encryptedPrivateKey);
                 $this->view->file_put_contents($this->publicKeyPath, $keypair['publicKey']);
             }
             \OC_FileProxy::$enabled = true;
         }
     } else {
         // check if public-key exists but private-key is missing
         if ($this->view->file_exists($this->publicKeyPath) && !$this->view->file_exists($this->privateKeyPath)) {
             \OCP\Util::writeLog('Encryption library', 'public key exists but private key is missing for "' . $this->keyId . '"', \OCP\Util::FATAL);
             return false;
         } else {
             if (!$this->view->file_exists($this->publicKeyPath) && $this->view->file_exists($this->privateKeyPath)) {
                 \OCP\Util::writeLog('Encryption library', 'private key exists but public key is missing for "' . $this->keyId . '"', \OCP\Util::FATAL);
                 return false;
             }
         }
     }
     return true;
 }
Beispiel #30
0
 function setPassword($password)
 {
     if (!mb_ereg_match(REGEX_PASSWORD, $password)) {
         return false;
     }
     if (cracklib_checkPW($password, array('open', 'caching', 'cache', $this->getUsername(), $this->getFirstName(), $this->getLastName())) == false) {
         return false;
     }
     $encryptedPassword = crypt::encryptPassword($password);
     return $this->reUser->setValue('password', $encryptedPassword);
 }