isAjax()) { $response->setRequestStatus(false); // redirect_flag redirects to the login page $response->addJSON('redirect_flag', '1'); if (defined('TESTSUITE')) { return true; } else { exit; } } // No recall if blowfish secret is not configured as it would produce // garbage if ($GLOBALS['cfg']['LoginCookieRecall'] && ! empty($GLOBALS['cfg']['blowfish_secret']) ) { $default_user = $GLOBALS['PHP_AUTH_USER']; $default_server = $GLOBALS['pma_auth_server']; $autocomplete = ''; } else { $default_user = ''; $default_server = ''; // skip the IE autocomplete feature. $autocomplete = ' autocomplete="off"'; } $response->getFooter()->setMinimal(); $header = $response->getHeader(); $header->setBodyId('loginform'); $header->setTitle('phpMyAdmin'); $header->disableMenuAndConsole(); $header->disableWarnings(); if (@file_exists(CUSTOM_HEADER_FILE)) { include CUSTOM_HEADER_FILE; } echo '

'; echo sprintf( __('Welcome to %s'), 'phpMyAdmin' ); echo "

"; // Show error message if (! empty($conn_error)) { Message::rawError($conn_error)->display(); } elseif (isset($_GET['session_expired']) && intval($_GET['session_expired']) == 1 ) { Message::rawError( __('Your session has expired. Please log in again.') )->display(); } echo "\n"; echo "
"; // Displays the languages form if (empty($GLOBALS['cfg']['Lang'])) { include_once './libraries/display_select_lang.lib.php'; // use fieldset, don't show doc link echo PMA_getLanguageSelectorHtml(true, false); } echo '

'; echo __('Log in'); echo Util::showDocu('index'); echo ''; if ($GLOBALS['cfg']['AllowArbitraryServer']) { echo '
'; } echo '
'; if (count($GLOBALS['cfg']['Servers']) > 1) { echo '
'; } else { echo ' '; } // end if (server choice) // Add captcha input field if reCaptcha is enabled if (!empty($GLOBALS['cfg']['CaptchaLoginPrivateKey']) && !empty($GLOBALS['cfg']['CaptchaLoginPublicKey']) ) { // If enabled show captcha to the user on the login screen. echo ''; echo '
'; } echo '
'; $_form_params = array(); if (! empty($GLOBALS['target'])) { $_form_params['target'] = $GLOBALS['target']; } if (! empty($GLOBALS['db'])) { $_form_params['db'] = $GLOBALS['db']; } if (! empty($GLOBALS['table'])) { $_form_params['table'] = $GLOBALS['table']; } // do not generate a "server" hidden field as we want the "server" // drop-down to have priority echo PMA_URL_getHiddenInputs($_form_params, '', 0, 'server'); echo '
'; if ($GLOBALS['error_handler']->hasDisplayErrors()) { echo '
'; $GLOBALS['error_handler']->dispErrors(); echo '
'; } echo '
'; if (@file_exists(CUSTOM_FOOTER_FILE)) { include CUSTOM_FOOTER_FILE; } if (! defined('TESTSUITE')) { exit; } else { return true; } } /** * Gets advanced authentication settings * * this function DOES NOT check authentication - it just checks/provides * authentication credentials required to connect to the MySQL server * usually with $GLOBALS['dbi']->connect() * * it returns false if something is missing - which usually leads to * auth() which displays login form * * it returns true if all seems ok which usually leads to auth_set_user() * * it directly switches to authFails() if user inactivity timeout is reached * * @return boolean whether we get authentication settings or not */ public function authCheck() { global $conn_error; // Initialization /** * @global $GLOBALS['pma_auth_server'] the user provided server to * connect to */ $GLOBALS['pma_auth_server'] = ''; $GLOBALS['PHP_AUTH_USER'] = $GLOBALS['PHP_AUTH_PW'] = ''; $GLOBALS['from_cookie'] = false; if (! empty($_REQUEST['pma_username'])) { // Verify Captcha if it is required. if (! empty($GLOBALS['cfg']['CaptchaLoginPrivateKey']) && ! empty($GLOBALS['cfg']['CaptchaLoginPublicKey']) ) { if (! empty($_POST["g-recaptcha-response"])) { include_once 'libraries/plugins/auth/recaptcha/autoload.php'; $reCaptcha = new ReCaptcha( $GLOBALS['cfg']['CaptchaLoginPrivateKey'] ); // verify captcha status. $resp = $reCaptcha->verify( $_POST["g-recaptcha-response"], $_SERVER["REMOTE_ADDR"] ); // Check if the captcha entered is valid, if not stop the login. if ($resp == null || ! $resp->isSuccess()) { $conn_error = __('Entered captcha is wrong, try again!'); return false; } } else { $conn_error = __('Please enter correct captcha!'); return false; } } // The user just logged in $GLOBALS['PHP_AUTH_USER'] = PMA_sanitizeMySQLUser($_REQUEST['pma_username']); $GLOBALS['PHP_AUTH_PW'] = empty($_REQUEST['pma_password']) ? '' : $_REQUEST['pma_password']; if ($GLOBALS['cfg']['AllowArbitraryServer'] && isset($_REQUEST['pma_servername']) ) { if ($GLOBALS['cfg']['ArbitraryServerRegexp']) { $parts = explode(' ', $_REQUEST['pma_servername']); if (count($parts) == 2) { $tmp_host = $parts[0]; } else { $tmp_host = $_REQUEST['pma_servername']; } $match = preg_match( $GLOBALS['cfg']['ArbitraryServerRegexp'], $tmp_host ); if (! $match) { $conn_error = __( 'You are not allowed to log in to this MySQL server!' ); return false; } } $GLOBALS['pma_auth_server'] = PMA_sanitizeMySQLHost($_REQUEST['pma_servername']); } PMA_secureSession(); return true; } // At the end, try to set the $GLOBALS['PHP_AUTH_USER'] // and $GLOBALS['PHP_AUTH_PW'] variables from cookies // check cookies if (empty($_COOKIE['pmaUser-' . $GLOBALS['server']])) { return false; } $GLOBALS['PHP_AUTH_USER'] = $this->cookieDecrypt( $_COOKIE['pmaUser-' . $GLOBALS['server']], $this->_getEncryptionSecret() ); // user was never logged in since session start if (empty($_SESSION['last_access_time'])) { return false; } // User inactive too long $last_access_time = time() - $GLOBALS['cfg']['LoginCookieValidity']; if ($_SESSION['last_access_time'] < $last_access_time) { Util::cacheUnset('is_create_db_priv'); Util::cacheUnset('is_reload_priv'); Util::cacheUnset('db_to_create'); Util::cacheUnset('dbs_where_create_table_allowed'); Util::cacheUnset('dbs_to_test'); Util::cacheUnset('db_priv'); Util::cacheUnset('col_priv'); Util::cacheUnset('table_priv'); Util::cacheUnset('proc_priv'); $GLOBALS['no_activity'] = true; $this->authFails(); if (! defined('TESTSUITE')) { exit; } else { return false; } } // check password cookie if (empty($_COOKIE['pmaAuth-' . $GLOBALS['server']])) { return false; } $auth_data = json_decode( $this->cookieDecrypt( $_COOKIE['pmaAuth-' . $GLOBALS['server']], $this->_getSessionEncryptionSecret() ), true ); if (! is_array($auth_data) || ! isset($auth_data['password'])) { return false; } $GLOBALS['PHP_AUTH_PW'] = $auth_data['password']; if ($GLOBALS['cfg']['AllowArbitraryServer'] && ! empty($auth_data['server'])) { $GLOBALS['pma_auth_server'] = $auth_data['server']; } $GLOBALS['from_cookie'] = true; return true; } /** * Set the user and password after last checkings if required * * @return boolean always true */ public function authSetUser() { global $cfg; // Ensures valid authentication mode, 'only_db', bookmark database and // table names and relation table name are used if (! hash_equals($cfg['Server']['user'], $GLOBALS['PHP_AUTH_USER'])) { foreach ($cfg['Servers'] as $idx => $current) { if ($current['host'] == $cfg['Server']['host'] && $current['port'] == $cfg['Server']['port'] && $current['socket'] == $cfg['Server']['socket'] && $current['ssl'] == $cfg['Server']['ssl'] && $current['connect_type'] == $cfg['Server']['connect_type'] && hash_equals($current['user'], $GLOBALS['PHP_AUTH_USER']) ) { $GLOBALS['server'] = $idx; $cfg['Server'] = $current; break; } } // end foreach } // end if if ($GLOBALS['cfg']['AllowArbitraryServer'] && ! empty($GLOBALS['pma_auth_server']) ) { /* Allow to specify 'host port' */ $parts = explode(' ', $GLOBALS['pma_auth_server']); if (count($parts) == 2) { $tmp_host = $parts[0]; $tmp_port = $parts[1]; } else { $tmp_host = $GLOBALS['pma_auth_server']; $tmp_port = ''; } if ($cfg['Server']['host'] != $GLOBALS['pma_auth_server']) { $cfg['Server']['host'] = $tmp_host; if (! empty($tmp_port)) { $cfg['Server']['port'] = $tmp_port; } } unset($tmp_host, $tmp_port, $parts); } $cfg['Server']['user'] = $GLOBALS['PHP_AUTH_USER']; $cfg['Server']['password'] = $GLOBALS['PHP_AUTH_PW']; // Avoid showing the password in phpinfo()'s output unset($GLOBALS['PHP_AUTH_PW']); unset($_SERVER['PHP_AUTH_PW']); $this->setSessionAccessTime(); } /** * Stores user credentials after successful login. * * @return void|bool */ public function storeUserCredentials() { global $cfg; // Name and password cookies need to be refreshed each time // Duration = one month for username $this->storeUsernameCookie($cfg['Server']['user']); // Duration = as configured // Do not store password cookie on password change as we will // set the cookie again after password has been changed if (! isset($_POST['change_pw'])) { $this->storePasswordCookie($cfg['Server']['password']); } // Set server cookies if required (once per session) and, in this case, // force reload to ensure the client accepts cookies if (! $GLOBALS['from_cookie']) { // URL where to go: $redirect_url = './index.php'; // any parameters to pass? $url_params = array(); if (mb_strlen($GLOBALS['db'])) { $url_params['db'] = $GLOBALS['db']; } if (mb_strlen($GLOBALS['table'])) { $url_params['table'] = $GLOBALS['table']; } // any target to pass? if (! empty($GLOBALS['target']) && $GLOBALS['target'] != 'index.php' ) { $url_params['target'] = $GLOBALS['target']; } /** * Clear user cache. */ Util::clearUserCache(); Response::getInstance() ->disable(); PMA_sendHeaderLocation( $redirect_url . PMA_URL_getCommon($url_params, 'text'), true ); if (! defined('TESTSUITE')) { exit; } else { return false; } } // end if return true; } /** * Stores username in a cookie. * * @param string $username User name * * @return void */ public function storeUsernameCookie($username) { // Name and password cookies need to be refreshed each time // Duration = one month for username $GLOBALS['PMA_Config']->setCookie( 'pmaUser-' . $GLOBALS['server'], $this->cookieEncrypt( $username, $this->_getEncryptionSecret() ) ); } /** * Stores password in a cookie. * * @param string $password Password * * @return void */ public function storePasswordCookie($password) { $payload = array('password' => $password); if ($GLOBALS['cfg']['AllowArbitraryServer'] && ! empty($GLOBALS['pma_auth_server'])) { $payload['server'] = $GLOBALS['pma_auth_server']; } // Duration = as configured $GLOBALS['PMA_Config']->setCookie( 'pmaAuth-' . $GLOBALS['server'], $this->cookieEncrypt( json_encode($payload), $this->_getSessionEncryptionSecret() ), null, $GLOBALS['cfg']['LoginCookieStore'] ); } /** * User is not allowed to login to MySQL -> authentication failed * * prepares error message and switches to auth() which display the error * and the login form * * this function MUST exit/quit the application, * currently done by call to auth() * * @return void */ public function authFails() { global $conn_error; // Deletes password cookie and displays the login form $GLOBALS['PMA_Config']->removeCookie('pmaAuth-' . $GLOBALS['server']); $conn_error = $this->getErrorMessage(); $response = Response::getInstance(); // needed for PHP-CGI (not need for FastCGI or mod-php) $response->header('Cache-Control: no-store, no-cache, must-revalidate'); $response->header('Pragma: no-cache'); $this->auth(); } /** * Returns blowfish secret or generates one if needed. * * @return string */ private function _getEncryptionSecret() { if (empty($GLOBALS['cfg']['blowfish_secret'])) { return $this->_getSessionEncryptionSecret(); } else { return $GLOBALS['cfg']['blowfish_secret']; } } /** * Returns blowfish secret or generates one if needed. * * @return string */ private function _getSessionEncryptionSecret() { if (empty($_SESSION['encryption_key'])) { if (self::useOpenSSL()) { $_SESSION['encryption_key'] = openssl_random_pseudo_bytes(32); } else { $_SESSION['encryption_key'] = Crypt\Random::string(32); } } return $_SESSION['encryption_key']; } /** * Checks whether we should use openssl for encryption. * * @return boolean */ public static function useOpenSSL() { return ( function_exists('openssl_encrypt') && function_exists('openssl_decrypt') && function_exists('openssl_random_pseudo_bytes') ); } /** * Concatenates secret in order to make it 16 bytes log * * This doesn't add any security, just ensures the secret * is long enough by copying it. * * @param string $secret Original secret * * @return string */ public function enlargeSecret($secret) { while (strlen($secret) < 16) { $secret .= $secret; } return substr($secret, 0, 16); } /** * Derives MAC secret from encryption secret. * * @param string $secret the secret * * @return string the MAC secret */ public function getMACSecret($secret) { // Grab first part, up to 16 chars // The MAC and AES secrets can overlap if original secret is short $length = strlen($secret); if ($length > 16) { return substr($secret, 0, 16); } return $this->enlargeSecret( $length == 1 ? $secret : substr($secret, 0, -1) ); } /** * Derives AES secret from encryption secret. * * @param string $secret the secret * * @return string the AES secret */ public function getAESSecret($secret) { // Grab second part, up to 16 chars // The MAC and AES secrets can overlap if original secret is short $length = strlen($secret); if ($length > 16) { return substr($secret, -16); } return $this->enlargeSecret( $length == 1 ? $secret : substr($secret, 1) ); } /** * Encryption using openssl's AES or phpseclib's AES * (phpseclib uses mcrypt when it is available) * * @param string $data original data * @param string $secret the secret * * @return string the encrypted result */ public function cookieEncrypt($data, $secret) { $mac_secret = $this->getMACSecret($secret); $aes_secret = $this->getAESSecret($secret); $iv = $this->createIV(); if (self::useOpenSSL()) { $result = openssl_encrypt( $data, 'AES-128-CBC', $secret, 0, $iv ); } else { $cipher = new Crypt\AES(Crypt\Base::MODE_CBC); $cipher->setIV($iv); $cipher->setKey($aes_secret); $result = base64_encode($cipher->encrypt($data)); } $iv = base64_encode($iv); return json_encode( array( 'iv' => $iv, 'mac' => hash_hmac('sha1', $iv . $result, $mac_secret), 'payload' => $result, ) ); } /** * Decryption using openssl's AES or phpseclib's AES * (phpseclib uses mcrypt when it is available) * * @param string $encdata encrypted data * @param string $secret the secret * * @return string|bool original data, false on error */ public function cookieDecrypt($encdata, $secret) { $data = json_decode($encdata, true); if (! is_array($data) || ! isset($data['mac']) || ! isset($data['iv']) || ! isset($data['payload']) || ! is_string($data['mac']) || ! is_string($data['iv']) || ! is_string($data['payload']) ) { return false; } $mac_secret = $this->getMACSecret($secret); $aes_secret = $this->getAESSecret($secret); $newmac = hash_hmac('sha1', $data['iv'] . $data['payload'], $mac_secret); if (! hash_equals($data['mac'], $newmac)) { return false; } if (self::useOpenSSL()) { return openssl_decrypt( $data['payload'], 'AES-128-CBC', $secret, 0, base64_decode($data['iv']) ); } else { $cipher = new Crypt\AES(Crypt\Base::MODE_CBC); $cipher->setIV(base64_decode($data['iv'])); $cipher->setKey($aes_secret); return $cipher->decrypt(base64_decode($data['payload'])); } } /** * Returns size of IV for encryption. * * @return int */ public function getIVSize() { if (self::useOpenSSL()) { return openssl_cipher_iv_length('AES-128-CBC'); } $cipher = new Crypt\AES(Crypt\Base::MODE_CBC); return $cipher->block_size; } /** * Initialization * Store the initialization vector because it will be needed for * further decryption. I don't think necessary to have one iv * per server so I don't put the server number in the cookie name. * * @return void */ public function createIV() { /* Testsuite shortcut only to allow predictable IV */ if (! is_null($this->_cookie_iv)) { return $this->_cookie_iv; } if (self::useOpenSSL()) { return openssl_random_pseudo_bytes( $this->getIVSize() ); } else { return Crypt\Random::string( $this->getIVSize() ); } } /** * Sets encryption IV to use * * This is for testing only! * * @param string $vector The IV * * @return void */ public function setIV($vector) { $this->_cookie_iv = $vector; } /** * Callback when user changes password. * * @param string $password New password to set * * @return void */ public function handlePasswordChange($password) { $this->storePasswordCookie($password); } /** * Perform logout * * @return void */ public function logOut() { // -> delete password cookie(s) if ($GLOBALS['cfg']['LoginCookieDeleteAll']) { foreach ($GLOBALS['cfg']['Servers'] as $key => $val) { $GLOBALS['PMA_Config']->removeCookie('pmaAuth-' . $key); if (isset($_COOKIE['pmaAuth-' . $key])) { unset($_COOKIE['pmaAuth-' . $key]); } } } else { $GLOBALS['PMA_Config']->removeCookie( 'pmaAuth-' . $GLOBALS['server'] ); if (isset($_COOKIE['pmaAuth-' . $GLOBALS['server']])) { unset($_COOKIE['pmaAuth-' . $GLOBALS['server']]); } } parent::logOut(); } }