예제 #1
0
 $dataReceived = prepareExchangedData($_POST['data'], "decode");
 // Prepare variables
 $login = htmlspecialchars_decode($dataReceived['login']);
 $name = htmlspecialchars_decode($dataReceived['name']);
 $lastname = htmlspecialchars_decode($dataReceived['lastname']);
 $pw = htmlspecialchars_decode($dataReceived['pw']);
 // Empty user
 if (mysqli_escape_string($link, htmlspecialchars_decode($login)) == "") {
     echo '[ { "error" : "' . addslashes($LANG['error_empty_data']) . '" } ]';
     break;
 }
 // Check if user already exists
 $data = DB::query("SELECT id, fonction_id, groupes_interdits, groupes_visibles FROM " . prefix_table("users") . "\n                WHERE login LIKE %ss", mysqli_escape_string($link, stripslashes($login)));
 if (DB::count() == 0) {
     // Add user in DB
     DB::insert(prefix_table("users"), array('login' => $login, 'name' => $name, 'lastname' => $lastname, 'pw' => bCrypt(stringUtf8Decode($pw), COST), 'email' => $dataReceived['email'], 'admin' => $dataReceived['admin'] == "true" ? '1' : '0', 'gestionnaire' => $dataReceived['manager'] == "true" ? '1' : '0', 'read_only' => $dataReceived['read_only'] == "true" ? '1' : '0', 'personal_folder' => $dataReceived['personal_folder'] == "true" ? '1' : '0', 'user_language' => $_SESSION['settings']['default_language'], 'fonction_id' => $dataReceived['manager'] == "true" ? $_SESSION['fonction_id'] : '0', 'groupes_interdits' => $dataReceived['manager'] == "true" && isset($data['groupes_interdits']) && !is_null($data['groupes_interdits']) ? $data['groupes_interdits'] : '0', 'groupes_visibles' => $dataReceived['manager'] == "true" && isset($data['groupes_visibles']) && !is_null($data['groupes_visibles']) ? $data['groupes_visibles'] : '0', 'isAdministratedByRole' => $dataReceived['isAdministratedByRole']));
     $new_user_id = DB::insertId();
     // Create personnal folder
     if ($dataReceived['personal_folder'] == "true") {
         DB::insert(prefix_table("nested_tree"), array('parent_id' => '0', 'title' => $new_user_id, 'bloquer_creation' => '0', 'bloquer_modification' => '0', 'personal_folder' => '1'));
         $tree->rebuild();
     }
     // Create folder and role for domain
     if ($dataReceived['new_folder_role_domain'] == "true") {
         // create folder
         DB::insert(prefix_table("nested_tree"), array('parent_id' => 0, 'title' => mysqli_escape_string($link, stripslashes($dataReceived['domain'])), 'personal_folder' => 0, 'renewal_period' => 0, 'bloquer_creation' => '0', 'bloquer_modification' => '0'));
         $new_folder_id = DB::insertId();
         // Add complexity
         DB::insert(prefix_table("misc"), array('type' => 'complex', 'intitule' => $new_folder_id, 'valeur' => 50));
         // Create role
         DB::insert(prefix_table("roles_title"), array('title' => mysqli_escape_string($link, stripslashes($dataReceived['domain']))));
예제 #2
0
function identifyUser($sentData)
{
    global $debugLdap, $debugDuo, $k;
    include $_SESSION['settings']['cpassman_dir'] . '/includes/settings.php';
    header("Content-type: text/html; charset=utf-8");
    error_reporting(E_ERROR);
    require_once $_SESSION['settings']['cpassman_dir'] . '/sources/main.functions.php';
    require_once $_SESSION['settings']['cpassman_dir'] . '/sources/SplClassLoader.php';
    if ($debugDuo == 1) {
        $dbgDuo = fopen($_SESSION['settings']['path_to_files_folder'] . "/duo.debug.txt", "a");
    }
    /*
    if (empty($sentData) && isset($_COOKIE['TeamPassC'])) {
    	$sentData = prepareExchangedData($_COOKIE['TeamPassC'], "encode");
    	setcookie('TeamPassC', "", time()-3600);
    }
    */
    if ($debugDuo == 1) {
        fputs($dbgDuo, "Content of data sent '" . $sentData . "'\n");
    }
    // connect to the server
    require_once $_SESSION['settings']['cpassman_dir'] . '/includes/libraries/Database/Meekrodb/db.class.php';
    DB::$host = $server;
    DB::$user = $user;
    DB::$password = $pass;
    DB::$dbName = $database;
    DB::$port = $port;
    DB::$encoding = $encoding;
    DB::$error_handler = 'db_error_handler';
    $link = mysqli_connect($server, $user, $pass, $database, $port);
    $link->set_charset($encoding);
    //Load AES
    $aes = new SplClassLoader('Encryption\\Crypt', '../includes/libraries');
    $aes->register();
    // load passwordLib library
    $pwdlib = new SplClassLoader('PasswordLib', '../includes/libraries');
    $pwdlib->register();
    $pwdlib = new PasswordLib\PasswordLib();
    // User's language loading
    $k['langage'] = @$_SESSION['user_language'];
    require_once $_SESSION['settings']['cpassman_dir'] . '/includes/language/' . $_SESSION['user_language'] . '.php';
    // decrypt and retreive data in JSON format
    $dataReceived = prepareExchangedData($sentData, "decode");
    // Prepare variables
    $passwordClear = htmlspecialchars_decode($dataReceived['pw']);
    $passwordOldEncryption = encryptOld(htmlspecialchars_decode($dataReceived['pw']));
    $username = htmlspecialchars_decode($dataReceived['login']);
    $logError = "";
    if ($debugDuo == 1) {
        fputs($dbgDuo, "Starting authentication of '" . $username . "'\n");
    }
    // GET SALT KEY LENGTH
    if (strlen(SALT) > 32) {
        $_SESSION['error']['salt'] = true;
    }
    $_SESSION['user_language'] = $k['langage'];
    $ldapConnection = false;
    /* LDAP connection */
    if ($debugLdap == 1) {
        // create temp file
        $dbgLdap = fopen($_SESSION['settings']['path_to_files_folder'] . "/ldap.debug.txt", "w");
        fputs($dbgLdap, "Get all LDAP params : \n" . 'mode : ' . $_SESSION['settings']['ldap_mode'] . "\n" . 'type : ' . $_SESSION['settings']['ldap_type'] . "\n" . 'base_dn : ' . $_SESSION['settings']['ldap_domain_dn'] . "\n" . 'search_base : ' . $_SESSION['settings']['ldap_search_base'] . "\n" . 'bind_dn : ' . $_SESSION['settings']['ldap_bind_dn'] . "\n" . 'bind_passwd : ' . $_SESSION['settings']['ldap_bind_passwd'] . "\n" . 'user_attribute : ' . $_SESSION['settings']['ldap_user_attribute'] . "\n" . 'account_suffix : ' . $_SESSION['settings']['ldap_suffix'] . "\n" . 'domain_controllers : ' . $_SESSION['settings']['ldap_domain_controler'] . "\n" . 'use_ssl : ' . $_SESSION['settings']['ldap_ssl'] . "\n" . 'use_tls : ' . $_SESSION['settings']['ldap_tls'] . "\n*********\n\n");
    }
    if ($debugDuo == 1) {
        fputs($dbgDuo, "LDAP status: " . $_SESSION['settings']['ldap_mode'] . "\n");
    }
    if (isset($_SESSION['settings']['ldap_mode']) && $_SESSION['settings']['ldap_mode'] == 1 && $username != "admin") {
        //Multiple Domain Names
        if (strpos(html_entity_decode($username), '\\') == true) {
            $ldap_suffix = "@" . substr(html_entity_decode($username), 0, strpos(html_entity_decode($username), '\\'));
            $username = substr(html_entity_decode($username), strpos(html_entity_decode($username), '\\') + 1);
        }
        if ($_SESSION['settings']['ldap_type'] == 'posix-search') {
            $ldapconn = ldap_connect($_SESSION['settings']['ldap_domain_controler']);
            if ($debugLdap == 1) {
                fputs($dbgLdap, "LDAP connection : " . ($ldapconn ? "Connected" : "Failed") . "\n");
            }
            ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
            if ($ldapconn) {
                $ldapbind = ldap_bind($ldapconn, $_SESSION['settings']['ldap_bind_dn'], $_SESSION['settings']['ldap_bind_passwd']);
                if ($debugLdap == 1) {
                    fputs($dbgLdap, "LDAP bind : " . ($ldapbind ? "Bound" : "Failed") . "\n");
                }
                if ($ldapbind) {
                    $filter = "(&(" . $_SESSION['settings']['ldap_user_attribute'] . "={$username})(objectClass=posixAccount))";
                    $result = ldap_search($ldapconn, $_SESSION['settings']['ldap_search_base'], $filter, array('dn'));
                    if ($debugLdap == 1) {
                        fputs($dbgLdap, 'Search filter : ' . $filter . "\n" . 'Results : ' . print_r(ldap_get_entries($ldapconn, $result), true) . "\n");
                    }
                    if (ldap_count_entries($ldapconn, $result)) {
                        // try auth
                        $result = ldap_get_entries($ldapconn, $result);
                        $user_dn = $result[0]['dn'];
                        $ldapbind = ldap_bind($ldapconn, $user_dn, $passwordClear);
                        if ($ldapbind) {
                            $ldapConnection = true;
                        } else {
                            $ldapConnection = false;
                        }
                    }
                } else {
                    $ldapConnection = false;
                }
            } else {
                $ldapConnection = false;
            }
        } else {
            if ($debugLdap == 1) {
                fputs($dbgLdap, "Get all ldap params : \n" . 'base_dn : ' . $_SESSION['settings']['ldap_domain_dn'] . "\n" . 'account_suffix : ' . $_SESSION['settings']['ldap_suffix'] . "\n" . 'domain_controllers : ' . $_SESSION['settings']['ldap_domain_controler'] . "\n" . 'use_ssl : ' . $_SESSION['settings']['ldap_ssl'] . "\n" . 'use_tls : ' . $_SESSION['settings']['ldap_tls'] . "\n*********\n\n");
            }
            $adldap = new SplClassLoader('LDAP\\adLDAP', '../includes/libraries');
            $adldap->register();
            // Posix style LDAP handles user searches a bit differently
            if ($_SESSION['settings']['ldap_type'] == 'posix') {
                $ldap_suffix = ',' . $_SESSION['settings']['ldap_suffix'] . ',' . $_SESSION['settings']['ldap_domain_dn'];
            } elseif ($_SESSION['settings']['ldap_type'] == 'windows' and $ldap_suffix == '') {
                //Multiple Domain Names
                $ldap_suffix = $_SESSION['settings']['ldap_suffix'];
            }
            $adldap = new LDAP\adLDAP\adLDAP(array('base_dn' => $_SESSION['settings']['ldap_domain_dn'], 'account_suffix' => $ldap_suffix, 'domain_controllers' => explode(",", $_SESSION['settings']['ldap_domain_controler']), 'use_ssl' => $_SESSION['settings']['ldap_ssl'], 'use_tls' => $_SESSION['settings']['ldap_tls']));
            if ($debugLdap == 1) {
                fputs($dbgLdap, "Create new adldap object : " . $adldap->get_last_error() . "\n\n\n");
                //Debug
            }
            // openLDAP expects an attribute=value pair
            if ($_SESSION['settings']['ldap_type'] == 'posix') {
                $auth_username = $_SESSION['settings']['ldap_user_attribute'] . '=' . $username;
            } else {
                $auth_username = $username;
            }
            // authenticate the user
            if ($adldap->authenticate($auth_username, html_entity_decode($passwordClear))) {
                $ldapConnection = true;
                //update user's password
                $data['pw'] = $pwdlib->createPasswordHash($passwordClear);
                DB::update(prefix_table('users'), array('pw' => $data['pw']), "login=%s", $username);
            } else {
                $ldapConnection = false;
            }
            if ($debugLdap == 1) {
                fputs($dbgLdap, "After authenticate : " . $adldap->get_last_error() . "\n\n\n" . "ldap status : " . $ldapConnection . "\n\n\n");
                //Debug
            }
        }
    } else {
        if (isset($_SESSION['settings']['ldap_mode']) && $_SESSION['settings']['ldap_mode'] == 2) {
            // nothing
        }
    }
    // Check if user exists
    $data = DB::queryFirstRow("SELECT * FROM " . prefix_table("users") . " WHERE login=%s_login", array('login' => $username));
    $counter = DB::count();
    if ($debugDuo == 1) {
        fputs($dbgDuo, "USer exists: " . $counter . "\n");
    }
    // Check PSK
    if (isset($_SESSION['settings']['psk_authentication']) && $_SESSION['settings']['psk_authentication'] == 1 && $data['admin'] != 1) {
        $psk = htmlspecialchars_decode($dataReceived['psk']);
        $pskConfirm = htmlspecialchars_decode($dataReceived['psk_confirm']);
        if (empty($psk)) {
            echo '[{"value" : "psk_required"}]';
            exit;
        } elseif (empty($data['psk'])) {
            if (empty($pskConfirm)) {
                echo '[{"value" : "bad_psk_confirmation"}]';
                exit;
            } else {
                $_SESSION['my_sk'] = $psk;
            }
        } elseif ($pwdlib->verifyPasswordHash($psk, $data['psk']) === true) {
            echo '[{"value" : "bad_psk"}]';
            exit;
        }
    }
    $proceedIdentification = false;
    if ($counter > 0) {
        $proceedIdentification = true;
    } elseif ($counter == 0 && $ldapConnection == true && isset($_SESSION['settings']['ldap_elusers']) && $_SESSION['settings']['ldap_elusers'] == 0) {
        // If LDAP enabled, create user in CPM if doesn't exist
        $data['pw'] = $pwdlib->createPasswordHash($passwordClear);
        // create passwordhash
        DB::insert(prefix_table('users'), array('login' => $username, 'pw' => $data['pw'], 'email' => "", 'admin' => '0', 'gestionnaire' => '0', 'personal_folder' => $_SESSION['settings']['enable_pf_feature'] == "1" ? '1' : '0', 'fonction_id' => '0', 'groupes_interdits' => '0', 'groupes_visibles' => '0', 'last_pw_change' => time(), 'user_language' => $_SESSION['settings']['default_language']));
        $newUserId = DB::insertId();
        // Create personnal folder
        if ($_SESSION['settings']['enable_pf_feature'] == "1") {
            DB::insert(prefix_table("nested_tree"), array('parent_id' => '0', 'title' => $newUserId, 'bloquer_creation' => '0', 'bloquer_modification' => '0', 'personal_folder' => '1'));
        }
        // Get info for user
        //$sql = "SELECT * FROM ".prefix_table("users")." WHERE login = '******'";
        //$row = $db->query($sql);
        $proceedIdentification = true;
    }
    // Check if user exists (and has been created in case of new LDAP user)
    $data = DB::queryFirstRow("SELECT * FROM " . prefix_table("users") . " WHERE login=%s_login", array('login' => $username));
    $counter = DB::count();
    if ($counter == 0) {
        echo '[{"value" : "user_not_exists", "text":""}]';
        exit;
    }
    if ($debugDuo == 1) {
        fputs($dbgDuo, "USer exists (confirm): " . $counter . "\n");
    }
    // check GA code
    if (isset($_SESSION['settings']['2factors_authentication']) && $_SESSION['settings']['2factors_authentication'] == 1 && $username != "admin") {
        if (isset($dataReceived['GACode']) && !empty($dataReceived['GACode'])) {
            include_once $_SESSION['settings']['cpassman_dir'] . "/includes/libraries/Authentication/GoogleAuthenticator/FixedBitNotation.php";
            include_once $_SESSION['settings']['cpassman_dir'] . "/includes/libraries/Authentication/GoogleAuthenticator/GoogleAuthenticator.php";
            $g = new Authentication\GoogleAuthenticator\GoogleAuthenticator();
            if ($g->checkCode($data['ga'], $dataReceived['GACode'])) {
                $proceedIdentification = true;
            } else {
                $proceedIdentification = false;
                $logError = "ga_code_wrong";
            }
        } else {
            $proceedIdentification = false;
            $logError = "ga_code_wrong";
        }
    }
    if ($debugDuo == 1) {
        fputs($dbgDuo, "Proceed with Ident: " . $proceedIdentification . "\n");
    }
    if ($proceedIdentification === true) {
        // User exists in the DB
        //$data = $db->fetchArray($row);
        //v2.1.17 -> change encryption for users password
        if ($passwordOldEncryption == $data['pw'] && !empty($data['pw'])) {
            //update user's password
            $data['pw'] = bCrypt($passwordClear, COST);
            DB::update(prefix_table('users'), array('pw' => $data['pw']), "id=%i", $data['id']);
        }
        if (crypt($passwordClear, $data['pw']) == $data['pw'] && !empty($data['pw'])) {
            //update user's password
            $data['pw'] = $pwdlib->createPasswordHash($passwordClear);
            DB::update(prefix_table('users'), array('pw' => $data['pw']), "id=%i", $data['id']);
        }
        // check the given password
        if ($pwdlib->verifyPasswordHash($passwordClear, $data['pw']) === true) {
            $userPasswordVerified = true;
        } else {
            $userPasswordVerified = false;
        }
        if ($debugDuo == 1) {
            fputs($dbgDuo, "User's password verified: " . $userPasswordVerified . "\n");
        }
        // Can connect if
        // 1- no LDAP mode + user enabled + pw ok
        // 2- LDAP mode + user enabled + ldap connection ok + user is not admin
        // 3-  LDAP mode + user enabled + pw ok + usre is admin
        // This in order to allow admin by default to connect even if LDAP is activated
        if (isset($_SESSION['settings']['ldap_mode']) && $_SESSION['settings']['ldap_mode'] == 0 && $userPasswordVerified == true && $data['disabled'] == 0 || isset($_SESSION['settings']['ldap_mode']) && $_SESSION['settings']['ldap_mode'] == 1 && $ldapConnection == true && $data['disabled'] == 0 && $username != "admin" || isset($_SESSION['settings']['ldap_mode']) && $_SESSION['settings']['ldap_mode'] == 2 && $ldapConnection == true && $data['disabled'] == 0 && $username != "admin" || isset($_SESSION['settings']['ldap_mode']) && $_SESSION['settings']['ldap_mode'] == 1 && $username == "admin" && $userPasswordVerified == true && $data['disabled'] == 0) {
            $_SESSION['autoriser'] = true;
            // Generate a ramdom ID
            $key = $pwdlib->getRandomToken(50);
            if ($debugDuo == 1) {
                fputs($dbgDuo, "User's token: " . $key . "\n");
            }
            // Log into DB the user's connection
            if (isset($_SESSION['settings']['log_connections']) && $_SESSION['settings']['log_connections'] == 1) {
                logEvents('user_connection', 'connection', $data['id']);
            }
            // Save account in SESSION
            $_SESSION['login'] = stripslashes($username);
            $_SESSION['name'] = stripslashes($data['name']);
            $_SESSION['lastname'] = stripslashes($data['lastname']);
            $_SESSION['user_id'] = $data['id'];
            $_SESSION['user_admin'] = $data['admin'];
            $_SESSION['user_manager'] = $data['gestionnaire'];
            $_SESSION['user_read_only'] = $data['read_only'];
            $_SESSION['last_pw_change'] = $data['last_pw_change'];
            $_SESSION['last_pw'] = $data['last_pw'];
            $_SESSION['can_create_root_folder'] = $data['can_create_root_folder'];
            $_SESSION['key'] = $key;
            $_SESSION['personal_folder'] = $data['personal_folder'];
            $_SESSION['user_language'] = $data['user_language'];
            $_SESSION['user_email'] = $data['email'];
            $_SESSION['user_ga'] = $data['ga'];
            $_SESSION['user_avatar'] = $data['avatar'];
            $_SESSION['user_avatar_thumb'] = $data['avatar_thumb'];
            $_SESSION['user_upgrade_needed'] = $data['upgrade_needed'];
            // manage session expiration
            $serverTime = time();
            if ($dataReceived['TimezoneOffset'] > 0) {
                $userTime = $serverTime + $dataReceived['TimezoneOffset'];
            } else {
                $userTime = $serverTime;
            }
            $_SESSION['fin_session'] = $userTime + $dataReceived['duree_session'] * 60;
            /* If this option is set user password MD5 is used as personal SALTKey */
            if (isset($_SESSION['settings']['use_md5_password_as_salt']) && $_SESSION['settings']['use_md5_password_as_salt'] == 1) {
                $_SESSION['my_sk'] = md5($passwordClear);
                setcookie("TeamPass_PFSK_" . md5($_SESSION['user_id']), encrypt($_SESSION['my_sk'], ""), time() + 60 * 60 * 24 * $_SESSION['settings']['personal_saltkey_cookie_duration'], '/');
            }
            @syslog(LOG_WARNING, "User logged in - " . $_SESSION['user_id'] . " - " . date("Y/m/d H:i:s") . " {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})");
            if (empty($data['last_connexion'])) {
                $_SESSION['derniere_connexion'] = time();
            } else {
                $_SESSION['derniere_connexion'] = $data['last_connexion'];
            }
            if (!empty($data['latest_items'])) {
                $_SESSION['latest_items'] = explode(';', $data['latest_items']);
            } else {
                $_SESSION['latest_items'] = array();
            }
            if (!empty($data['favourites'])) {
                $_SESSION['favourites'] = explode(';', $data['favourites']);
            } else {
                $_SESSION['favourites'] = array();
            }
            if (!empty($data['groupes_visibles'])) {
                $_SESSION['groupes_visibles'] = @implode(';', $data['groupes_visibles']);
            } else {
                $_SESSION['groupes_visibles'] = array();
            }
            if (!empty($data['groupes_interdits'])) {
                $_SESSION['groupes_interdits'] = @implode(';', $data['groupes_interdits']);
            } else {
                $_SESSION['groupes_interdits'] = array();
            }
            // User's roles
            $_SESSION['fonction_id'] = $data['fonction_id'];
            $_SESSION['user_roles'] = explode(";", $data['fonction_id']);
            // build array of roles
            $_SESSION['user_pw_complexity'] = 0;
            $_SESSION['arr_roles'] = array();
            foreach (array_filter(explode(';', $_SESSION['fonction_id'])) as $role) {
                $resRoles = DB::queryFirstRow("SELECT title, complexity FROM " . prefix_table("roles_title") . " WHERE id=%i", $role);
                $_SESSION['arr_roles'][$role] = array('id' => $role, 'title' => $resRoles['title']);
                // get highest complexity
                if ($_SESSION['user_pw_complexity'] < $resRoles['complexity']) {
                    $_SESSION['user_pw_complexity'] = $resRoles['complexity'];
                }
            }
            // build complete array of roles
            $_SESSION['arr_roles_full'] = array();
            $rows = DB::query("SELECT id, title FROM " . prefix_table("roles_title") . " ORDER BY title ASC");
            foreach ($rows as $record) {
                $_SESSION['arr_roles_full'][$record['id']] = array('id' => $record['id'], 'title' => $record['title']);
            }
            // Set some settings
            $_SESSION['user']['find_cookie'] = false;
            $_SESSION['settings']['update_needed'] = "";
            // Update table
            DB::update(prefix_table('users'), array('key_tempo' => $_SESSION['key'], 'last_connexion' => time(), 'timestamp' => time(), 'disabled' => 0, 'no_bad_attempts' => 0, 'session_end' => $_SESSION['fin_session'], 'psk' => $pwdlib->createPasswordHash(htmlspecialchars_decode($psk))), "id=%i", $data['id']);
            if ($debugDuo == 1) {
                fputs($dbgDuo, "Preparing to identify the user rights\n");
            }
            // Get user's rights
            identifyUserRights($data['groupes_visibles'], $_SESSION['groupes_interdits'], $data['admin'], $data['fonction_id'], false);
            // Get some more elements
            $_SESSION['screenHeight'] = $dataReceived['screenHeight'];
            // Get last seen items
            $_SESSION['latest_items_tab'][] = "";
            foreach ($_SESSION['latest_items'] as $item) {
                if (!empty($item)) {
                    $data = DB::queryFirstRow("SELECT id,label,id_tree FROM " . prefix_table("items") . " WHERE id=%i", $item);
                    $_SESSION['latest_items_tab'][$item] = array('id' => $item, 'label' => $data['label'], 'url' => 'index.php?page=items&amp;group=' . $data['id_tree'] . '&amp;id=' . $item);
                }
            }
            // send back the random key
            $return = $dataReceived['randomstring'];
            // Send email
            if (isset($_SESSION['settings']['enable_send_email_on_user_login']) && $_SESSION['settings']['enable_send_email_on_user_login'] == 1 && $_SESSION['user_admin'] != 1) {
                // get all Admin users
                $receivers = "";
                $rows = DB::query("SELECT email FROM " . prefix_table("users") . " WHERE admin = %i", 1);
                foreach ($rows as $record) {
                    if (empty($receivers)) {
                        $receivers = $record['email'];
                    } else {
                        $receivers = "," . $record['email'];
                    }
                }
                // Add email to table
                DB::insert(prefix_table("emails"), array('timestamp' => time(), 'subject' => $LANG['email_subject_on_user_login'], 'body' => str_replace(array('#tp_user#', '#tp_date#', '#tp_time#'), array(" " . $_SESSION['login'], date($_SESSION['settings']['date_format'], $_SESSION['derniere_connexion']), date($_SESSION['settings']['time_format'], $_SESSION['derniere_connexion'])), $LANG['email_body_on_user_login']), 'receivers' => $receivers, 'status' => "not sent"));
            }
        } elseif ($data['disabled'] == 1) {
            // User and password is okay but account is locked
            $return = "user_is_locked";
        } else {
            // User exists in the DB but Password is false
            // check if user is locked
            $userIsLocked = 0;
            $nbAttempts = intval($data['no_bad_attempts'] + 1);
            if ($_SESSION['settings']['nb_bad_authentication'] > 0 && intval($_SESSION['settings']['nb_bad_authentication']) < $nbAttempts) {
                $userIsLocked = 1;
                // log it
                if (isset($_SESSION['settings']['log_connections']) && $_SESSION['settings']['log_connections'] == 1) {
                    logEvents('user_locked', 'connection', $data['id']);
                }
            }
            DB::update(prefix_table('users'), array('key_tempo' => $_SESSION['key'], 'last_connexion' => time(), 'disabled' => $userIsLocked, 'no_bad_attempts' => $nbAttempts), "id=%i", $data['id']);
            // What return shoulb we do
            if ($userIsLocked == 1) {
                $return = "user_is_locked";
            } elseif ($_SESSION['settings']['nb_bad_authentication'] == 0) {
                $return = "false";
            } else {
                $return = $nbAttempts;
            }
        }
    } else {
        $return = "false";
    }
    if ($debugDuo == 1) {
        fputs($dbgDuo, "\n\n----\n" . "Identified : " . $return . "\n");
    }
    echo '[{"value" : "' . $return . '", "user_admin":"', isset($_SESSION['user_admin']) ? $_SESSION['user_admin'] : "", '", "initial_url" : "' . @$_SESSION['initial_url'] . '",
            "error" : "' . $logError . '"}]';
    $_SESSION['initial_url'] = "";
    if ($_SESSION['settings']['cpassman_dir'] == "..") {
        $_SESSION['settings']['cpassman_dir'] = ".";
    }
}
예제 #3
0
     require_once '../sources/main.functions.php';
     //vérifier que l'admin n'existe pas
     $tmp = mysqli_fetch_row(mysqli_query($dbTmp, "SELECT COUNT(*) FROM `" . $_SESSION['tbl_prefix'] . "users` WHERE login = '******'"));
     if ($tmp[0] == 0) {
         $res8 = mysqli_query($dbTmp, "INSERT INTO `" . $_SESSION['tbl_prefix'] . "users` (`id`, `login`, `pw`, `groupes_visibles`, `derniers`, `key_tempo`, `last_pw_change`, `last_pw`, `admin`, `fonction_id`, `groupes_interdits`, `last_connexion`, `gestionnaire`, `email`, `favourites`, `latest_items`, `personal_folder`) VALUES (NULL, 'admin', '" . bCrypt('admin', '13') . "', '', '', '', '', '', '1', '', '', '', '0', '', '', '', '0')");
         if ($res8) {
             echo 'document.getElementById("tbl_8").innerHTML = "<img src=\\"images/tick.png\\">";';
         } else {
             echo 'document.getElementById("res_step4").innerHTML = "Could not import admin account!";';
             echo 'document.getElementById("tbl_8").innerHTML = "<img src=\\"images/exclamation-red.png\\">";';
             echo 'document.getElementById("loader").style.display = "none";';
             mysqli_close($dbTmp);
             break;
         }
     } else {
         mysqli_query($dbTmp, "UPDATE `" . $_SESSION['tbl_prefix'] . "users` SET `pw` = '" . bCrypt('admin', '13') . "' WHERE login = '******' AND id = '1'");
         echo 'document.getElementById("tbl_8").innerHTML = "<img src=\\"images/tick.png\\">";';
     }
 } else {
     echo 'document.getElementById("res_step4").innerHTML = "An error appears on table USERS! ' . mysqli_error($dbTmp) . '";';
     echo 'document.getElementById("tbl_7").innerHTML = "<img src=\\"images/exclamation-red.png\\">";';
     echo 'document.getElementById("loader").style.display = "none";';
     mysqli_close($dbTmp);
     break;
 }
 ## TABLE 8 - TAGS
 $res8 = mysqli_query($dbTmp, "CREATE TABLE IF NOT EXISTS `" . $_SESSION['tbl_prefix'] . "tags` (\n                  `id` int(12) NOT null AUTO_INCREMENT,\n                  `tag` varchar(30) NOT NULL,\n                  `item_id` int(12) NOT NULL,\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `id` (`id`)\n               ) CHARSET=utf8;");
 if ($res8) {
     echo 'document.getElementById("tbl_9").innerHTML = "<img src=\\"images/tick.png\\">";';
 } else {
     echo 'document.getElementById("res_step4").innerHTML = "An error appears on table TAGS! ' . mysqli_error($dbTmp) . '";';
예제 #4
0
                             }
                         }
                     }
                 }
             }
         }
     }
 } else {
     if ($activity == "entry") {
         if ($task == "admin") {
             // check that admin accounts doesn't exist
             $tmp = mysqli_fetch_row(mysqli_query($dbTmp, "SELECT COUNT(*) FROM `" . $var['tbl_prefix'] . "users` WHERE login = '******'"));
             if ($tmp[0] == 0 || empty($tmp[0])) {
                 $mysqli_result = mysqli_query($dbTmp, "INSERT INTO `" . $var['tbl_prefix'] . "users` (`id`, `login`, `pw`, `groupes_visibles`, `derniers`, `key_tempo`, `last_pw_change`, `last_pw`, `admin`, `fonction_id`, `groupes_interdits`, `last_connexion`, `gestionnaire`, `email`, `favourites`, `latest_items`, `personal_folder`) VALUES ('1', 'admin', '" . bCrypt($var['admin_pwd'], '13') . "', '', '', '', '', '', '1', '', '', '', '0', '', '', '', '0')");
             } else {
                 $mysqli_result = mysqli_query($dbTmp, "UPDATE `" . $var['tbl_prefix'] . "users` SET `pw` = '" . bCrypt($var['admin_pwd'], '13') . "' WHERE login = '******' AND id = '1'");
             }
             // check that API doesn't exist
             $tmp = mysqli_fetch_row(mysqli_query($dbTmp, "SELECT COUNT(*) FROM `" . $var['tbl_prefix'] . "users` WHERE id = '" . API_USER_ID . "'"));
             if ($tmp[0] == 0 || empty($tmp[0])) {
                 $mysqli_result = mysqli_query($dbTmp, "INSERT INTO `" . $var['tbl_prefix'] . "users` (`id`, `login`, `read_only`) VALUES ('" . API_USER_ID . "', 'API', '1')");
             }
         }
     }
 }
 // answer back
 if ($mysqli_result) {
     echo '[{"error" : "", "index" : "' . $_POST['index'] . '", "multiple" : "' . $_POST['multiple'] . '", "table" : "' . $task . '"}]';
 } else {
     echo '[{"error" : "' . $mysqli_result . '", "index" : "' . $_POST['index'] . '", "multiple" : "' . $_POST['multiple'] . '", "table" : "' . $task . '"}]';
 }
예제 #5
0
<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);
$Naam = $_POST["Naam"];
$Postcode = $_POST["Postcode"];
$Huisnr = $_POST["Huisnr"];
$Toevoeging = $_POST["Toevoeging"];
$Plaats = $_POST["Woonplaats"];
$Straat = $_POST["Straat"];
$Gebruikersnaam = $_POST["Gebruikersnaam"];
$Wachtwoord = $_POST["Wachtwoord"];
include "functions.php";
$link = connect();
if ($link == false) {
    echo 0;
    exit;
}
$Hash = bCrypt($Wachtwoord, 12);
$AdresID = insertAddress($Postcode, $Huisnr, $Toevoeging, $Straat, $Plaats);
$PersoonID = insertPersoon($Naam, $AdresID);
insertLogingegevens($PersoonID, $Gebruikersnaam, $Hash);
예제 #6
0
function rest_get()
{
    $_SESSION['user_id'] = "'api'";
    if (!@count($GLOBALS['request']) == 0) {
        $request_uri = $GLOBALS['_SERVER']['REQUEST_URI'];
        preg_match('/\\/api(\\/index.php|)\\/(.*)\\?apikey=(.*)/', $request_uri, $matches);
        if (count($matches) == 0) {
            rest_error('REQUEST_SENT_NOT_UNDERSTANDABLE');
        }
        $GLOBALS['request'] = explode('/', $matches[2]);
    }
    if (apikey_checker($GLOBALS['apikey'])) {
        global $server, $user, $pass, $database, $pre, $link;
        teampass_connect();
        $category_query = "";
        if ($GLOBALS['request'][0] == "read") {
            if ($GLOBALS['request'][1] == "category") {
                // get ids
                if (strpos($GLOBALS['request'][2], ";") > 0) {
                    $condition = "id_tree IN %ls";
                    $condition_value = explode(';', $GLOBALS['request'][2]);
                } else {
                    $condition = "id_tree = %s";
                    $condition_value = $GLOBALS['request'][2];
                }
                DB::debugMode(false);
                // get items in this module
                $response = DB::query("SELECT id,label,login,pw, pw_iv FROM " . prefix_table("items") . " WHERE " . $condition, $condition_value);
                foreach ($response as $data) {
                    // prepare output
                    $id = $data['id'];
                    $json[$id]['label'] = mb_convert_encoding($data['label'], mb_detect_encoding($data['label']), 'UTF-8');
                    $json[$id]['login'] = mb_convert_encoding($data['login'], mb_detect_encoding($data['login']), 'UTF-8');
                    $json[$id]['pw'] = cryption($data['pw'], SALT, $data['pw_iv'], "decrypt");
                }
                /* load folders */
                $response = DB::query("SELECT id,parent_id,title,nleft,nright,nlevel FROM " . prefix_table("nested_tree") . " WHERE parent_id=%i ORDER BY `title` ASC", $GLOBALS['request'][2]);
                $rows = array();
                $i = 0;
                foreach ($response as $row) {
                    $response = DB::query("SELECT id,label,login,pw, pw_iv FROM " . prefix_table("items") . " WHERE id_tree=%i", $row['id']);
                    foreach ($response as $data) {
                        // prepare output
                        $id = $data['id'];
                        $json[$id]['label'] = mb_convert_encoding($data['label'], mb_detect_encoding($data['label']), 'UTF-8');
                        $json[$id]['login'] = mb_convert_encoding($data['login'], mb_detect_encoding($data['login']), 'UTF-8');
                        $json[$id]['pw'] = cryption($data['pw'], SALT, $data['pw_iv'], "decrypt");
                    }
                }
            } elseif ($GLOBALS['request'][1] == "items") {
                $array_items = explode(';', $GLOBALS['request'][2]);
                // check if not empty
                if (count($array_items) == 0) {
                    rest_error('NO_ITEM');
                }
                // only accepts numeric
                foreach ($array_items as $item) {
                    if (!is_numeric($item)) {
                        rest_error('ITEM_MALFORMED');
                    }
                }
                $response = DB::query("select id,label,login,pw, pw_iv, id_tree from " . prefix_table("items") . " where id IN %ls", $array_items);
                foreach ($response as $data) {
                    // prepare output
                    $id = $data['id'];
                    $json[$id]['label'] = mb_convert_encoding($data['label'], mb_detect_encoding($data['label']), 'UTF-8');
                    $json[$id]['login'] = mb_convert_encoding($data['login'], mb_detect_encoding($data['login']), 'UTF-8');
                    $json[$id]['pw'] = cryption($data['pw'], SALT, $data['pw_iv'], "decrypt");
                }
            }
            if (isset($json) && $json) {
                echo json_encode($json);
            } else {
                rest_error('EMPTY');
            }
        } elseif ($GLOBALS['request'][0] == "find") {
            if ($GLOBALS['request'][1] == "item") {
                $array_category = explode(';', $GLOBALS['request'][2]);
                $item = $GLOBALS['request'][3];
                foreach ($array_category as $category) {
                    if (!preg_match_all("/^([\\w\\:\\'\\-\\sàáâãäåçèéêëìíîïðòóôõöùúûüýÿ]+)\$/i", $category, $result)) {
                        rest_error('CATEGORY_MALFORMED');
                    }
                }
                if (!preg_match_all("/^([\\w\\:\\'\\-\\sàáâãäåçèéêëìíîïðòóôõöùúûüýÿ]+)\$/i", $item, $result)) {
                    rest_error('ITEM_MALFORMED');
                } elseif (empty($item) || count($array_category) == 0) {
                    rest_error('MALFORMED');
                }
                if (count($array_category) > 1 && count($array_category) < 5) {
                    for ($i = count($array_category); $i > 0; $i--) {
                        $slot = $i - 1;
                        if (!$slot) {
                            $category_query .= "select id from " . prefix_table("nested_tree") . " where title LIKE '" . $array_category[$slot] . "' AND parent_id = 0";
                        } else {
                            $category_query .= "select id from " . prefix_table("nested_tree") . " where title LIKE '" . $array_category[$slot] . "' AND parent_id = (";
                        }
                    }
                    for ($i = 1; $i < count($array_category); $i++) {
                        $category_query .= ")";
                    }
                } elseif (count($array_category) == 1) {
                    $category_query = "select id from " . prefix_table("nested_tree") . " where title LIKE '" . $array_category[0] . "' AND parent_id = 0";
                } else {
                    rest_error('NO_CATEGORY');
                }
                DB::debugMode(false);
                $response = DB::query("select id, label, login, pw, pw_iv, id_tree\n                    from " . prefix_table("items") . "\n                    where id_tree = (%s)\n                    and label LIKE %ss", $category_query, $item);
                foreach ($response as $data) {
                    // prepare output
                    $json['id'] = mb_convert_encoding($data['id'], mb_detect_encoding($data['id']), 'UTF-8');
                    $json['label'] = mb_convert_encoding($data['label'], mb_detect_encoding($data['label']), 'UTF-8');
                    $json['login'] = mb_convert_encoding($data['login'], mb_detect_encoding($data['login']), 'UTF-8');
                    $json['pw'] = cryption($data['pw'], SALT, $data['pw_iv'], "decrypt");
                    $json['folder_id'] = $data['id_tree'];
                    $json['status'] = utf8_encode("OK");
                }
                if (isset($json) && $json) {
                    echo json_encode($json);
                } else {
                    rest_error('EMPTY');
                }
            }
        } elseif ($GLOBALS['request'][0] == "add") {
            if ($GLOBALS['request'][1] == "item") {
                // get item definition
                $array_item = explode(';', urldecode($GLOBALS['request'][2]));
                if (count($array_item) != 9) {
                    rest_error('ITEMBADDEFINITION');
                }
                $item_label = $array_item[0];
                $item_pwd = $array_item[1];
                $item_desc = $array_item[2];
                $item_folder_id = $array_item[3];
                $item_login = $array_item[4];
                $item_email = $array_item[5];
                $item_url = $array_item[6];
                $item_tags = $array_item[7];
                $item_anyonecanmodify = $array_item[8];
                // added so one can sent data including the http or https !
                // anyway we have to urlencode this data
                $item_url = urldecode($item_url);
                // same for the email
                $item_email = urldecode($item_email);
                // do some checks
                if (!empty($item_label) && !empty($item_pwd) && !empty($item_folder_id)) {
                    // Check length
                    if (strlen($item_pwd) > 50) {
                        rest_error('PASSWORDTOOLONG');
                    }
                    // Check Folder ID
                    DB::query("SELECT * FROM " . prefix_table("nested_tree") . " WHERE id = %i", $item_folder_id);
                    $counter = DB::count();
                    if ($counter == 0) {
                        rest_error('NOSUCHFOLDER');
                    }
                    // check if element doesn't already exist
                    DB::query("SELECT * FROM " . prefix_table("items") . " WHERE label = %s AND inactif = %i", addslashes($item_label), "0");
                    $counter = DB::count();
                    if ($counter != 0) {
                        $itemExists = 1;
                        // prevent the error if the label already exists
                        // so lets just add the time() as a random factor
                        $item_label .= " (" . time() . ")";
                    } else {
                        $itemExists = 0;
                    }
                    if ($itemExists == 0) {
                        $encrypt = cryption($item_pwd, SALT, "", "encrypt");
                        if (empty($encrypt['string'])) {
                            rest_error('PASSWORDEMPTY');
                        }
                        // ADD item
                        try {
                            DB::insert(prefix_table("items"), array("label" => $item_label, "description" => $item_desc, 'pw' => $encrypt['string'], 'pw_iv' => $encrypt['iv'], "email" => $item_email, "url" => $item_url, "id_tree" => intval($item_folder_id), "login" => $item_login, "inactif" => 0, "restricted_to" => "", "perso" => 0, "anyone_can_modify" => intval($item_anyonecanmodify)));
                            $newID = DB::InsertId();
                            // log
                            DB::insert(prefix_table("log_items"), array("id_item" => $newID, "date" => time(), "id_user" => "9999999", "action" => "at_creation"));
                            // Add tags
                            $tags = explode(' ', $item_tags);
                            foreach ((array) $tags as $tag) {
                                if (!empty($tag)) {
                                    DB::insert(prefix_table("tags"), array("item_id" => $newID, "tag" => strtolower($tag)));
                                }
                            }
                            // Update CACHE table
                            DB::insert(prefix_table("cache"), array("id" => $newID, "label" => $item_label, "description" => $item_desc, "tags" => $item_tags, "id_tree" => $item_folder_id, "perso" => "0", "restricted_to" => "", "login" => $item_login, "folder" => "", "author" => "9999999"));
                            echo '{"status":"item added"}';
                        } catch (PDOException $ex) {
                            echo '<br />' . $ex->getMessage();
                        }
                    } else {
                        rest_error('ITEMEXISTS');
                    }
                } else {
                    rest_error('ITEMMISSINGDATA');
                }
            } elseif ($GLOBALS['request'][1] == "user") {
                // get user definition
                $array_user = explode(';', $GLOBALS['request'][2]);
                if (count($array_user) != 11) {
                    rest_error('USERBADDEFINITION');
                }
                $login = $array_user[0];
                $name = $array_user[1];
                $lastname = $array_user[2];
                $password = $array_user[3];
                $email = $array_user[4];
                $adminby = $array_user[5];
                $isreadonly = $array_user[6];
                $roles = $array_user[7];
                $isadmin = $array_user[8];
                $ismanager = $array_user[9];
                $haspf = $array_user[10];
                // Empty user
                if (mysqli_escape_string($link, htmlspecialchars_decode($login)) == "") {
                    rest_error('USERLOGINEMPTY');
                }
                // Check if user already exists
                $data = DB::query("SELECT id, fonction_id, groupes_interdits, groupes_visibles FROM " . prefix_table("users") . "\n            WHERE login LIKE %ss", mysqli_escape_string($link, stripslashes($login)));
                if (DB::count() == 0) {
                    try {
                        // find AdminRole code in DB
                        $resRole = DB::queryFirstRow("SELECT id\n                            FROM " . prefix_table("roles_title") . "\n                            WHERE title LIKE %ss", mysqli_escape_string($link, stripslashes($adminby)));
                        // get default language
                        $lang = DB::queryFirstRow("SELECT `valeur` FROM " . prefix_table("misc") . " WHERE type = %s AND intitule = %s", "admin", "default_language");
                        // prepare roles list
                        $rolesList = "";
                        foreach (explode('|', $roles) as $role) {
                            echo $role . "-";
                            $tmp = DB::queryFirstRow("SELECT `id` FROM " . prefix_table("roles_title") . " WHERE title = %s", $role);
                            if (empty($rolesList)) {
                                $rolesList = $tmp['id'];
                            } else {
                                $rolesList .= ";" . $tmp['id'];
                            }
                        }
                        // Add user in DB
                        DB::insert(prefix_table("users"), array('login' => $login, 'name' => $name, 'lastname' => $lastname, 'pw' => bCrypt(stringUtf8Decode($password), COST), 'email' => $email, 'admin' => intval($isadmin), 'gestionnaire' => intval($ismanager), 'read_only' => intval($isreadonly), 'personal_folder' => intval($haspf), 'user_language' => $lang['valeur'], 'fonction_id' => $rolesList, 'groupes_interdits' => '0', 'groupes_visibles' => '0', 'isAdministratedByRole' => empty($resRole) ? '0' : $resRole['id']));
                        $new_user_id = DB::insertId();
                        // Create personnal folder
                        if (intval($haspf) == 1) {
                            DB::insert(prefix_table("nested_tree"), array('parent_id' => '0', 'title' => $new_user_id, 'bloquer_creation' => '0', 'bloquer_modification' => '0', 'personal_folder' => '1'));
                        }
                        // Send email to new user
                        @sendEmail($LANG['email_subject_new_user'], str_replace(array('#tp_login#', '#tp_pw#', '#tp_link#'), array(" " . addslashes($login), addslashes($password), $_SESSION['settings']['email_server_url']), $LANG['email_new_user_mail']), $email);
                        // update LOG
                        logEvents('user_mngt', 'at_user_added', 'api - ' . $GLOBALS['apikey'], $new_user_id);
                        echo '{"status":"user added"}';
                    } catch (PDOException $ex) {
                        echo '<br />' . $ex->getMessage();
                    }
                } else {
                    rest_error('USERALREADYEXISTS');
                }
            }
        } elseif ($GLOBALS['request'][0] == "auth") {
            /*
             ** FOR SECURITY PURPOSE, it is mandatory to use SSL to connect your teampass instance. The user password is not encrypted!
             **
             **
             ** Expected call format: .../api/index.php/auth/<PROTOCOL>/<URL>/<login>/<password>?apikey=<VALID API KEY>
             ** Example: https://127.0.0.1/teampass/api/index.php/auth/http/www.zadig-tge.adp.com/U1/test/76?apikey=chahthait5Aidood6johh6Avufieb6ohpaixain
             ** RESTRICTIONS:
             **              - <PROTOCOL>        ==> http|https|ftp|...
             **              - <URL>             ==> encode URL without protocol (example: http://www.teampass.net becomes www.teampass.net)
             **              - <login>           ==> user's login
             **              - <password>        ==> currently clear password
             **
             ** RETURNED ANSWER:
             **              - format sent back is JSON
             **              - Example: {"<item_id>":{"label":"<pass#1>","login":"******","pw":"<pwd#1>"},"<item_id>":{"label":"<pass#2>","login":"******","pw":"<pwd#2>"}}
             **
             */
            // get user credentials
            if (isset($GLOBALS['request'][3]) && isset($GLOBALS['request'][4])) {
                // get url
                if (isset($GLOBALS['request'][1]) && isset($GLOBALS['request'][2])) {
                    // is user granted?
                    $user = DB::queryFirstRow("SELECT `id`, `pw`, `groupes_interdits`, `groupes_visibles`, `fonction_id` FROM " . $pre . "users WHERE login = %s", $GLOBALS['request'][3]);
                    // load passwordLib library
                    $_SESSION['settings']['cpassman_dir'] = "..";
                    require_once '../sources/SplClassLoader.php';
                    $pwdlib = new SplClassLoader('PasswordLib', '../includes/libraries');
                    $pwdlib->register();
                    $pwdlib = new PasswordLib\PasswordLib();
                    if ($pwdlib->verifyPasswordHash($GLOBALS['request'][4], $user['pw']) === true) {
                        // define the restriction of "id_tree" of this user
                        $userDef = DB::queryOneColumn('folder_id', "SELECT DISTINCT folder_id \n                            FROM " . prefix_table("roles_values") . "\n                            WHERE type IN ('R', 'W') ", empty($user['groupes_interdits']) ? "" : "\n                            AND folder_id NOT IN (" . str_replace(";", ",", $user['groupes_interdits']) . ")", " \n                            AND role_id IN %ls \n                            GROUP BY folder_id", explode(";", $user['groupes_interdits']));
                        // complete with "groupes_visibles"
                        foreach (explode(";", $user['groupes_visibles']) as $v) {
                            array_push($userDef, $v);
                        }
                        // find the item associated to the url
                        $response = DB::query("SELECT id, label, login, pw, pw_iv, id_tree, restricted_to\n                            FROM " . prefix_table("items") . " \n                            WHERE url LIKE %s\n                            AND id_tree IN (" . implode(",", $userDef) . ")\n                            ORDER BY id DESC", $GLOBALS['request'][1] . "://" . urldecode($GLOBALS['request'][2] . '%'));
                        $counter = DB::count();
                        if ($counter > 0) {
                            $json = "";
                            foreach ($response as $data) {
                                // check if item visible
                                if (empty($data['restricted_to']) || $data['restricted_to'] != "" && in_array($user['id'], explode(";", $data['restricted_to']))) {
                                    // prepare export
                                    $json[$data['id']]['label'] = mb_convert_encoding($data['label'], mb_detect_encoding($data['label']), 'UTF-8');
                                    $json[$data['id']]['login'] = mb_convert_encoding($data['login'], mb_detect_encoding($data['login']), 'UTF-8');
                                    $json[$data['id']]['pw'] = cryption($data['pw'], SALT, $data['pw_iv'], "decrypt");
                                }
                            }
                            // prepare answer. If no access then inform
                            if (empty($json)) {
                                rest_error('AUTH_NO_DATA');
                            } else {
                                echo json_encode($json);
                            }
                        } else {
                            rest_error('AUTH_NO_DATA');
                        }
                    } else {
                        rest_error('AUTH_NOT_GRANTED');
                    }
                } else {
                    rest_error('AUTH_NO_URL');
                }
            } else {
                rest_error('AUTH_NO_IDENTIFIER');
            }
        } elseif ($GLOBALS['request'][0] == "set") {
            /*
             * Expected call format: .../api/index.php/set/<login_to_save>/<password_to_save>/<url>/<user_login>/<user_password>?apikey=<VALID API KEY>
             * Example: https://127.0.0.1/teampass/api/index.php/auth/myLogin/myPassword/USER1/test/76?apikey=chahthait5Aidood6johh6Avufieb6ohpaixain
             *
             * NEW ITEM WILL BE STORED IN SPECIFIC FOLDER
             */
            // get user credentials
            if (isset($GLOBALS['request'][4]) && isset($GLOBALS['request'][5])) {
                // get url
                if (isset($GLOBALS['request'][1]) && isset($GLOBALS['request'][2]) && isset($GLOBALS['request'][3])) {
                    // is user granted?
                    $user = DB::queryFirstRow("SELECT `id`, `pw`, `groupes_interdits`, `groupes_visibles`, `fonction_id` FROM " . $pre . "users WHERE login = %s", $GLOBALS['request'][4]);
                    // load passwordLib library
                    $_SESSION['settings']['cpassman_dir'] = "..";
                    require_once '../sources/SplClassLoader.php';
                    $pwdlib = new SplClassLoader('PasswordLib', '../includes/libraries');
                    $pwdlib->register();
                    $pwdlib = new PasswordLib\PasswordLib();
                    // is user identified?
                    if ($pwdlib->verifyPasswordHash($GLOBALS['request'][5], $user['pw']) === true) {
                        // does the personal folder of this user exists?
                        DB::queryFirstRow("SELECT `id`\n                            FROM " . $pre . "nested_tree\n                            WHERE title = %s AND personal_folder = 1", $user['id']);
                        if (DB::count() > 0) {
                            // check if "teampass-connect" folder exists
                            // if not create it
                            $folder = DB::queryFirstRow("SELECT `id`\n                                FROM " . $pre . "nested_tree\n                                WHERE title = %s", "teampass-connect");
                            if (DB::count() == 0) {
                                DB::insert(prefix_table("nested_tree"), array('parent_id' => '0', 'title' => "teampass-connect"));
                                $tpc_folder_id = DB::insertId();
                                //Add complexity
                                DB::insert(prefix_table("misc"), array('type' => 'complex', 'intitule' => $tpc_folder_id, 'valeur' => '0'));
                                // rebuild tree
                                $tree = new Tree\NestedTree\NestedTree(prefix_table("nested_tree"), 'id', 'parent_id', 'title');
                                $tree->rebuild();
                            } else {
                                $tpc_folder_id = $folder['id'];
                            }
                            // encrypt password
                            $encrypt = cryption($GLOBALS['request'][2], SALT, "", "encrypt");
                            // add new item
                            DB::insert(prefix_table("items"), array('label' => "Credentials for " . urldecode($GLOBALS['request'][3] . '%'), 'description' => "Imported with Teampass-Connect", 'pw' => $encrypt['string'], 'pw_iv' => $encrypt['iv'], 'email' => "", 'url' => urldecode($GLOBALS['request'][3] . '%'), 'id_tree' => $tpc_folder_id, 'login' => $GLOBALS['request'][1], 'inactif' => '0', 'restricted_to' => $user['id'], 'perso' => '0', 'anyone_can_modify' => '0', 'complexity_level' => '0'));
                            $newID = DB::insertId();
                            // log
                            logItems($newID, "Credentials for " . urldecode($GLOBALS['request'][3] . '%'), $user['id'], 'at_creation', $GLOBALS['request'][1]);
                            $json['status'] = "ok";
                            // prepare answer. If no access then inform
                            if (empty($json)) {
                                rest_error('AUTH_NO_DATA');
                            } else {
                                echo json_encode($json);
                            }
                        } else {
                            rest_error('NO_PF_EXIST_FOR_USER');
                        }
                    } else {
                        rest_error('AUTH_NOT_GRANTED');
                    }
                } else {
                    rest_error('SET_NO_DATA');
                }
            } else {
                rest_error('AUTH_NO_IDENTIFIER');
            }
        } else {
            rest_error('METHOD');
        }
    }
}
예제 #7
0
<?php

//function bCrypt tirée directement de sources/main.functions.php, ligne 223.
function bCrypt($password, $cost)
{
    $salt = sprintf('$2y$%02d$', $cost);
    if (function_exists('openssl_random_pseudo_bytes')) {
        $salt .= bin2hex(openssl_random_pseudo_bytes(11));
    } else {
        $chars = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        for ($i = 0; $i < 22; $i++) {
            $salt .= $chars[mt_rand(0, 63)];
        }
    }
    return crypt($password, $salt);
}
// Le script prend en argument le mot de passe à chiffrer
echo bCrypt("{$argv['1']}", '13') . "\n";
예제 #8
0
 // check if key is okay
 $data = DB::queryFirstRow("SELECT valeur FROM " . $pre . "misc WHERE intitule = %s AND type = %s", mysqli_escape_string($link, $login), "password_recovery");
 if ($key == $data['valeur']) {
     //Load PWGEN
     $pwgen = new SplClassLoader('Encryption\\PwGen', '../includes/libraries');
     $pwgen->register();
     $pwgen = new Encryption\PwGen\pwgen();
     // Generate and change pw
     $newPw = "";
     $pwgen->setLength(10);
     $pwgen->setSecure(true);
     $pwgen->setSymbols(false);
     $pwgen->setCapitalize(true);
     $pwgen->setNumerals(true);
     $newPwNotCrypted = $pwgen->generate();
     $newPw = bCrypt(stringUtf8Decode($newPwNotCrypted), COST);
     // update DB
     DB::update($pre . "users", array('pw' => $newPw), "login = %s", mysqli_escape_string($link, $login));
     // Delete recovery in DB
     DB::delete($pre . "misc", "type = %s AND intitule = %s AND valeur = %s", "password_recovery", mysqli_escape_string($link, $login), $key);
     // Get email
     $dataUser = DB::queryFirstRow("SELECT email FROM " . $pre . "users WHERE login = %s", mysqli_escape_string($link, $login));
     $_SESSION['validite_pw'] = false;
     // send to user
     $ret = json_decode(@sendEmail($LANG['forgot_pw_email_subject_confirm'], $LANG['forgot_pw_email_body'] . " " . $newPwNotCrypted, $dataUser['email'], strip_tags($LANG['forgot_pw_email_body']) . " " . $newPwNotCrypted));
     // send email
     if (empty($ret['error'])) {
         echo 'done';
     } else {
         echo $ret['message'];
     }
예제 #9
0
 case "add_new_user":
     // Check KEY
     if ($_POST['key'] != $_SESSION['key']) {
         // error
         exit;
     }
     // Empty user
     if (mysqli_escape_string($link, htmlspecialchars_decode($_POST['login'])) == "") {
         echo '[ { "error" : "' . addslashes($LANG['error_empty_data']) . '" } ]';
         break;
     }
     // Check if user already exists
     $data = DB::query("SELECT id, fonction_id, groupes_interdits, groupes_visibles FROM " . $pre . "users\n                WHERE login LIKE %ss", mysqli_escape_string($link, stripslashes($_POST['login'])));
     if (DB::count() == 0) {
         // Add user in DB
         DB::insert($pre . "users", array('login' => mysqli_escape_string($link, htmlspecialchars_decode($_POST['login'])), 'name' => mysqli_escape_string($link, htmlspecialchars_decode($_POST['name'])), 'lastname' => mysqli_escape_string($link, htmlspecialchars_decode($_POST['lastname'])), 'pw' => bCrypt(stringUtf8Decode($_POST['pw']), COST), 'email' => $_POST['email'], 'admin' => $_POST['admin'] == "true" ? '1' : '0', 'gestionnaire' => $_POST['manager'] == "true" ? '1' : '0', 'read_only' => $_POST['read_only'] == "true" ? '1' : '0', 'personal_folder' => $_POST['personal_folder'] == "true" ? '1' : '0', 'fonction_id' => $_POST['manager'] == "true" ? $_SESSION['fonction_id'] : '0', 'groupes_interdits' => $_POST['manager'] == "true" ? $data['groupes_interdits'] : '0', 'groupes_visibles' => $_POST['manager'] == "true" ? $data['groupes_visibles'] : '0', 'isAdministratedByRole' => $_POST['isAdministratedByRole']));
         $new_user_id = DB::insertId();
         // Create personnal folder
         if ($_POST['personal_folder'] == "true") {
             DB::insert($pre . "nested_tree", array('parent_id' => '0', 'title' => $new_user_id, 'bloquer_creation' => '0', 'bloquer_modification' => '0', 'personal_folder' => '1'));
         }
         // Create folder and role for domain
         if ($_POST['new_folder_role_domain'] == "true") {
             // create folder
             DB::insert($pre . "nested_tree", array('parent_id' => 0, 'title' => mysqli_escape_string($link, stripslashes($_POST['domain'])), 'personal_folder' => 0, 'renewal_period' => 0, 'bloquer_creation' => '0', 'bloquer_modification' => '0'));
             $new_folder_id = DB::insertId();
             // Add complexity
             DB::insert($pre . "misc", array('type' => 'complex', 'intitule' => $new_folder_id, 'valeur' => 50));
             // Create role
             DB::insert($pre . "roles_title", array('title' => mysqli_escape_string($link, stripslashes($_POST['domain']))));
             $new_role_id = DB::insertId();