Upgraded phpmyadmin to 4.0.4 (All Languages) - No modifications yet
[openemr.git] / phpmyadmin / libraries / plugins / auth / AuthenticationCookie.class.php
blob72274d9e312dc4b87210919e796703acc353c207
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Cookie Authentication plugin for phpMyAdmin
6 * @package PhpMyAdmin-Authentication
7 * @subpackage Cookie
8 */
9 if (! defined('PHPMYADMIN')) {
10 exit;
13 /* Get the authentication interface */
14 require_once 'libraries/plugins/AuthenticationPlugin.class.php';
16 /**
17 * Remember where to redirect the user
18 * in case of an expired session.
20 if (! empty($_REQUEST['target'])) {
21 $GLOBALS['target'] = $_REQUEST['target'];
22 } else if (PMA_getenv('SCRIPT_NAME')) {
23 $GLOBALS['target'] = basename(PMA_getenv('SCRIPT_NAME'));
26 /**
27 * Swekey authentication functions.
29 require './libraries/plugins/auth/swekey/swekey.auth.lib.php';
31 /**
32 * Initialization
33 * Store the initialization vector because it will be needed for
34 * further decryption. I don't think necessary to have one iv
35 * per server so I don't put the server number in the cookie name.
37 if (function_exists('mcrypt_encrypt')) {
38 if (empty($_COOKIE['pma_mcrypt_iv'])
39 || ! ($iv = base64_decode($_COOKIE['pma_mcrypt_iv'], true))
40 ) {
41 srand((double) microtime() * 1000000);
42 $td = mcrypt_module_open(MCRYPT_BLOWFISH, '', MCRYPT_MODE_CBC, '');
43 if ($td === false) {
44 PMA_fatalError(__('Failed to use Blowfish from mcrypt!'));
46 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
47 $GLOBALS['PMA_Config']->setCookie(
48 'pma_mcrypt_iv',
49 base64_encode($iv)
54 /**
55 * Handles the cookie authentication method
57 * @package PhpMyAdmin-Authentication
59 class AuthenticationCookie extends AuthenticationPlugin
61 /**
62 * Displays authentication form
64 * this function MUST exit/quit the application
66 * @global string the last connection error
68 * @return void
70 public function auth()
72 global $conn_error;
74 $response = PMA_Response::getInstance();
75 if ($response->isAjax()) {
76 $response->isSuccess(false);
78 $login_link = '<br /><br />[ ' .
79 sprintf(
80 '<a href="%s" class="ajax login-link">%s</a>',
81 $GLOBALS['cfg']['PmaAbsoluteUri'],
82 __('Log in')
84 . ' ]';
86 if (! empty($conn_error)) {
88 $conn_error .= $login_link;
90 $response->addJSON(
91 'message',
92 PMA_Message::error(
93 $conn_error
96 } else {
97 $response->addJSON(
98 'message',
99 PMA_Message::error(
100 __('Your session has expired. Please log in again.') .
101 $login_link
105 exit;
108 /* Perform logout to custom URL */
109 if (! empty($_REQUEST['old_usr'])
110 && ! empty($GLOBALS['cfg']['Server']['LogoutURL'])
112 PMA_sendHeaderLocation($GLOBALS['cfg']['Server']['LogoutURL']);
113 exit;
116 // No recall if blowfish secret is not configured as it would produce
117 // garbage
118 if ($GLOBALS['cfg']['LoginCookieRecall']
119 && ! empty($GLOBALS['cfg']['blowfish_secret'])
121 $default_user = $GLOBALS['PHP_AUTH_USER'];
122 $default_server = $GLOBALS['pma_auth_server'];
123 $autocomplete = '';
124 } else {
125 $default_user = '';
126 $default_server = '';
127 // skip the IE autocomplete feature.
128 $autocomplete = ' autocomplete="off"';
131 $cell_align = ($GLOBALS['text_dir'] == 'ltr') ? 'left' : 'right';
133 $response->getFooter()->setMinimal();
134 $header = $response->getHeader();
135 $header->setBodyId('loginform');
136 $header->setTitle('phpMyAdmin');
137 $header->disableMenu();
138 $header->disableWarnings();
140 if (file_exists(CUSTOM_HEADER_FILE)) {
141 include CUSTOM_HEADER_FILE;
143 echo '
144 <div class="container">
145 <a href="';
146 echo PMA_linkURL('http://www.phpmyadmin.net/');
147 echo '" target="_blank" class="logo">';
148 $logo_image = $GLOBALS['pmaThemeImage'] . 'logo_right.png';
149 if (@file_exists($logo_image)) {
150 echo '<img src="' . $logo_image
151 . '" id="imLogo" name="imLogo" alt="phpMyAdmin" border="0" />';
152 } else {
153 echo '<img name="imLogo" id="imLogo" src="'
154 . $GLOBALS['pmaThemeImage'] . 'pma_logo.png' . '" '
155 . 'border="0" width="88" height="31" alt="phpMyAdmin" />';
157 echo '</a>
158 <h1>';
159 echo sprintf(
160 __('Welcome to %s'),
161 '<bdo dir="ltr" lang="en">phpMyAdmin</bdo>'
163 echo "</h1>";
165 // Show error message
166 if (! empty($conn_error)) {
167 PMA_Message::rawError($conn_error)->display();
170 echo "<noscript>\n";
171 PMA_message::error(
172 __("Javascript must be enabled past this point")
173 )->display();
174 echo "</noscript>\n";
176 echo "<div class='hide js-show'>";
177 // Displays the languages form
178 if (empty($GLOBALS['cfg']['Lang'])) {
179 include_once './libraries/display_select_lang.lib.php';
180 // use fieldset, don't show doc link
181 echo PMA_getLanguageSelectorHtml(true, false);
183 echo '</div>
184 <br />
185 <!-- Login form -->
186 <form method="post" action="index.php" name="login_form"' . $autocomplete .
187 ' class="disableAjax login hide js-show">
188 <fieldset>
189 <legend>';
190 echo __('Log in');
191 echo PMA_Util::showDocu('index');
192 echo '</legend>';
193 if ($GLOBALS['cfg']['AllowArbitraryServer']) {
194 echo '
195 <div class="item">
196 <label for="input_servername" title="';
197 echo __(
198 'You can enter hostname/IP address and port separated by space.'
200 echo '">';
201 echo __('Server:');
202 echo '</label>
203 <input type="text" name="pma_servername" id="input_servername"';
204 echo ' value="';
205 echo htmlspecialchars($default_server);
206 echo '" size="24" class="textfield" title="';
207 echo __(
208 'You can enter hostname/IP address and port separated by space.'
209 ); echo '" />
210 </div>';
212 echo '<div class="item">
213 <label for="input_username">' . __('Username:') . '</label>
214 <input type="text" name="pma_username" id="input_username" '
215 . 'value="' . htmlspecialchars($default_user) . '" size="24"'
216 . ' class="textfield"/>
217 </div>
218 <div class="item">
219 <label for="input_password">' . __('Password:') . '</label>
220 <input type="password" name="pma_password" id="input_password"'
221 . ' value="" size="24" class="textfield" />
222 </div>';
223 if (count($GLOBALS['cfg']['Servers']) > 1) {
224 echo '<div class="item">
225 <label for="select_server">' . __('Server Choice') .':</label>
226 <select name="server" id="select_server"';
227 if ($GLOBALS['cfg']['AllowArbitraryServer']) {
228 echo ' onchange="document.forms[\'login_form\'].'
229 . 'elements[\'pma_servername\'].value = \'\'" ';
231 echo '>';
233 include_once './libraries/select_server.lib.php';
234 echo PMA_selectServer(false, false);
236 echo '</select></div>';
237 } else {
238 echo ' <input type="hidden" name="server" value="'
239 . $GLOBALS['server'] . '" />';
240 } // end if (server choice)
242 echo '</fieldset>
243 <fieldset class="tblFooters">
244 <input value="' . __('Go') . '" type="submit" id="input_go" />';
245 $_form_params = array();
246 if (! empty($GLOBALS['target'])) {
247 $_form_params['target'] = $GLOBALS['target'];
249 if (! empty($GLOBALS['db'])) {
250 $_form_params['db'] = $GLOBALS['db'];
252 if (! empty($GLOBALS['table'])) {
253 $_form_params['table'] = $GLOBALS['table'];
255 // do not generate a "server" hidden field as we want the "server"
256 // drop-down to have priority
257 echo PMA_generate_common_hidden_inputs($_form_params, '', 0, 'server');
258 echo '</fieldset>
259 </form>';
261 // BEGIN Swekey Integration
262 Swekey_login('input_username', 'input_go');
263 // END Swekey Integration
265 if ($GLOBALS['error_handler']->hasDisplayErrors()) {
266 echo '<div>';
267 $GLOBALS['error_handler']->dispErrors();
268 echo '</div>';
270 echo '</div>';
271 if (file_exists(CUSTOM_FOOTER_FILE)) {
272 include CUSTOM_FOOTER_FILE;
274 exit;
278 * Gets advanced authentication settings
280 * this function DOES NOT check authentication - it just checks/provides
281 * authentication credentials required to connect to the MySQL server
282 * usually with PMA_DBI_connect()
284 * it returns false if something is missing - which usually leads to
285 * auth() which displays login form
287 * it returns true if all seems ok which usually leads to auth_set_user()
289 * it directly switches to authFails() if user inactivity timout is reached
291 * @todo AllowArbitraryServer on does not imply that the user wants an
292 * arbitrary server, or? so we should also check if this is filled
293 * and not only if allowed
295 * @return boolean whether we get authentication settings or not
297 public function authCheck()
299 // Initialization
301 * @global $GLOBALS['pma_auth_server'] the user provided server to
302 * connect to
304 $GLOBALS['pma_auth_server'] = '';
306 $GLOBALS['PHP_AUTH_USER'] = $GLOBALS['PHP_AUTH_PW'] = '';
307 $GLOBALS['from_cookie'] = false;
309 // BEGIN Swekey Integration
310 if (! Swekey_auth_check()) {
311 return false;
313 // END Swekey Integration
315 if (defined('PMA_CLEAR_COOKIES')) {
316 foreach ($GLOBALS['cfg']['Servers'] as $key => $val) {
317 $GLOBALS['PMA_Config']->removeCookie('pmaPass-' . $key);
318 $GLOBALS['PMA_Config']->removeCookie('pmaServer-' . $key);
319 $GLOBALS['PMA_Config']->removeCookie('pmaUser-' . $key);
321 return false;
324 if (! empty($_REQUEST['old_usr'])) {
325 // The user wants to be logged out
326 // -> delete his choices that were stored in session
328 // according to the PHP manual we should do this before the destroy:
329 //$_SESSION = array();
331 session_destroy();
332 // -> delete password cookie(s)
333 if ($GLOBALS['cfg']['LoginCookieDeleteAll']) {
334 foreach ($GLOBALS['cfg']['Servers'] as $key => $val) {
335 $GLOBALS['PMA_Config']->removeCookie('pmaPass-' . $key);
336 if (isset($_COOKIE['pmaPass-' . $key])) {
337 unset($_COOKIE['pmaPass-' . $key]);
340 } else {
341 $GLOBALS['PMA_Config']->removeCookie(
342 'pmaPass-' . $GLOBALS['server']
344 if (isset($_COOKIE['pmaPass-' . $GLOBALS['server']])) {
345 unset($_COOKIE['pmaPass-' . $GLOBALS['server']]);
350 if (! empty($_REQUEST['pma_username'])) {
351 // The user just logged in
352 $GLOBALS['PHP_AUTH_USER'] = $_REQUEST['pma_username'];
353 $GLOBALS['PHP_AUTH_PW'] = empty($_REQUEST['pma_password'])
354 ? ''
355 : $_REQUEST['pma_password'];
356 if ($GLOBALS['cfg']['AllowArbitraryServer']
357 && isset($_REQUEST['pma_servername'])
359 $GLOBALS['pma_auth_server'] = $_REQUEST['pma_servername'];
361 return true;
364 // At the end, try to set the $GLOBALS['PHP_AUTH_USER']
365 // and $GLOBALS['PHP_AUTH_PW'] variables from cookies
367 // servername
368 if ($GLOBALS['cfg']['AllowArbitraryServer']
369 && ! empty($_COOKIE['pmaServer-' . $GLOBALS['server']])
371 $GLOBALS['pma_auth_server']
372 = $_COOKIE['pmaServer-' . $GLOBALS['server']];
375 // username
376 if (empty($_COOKIE['pmaUser-' . $GLOBALS['server']])) {
377 return false;
380 $GLOBALS['PHP_AUTH_USER'] = $this->blowfishDecrypt(
381 $_COOKIE['pmaUser-' . $GLOBALS['server']],
382 $this->_getBlowfishSecret()
385 // user was never logged in since session start
386 if (empty($_SESSION['last_access_time'])) {
387 return false;
390 // User inactive too long
391 $last_access_time = time() - $GLOBALS['cfg']['LoginCookieValidity'];
392 if ($_SESSION['last_access_time'] < $last_access_time
394 PMA_Util::cacheUnset('is_create_db_priv', true);
395 PMA_Util::cacheUnset('is_process_priv', true);
396 PMA_Util::cacheUnset('is_reload_priv', true);
397 PMA_Util::cacheUnset('db_to_create', true);
398 PMA_Util::cacheUnset('dbs_where_create_table_allowed', true);
399 $GLOBALS['no_activity'] = true;
400 $this->authFails();
401 exit;
404 // password
405 if (empty($_COOKIE['pmaPass-' . $GLOBALS['server']])) {
406 return false;
409 $GLOBALS['PHP_AUTH_PW'] = $this->blowfishDecrypt(
410 $_COOKIE['pmaPass-' . $GLOBALS['server']],
411 $this->_getBlowfishSecret()
414 if ($GLOBALS['PHP_AUTH_PW'] == "\xff(blank)") {
415 $GLOBALS['PHP_AUTH_PW'] = '';
418 $GLOBALS['from_cookie'] = true;
420 return true;
424 * Set the user and password after last checkings if required
426 * @return boolean always true
428 public function authSetUser()
430 global $cfg;
432 // Ensures valid authentication mode, 'only_db', bookmark database and
433 // table names and relation table name are used
434 if ($cfg['Server']['user'] != $GLOBALS['PHP_AUTH_USER']) {
435 foreach ($cfg['Servers'] as $idx => $current) {
436 if ($current['host'] == $cfg['Server']['host']
437 && $current['port'] == $cfg['Server']['port']
438 && $current['socket'] == $cfg['Server']['socket']
439 && $current['ssl'] == $cfg['Server']['ssl']
440 && $current['connect_type'] == $cfg['Server']['connect_type']
441 && $current['user'] == $GLOBALS['PHP_AUTH_USER']
443 $GLOBALS['server'] = $idx;
444 $cfg['Server'] = $current;
445 break;
447 } // end foreach
448 } // end if
450 if ($GLOBALS['cfg']['AllowArbitraryServer']
451 && ! empty($GLOBALS['pma_auth_server'])
453 /* Allow to specify 'host port' */
454 $parts = explode(' ', $GLOBALS['pma_auth_server']);
455 if (count($parts) == 2) {
456 $tmp_host = $parts[0];
457 $tmp_port = $parts[1];
458 } else {
459 $tmp_host = $GLOBALS['pma_auth_server'];
460 $tmp_port = '';
462 if ($cfg['Server']['host'] != $GLOBALS['pma_auth_server']) {
463 $cfg['Server']['host'] = $tmp_host;
464 if (! empty($tmp_port)) {
465 $cfg['Server']['port'] = $tmp_port;
468 unset($tmp_host, $tmp_port, $parts);
470 $cfg['Server']['user'] = $GLOBALS['PHP_AUTH_USER'];
471 $cfg['Server']['password'] = $GLOBALS['PHP_AUTH_PW'];
473 // Avoid showing the password in phpinfo()'s output
474 unset($GLOBALS['PHP_AUTH_PW']);
475 unset($_SERVER['PHP_AUTH_PW']);
477 $_SESSION['last_access_time'] = time();
479 // Name and password cookies need to be refreshed each time
480 // Duration = one month for username
481 $GLOBALS['PMA_Config']->setCookie(
482 'pmaUser-' . $GLOBALS['server'],
483 $this->blowfishEncrypt(
484 $cfg['Server']['user'],
485 $this->_getBlowfishSecret()
489 // Duration = as configured
490 $GLOBALS['PMA_Config']->setCookie(
491 'pmaPass-' . $GLOBALS['server'],
492 $this->blowfishEncrypt(
493 ! empty($cfg['Server']['password'])
494 ? $cfg['Server']['password'] : "\xff(blank)",
495 $this->_getBlowfishSecret()
497 null,
498 $GLOBALS['cfg']['LoginCookieStore']
501 // Set server cookies if required (once per session) and, in this case,
502 // force reload to ensure the client accepts cookies
503 if (! $GLOBALS['from_cookie']) {
504 if ($GLOBALS['cfg']['AllowArbitraryServer']) {
505 if (! empty($GLOBALS['pma_auth_server'])) {
506 // Duration = one month for servername
507 $GLOBALS['PMA_Config']->setCookie(
508 'pmaServer-' . $GLOBALS['server'],
509 $cfg['Server']['host']
511 } else {
512 // Delete servername cookie
513 $GLOBALS['PMA_Config']->removeCookie(
514 'pmaServer-' . $GLOBALS['server']
519 // URL where to go:
520 $redirect_url = $cfg['PmaAbsoluteUri'] . 'index.php';
522 // any parameters to pass?
523 $url_params = array();
524 if (strlen($GLOBALS['db'])) {
525 $url_params['db'] = $GLOBALS['db'];
527 if (strlen($GLOBALS['table'])) {
528 $url_params['table'] = $GLOBALS['table'];
530 // any target to pass?
531 if (! empty($GLOBALS['target'])
532 && $GLOBALS['target'] != 'index.php'
534 $url_params['target'] = $GLOBALS['target'];
538 * Clear user cache.
540 PMA_Util::clearUserCache();
542 PMA_Response::getInstance()->disable();
544 PMA_sendHeaderLocation(
545 $redirect_url . PMA_generate_common_url($url_params, '&'),
546 true
548 exit;
549 } // end if
551 return true;
556 * User is not allowed to login to MySQL -> authentication failed
558 * prepares error message and switches to auth() which display the error
559 * and the login form
561 * this function MUST exit/quit the application,
562 * currently doen by call to auth()
564 * @return void
566 public function authFails()
568 global $conn_error;
570 // Deletes password cookie and displays the login form
571 $GLOBALS['PMA_Config']->removeCookie('pmaPass-' . $GLOBALS['server']);
573 if (! empty($GLOBALS['login_without_password_is_forbidden'])) {
574 $conn_error = __(
575 'Login without a password is forbidden by configuration'
576 . ' (see AllowNoPassword)'
578 } elseif (! empty($GLOBALS['allowDeny_forbidden'])) {
579 $conn_error = __('Access denied');
580 } elseif (! empty($GLOBALS['no_activity'])) {
581 $conn_error = sprintf(
582 __('No activity within %s seconds; please log in again'),
583 $GLOBALS['cfg']['LoginCookieValidity']
585 } elseif (PMA_DBI_getError()) {
586 $conn_error = '#' . $GLOBALS['errno'] . ' '
587 . __('Cannot log in to the MySQL server');
588 } else {
589 $conn_error = __('Cannot log in to the MySQL server');
592 // needed for PHP-CGI (not need for FastCGI or mod-php)
593 header('Cache-Control: no-store, no-cache, must-revalidate');
594 header('Pragma: no-cache');
596 $this->auth();
600 * Returns blowfish secret or generates one if needed.
602 * @return string
604 private function _getBlowfishSecret()
606 if (empty($GLOBALS['cfg']['blowfish_secret'])) {
607 if (empty($_SESSION['auto_blowfish_secret'])) {
608 // this returns 23 characters
609 $_SESSION['auto_blowfish_secret'] = uniqid('', true);
611 return $_SESSION['auto_blowfish_secret'];
612 } else {
613 // apply md5() to work around too long secrets (returns 32 characters)
614 return md5($GLOBALS['cfg']['blowfish_secret']);
619 * Encryption using blowfish algorithm (mcrypt)
620 * or phpseclib's AES if mcrypt not available
622 * @param string $data original data
623 * @param string $secret the secret
625 * @return string the encrypted result
627 public function blowfishEncrypt($data, $secret)
629 global $iv;
630 if (! function_exists('mcrypt_encrypt')) {
632 * This library uses mcrypt when available, so
633 * we could always call it instead of having an
634 * if/then/else logic, however the include_once
635 * call is costly
637 include_once "./libraries/phpseclib/Crypt/AES.php";
638 $cipher = new Crypt_AES(CRYPT_AES_MODE_ECB);
639 $cipher->setKey($secret);
640 return base64_encode($cipher->encrypt($data));
641 } else {
642 return base64_encode(
643 mcrypt_encrypt(
644 MCRYPT_BLOWFISH,
645 $secret,
646 $data,
647 MCRYPT_MODE_CBC,
655 * Decryption using blowfish algorithm (mcrypt)
656 * or phpseclib's AES if mcrypt not available
658 * @param string $encdata encrypted data
659 * @param string $secret the secret
661 * @return string original data
663 public function blowfishDecrypt($encdata, $secret)
665 global $iv;
666 if (! function_exists('mcrypt_encrypt')) {
667 include_once "./libraries/phpseclib/Crypt/AES.php";
668 $cipher = new Crypt_AES(CRYPT_AES_MODE_ECB);
669 $cipher->setKey($secret);
670 return $cipher->decrypt(base64_decode($encdata));
671 } else {
672 $data = base64_decode($encdata);
673 $decrypted = mcrypt_decrypt(
674 MCRYPT_BLOWFISH,
675 $secret,
676 $data,
677 MCRYPT_MODE_CBC,
680 return trim($decrypted);
685 * This method is called when any PluginManager to which the observer
686 * is attached calls PluginManager::notify()
688 * @param SplSubject $subject The PluginManager notifying the observer
689 * of an update.
691 * @return void
693 public function update (SplSubject $subject)