Add OK and Cancel button for grid editing
[phpmyadmin/arisferyanto.git] / libraries / auth / cookie.auth.lib.php
blobc21dbd6226a4c42fd36f234250d746e5f1f4c3a9
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Set of functions used to run cookie based authentication.
6 * @package PhpMyAdmin-Auth-Cookie
7 */
9 if (! defined('PHPMYADMIN')) {
10 exit;
13 /**
14 * Swekey authentication functions.
16 require './libraries/auth/swekey/swekey.auth.lib.php';
18 if (function_exists('mcrypt_encrypt')) {
19 /**
20 * Uses faster mcrypt library if available
21 * (as this is not called from anywhere else, put the code in-line
22 * for faster execution)
25 /**
26 * Initialization
27 * Store the initialization vector because it will be needed for
28 * further decryption. I don't think necessary to have one iv
29 * per server so I don't put the server number in the cookie name.
31 if (empty($_COOKIE['pma_mcrypt_iv']) || false === ($iv = base64_decode($_COOKIE['pma_mcrypt_iv'], true))) {
32 srand((double) microtime() * 1000000);
33 $td = mcrypt_module_open(MCRYPT_BLOWFISH, '', MCRYPT_MODE_CBC, '');
34 if ($td === false) {
35 die(__('Failed to use Blowfish from mcrypt!'));
37 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
38 $GLOBALS['PMA_Config']->setCookie('pma_mcrypt_iv', base64_encode($iv));
41 /**
42 * Encryption using blowfish algorithm (mcrypt)
44 * @param string original data
45 * @param string the secret
47 * @return string the encrypted result
49 * @access public
52 function PMA_blowfish_encrypt($data, $secret)
54 global $iv;
55 return base64_encode(mcrypt_encrypt(MCRYPT_BLOWFISH, $secret, $data, MCRYPT_MODE_CBC, $iv));
58 /**
59 * Decryption using blowfish algorithm (mcrypt)
61 * @param string encrypted data
62 * @param string the secret
64 * @return string original data
66 * @access public
69 function PMA_blowfish_decrypt($encdata, $secret)
71 global $iv;
72 return trim(mcrypt_decrypt(MCRYPT_BLOWFISH, $secret, base64_decode($encdata), MCRYPT_MODE_CBC, $iv));
75 } else {
76 include_once './libraries/blowfish.php';
79 /**
80 * Returns blowfish secret or generates one if needed.
82 * @access public
83 * @return string
85 function PMA_get_blowfish_secret()
87 if (empty($GLOBALS['cfg']['blowfish_secret'])) {
88 if (empty($_SESSION['auto_blowfish_secret'])) {
89 // this returns 23 characters
90 $_SESSION['auto_blowfish_secret'] = uniqid('', true);
92 return $_SESSION['auto_blowfish_secret'];
93 } else {
94 // apply md5() to work around too long secrets (returns 32 characters)
95 return md5($GLOBALS['cfg']['blowfish_secret']);
99 /**
100 * Displays authentication form
102 * this function MUST exit/quit the application
104 * @global string the last connection error
106 * @access public
108 function PMA_auth()
110 global $conn_error;
112 /* Perform logout to custom URL */
113 if (! empty($_REQUEST['old_usr'])
114 && ! empty($GLOBALS['cfg']['Server']['LogoutURL'])) {
115 PMA_sendHeaderLocation($GLOBALS['cfg']['Server']['LogoutURL']);
116 exit;
119 /* No recall if blowfish secret is not configured as it would produce garbage */
120 if ($GLOBALS['cfg']['LoginCookieRecall'] && !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 // Defines the charset to be used
134 header('Content-Type: text/html; charset=utf-8');
136 /* HTML header; do not show here the PMA version to improve security */
137 $page_title = 'phpMyAdmin ';
138 include './libraries/header_meta_style.inc.php';
139 // if $page_title is set, this script uses it as the title:
140 include './libraries/header_scripts.inc.php';
142 <script type="text/javascript">
143 //<![CDATA[
144 // show login form in top frame
145 if (top != self) {
146 window.top.location.href=location;
148 //]]>
149 </script>
150 </head>
152 <body class="loginform">
154 <?php
155 if (file_exists(CUSTOM_HEADER_FILE)) {
156 include CUSTOM_HEADER_FILE;
160 <div class="container">
161 <a href="<?php echo PMA_linkURL('http://www.phpmyadmin.net/'); ?>" target="_blank" class="logo"><?php
162 $logo_image = $GLOBALS['pmaThemeImage'] . 'logo_right.png';
163 if (@file_exists($logo_image)) {
164 echo '<img src="' . $logo_image . '" id="imLogo" name="imLogo" alt="phpMyAdmin" border="0" />';
165 } else {
166 echo '<img name="imLogo" id="imLogo" src="' . $GLOBALS['pmaThemeImage'] . 'pma_logo.png' . '" '
167 . 'border="0" width="88" height="31" alt="phpMyAdmin" />';
169 ?></a>
170 <h1>
171 <?php
172 echo sprintf(__('Welcome to %s'),
173 '<bdo dir="ltr" xml:lang="en">' . $page_title . '</bdo>');
175 </h1>
176 <?php
178 // Show error message
179 if (! empty($conn_error)) {
180 PMA_Message::rawError($conn_error)->display();
183 // Displays the languages form
184 if (empty($GLOBALS['cfg']['Lang'])) {
185 include_once './libraries/display_select_lang.lib.php';
186 // use fieldset, don't show doc link
187 PMA_select_language(true, false);
191 <br />
192 <!-- Login form -->
193 <form method="post" action="index.php" name="login_form"<?php echo $autocomplete; ?> target="_top" class="login">
194 <fieldset>
195 <legend>
196 <?php
197 echo __('Log in');
198 echo '<a href="./Documentation.html" target="documentation" ' .
199 'title="' . __('phpMyAdmin documentation') . '"> ';
200 if ($GLOBALS['cfg']['ReplaceHelpImg']) {
201 echo PMA_getImage('b_help.png', __('phpMyAdmin documentation'));
202 } else {
203 echo '(*)';
205 echo '</a>';
207 </legend>
209 <?php if ($GLOBALS['cfg']['AllowArbitraryServer']) { ?>
210 <div class="item">
211 <label for="input_servername" title="<?php echo __('You can enter hostname/IP address and port separated by space.'); ?>"><?php echo __('Server:'); ?></label>
212 <input type="text" name="pma_servername" id="input_servername" value="<?php echo htmlspecialchars($default_server); ?>" size="24" class="textfield" title="<?php echo __('You can enter hostname/IP address and port separated by space.'); ?>" />
213 </div>
214 <?php } ?>
215 <div class="item">
216 <label for="input_username"><?php echo __('Username:'); ?></label>
217 <input type="text" name="pma_username" id="input_username" value="<?php echo htmlspecialchars($default_user); ?>" size="24" class="textfield"/>
218 </div>
219 <div class="item">
220 <label for="input_password"><?php echo __('Password:'); ?></label>
221 <input type="password" name="pma_password" id="input_password" value="" size="24" class="textfield" />
222 </div>
223 <?php
224 if (count($GLOBALS['cfg']['Servers']) > 1) {
226 <div class="item">
227 <label for="select_server"><?php echo __('Server Choice'); ?>:</label>
228 <select name="server" id="select_server"
229 <?php
230 if ($GLOBALS['cfg']['AllowArbitraryServer']) {
231 echo ' onchange="document.forms[\'login_form\'].elements[\'pma_servername\'].value = \'\'" ';
233 echo '>';
235 include_once './libraries/select_server.lib.php';
236 PMA_select_server(false, false);
238 echo '</select></div>';
239 } else {
240 echo ' <input type="hidden" name="server" value="' . $GLOBALS['server'] . '" />';
241 } // end if (server choice)
243 </fieldset>
244 <fieldset class="tblFooters">
245 <input value="<?php echo __('Go'); ?>" type="submit" id="input_go" />
246 <?php
247 $_form_params = array();
248 if (! empty($GLOBALS['target'])) {
249 $_form_params['target'] = $GLOBALS['target'];
251 if (! empty($GLOBALS['db'])) {
252 $_form_params['db'] = $GLOBALS['db'];
254 if (! empty($GLOBALS['table'])) {
255 $_form_params['table'] = $GLOBALS['table'];
257 // do not generate a "server" hidden field as we want the "server"
258 // drop-down to have priority
259 echo PMA_generate_common_hidden_inputs($_form_params, '', 0, 'server');
261 </fieldset>
262 </form>
264 <?php
266 // BEGIN Swekey Integration
267 Swekey_login('input_username', 'input_go');
268 // END Swekey Integration
270 // show the "Cookies required" message only if cookies are disabled
271 // (we previously tried to set some cookies)
272 if (empty($_COOKIE)) {
273 trigger_error(__('Cookies must be enabled past this point.'), E_USER_NOTICE);
275 if ($GLOBALS['error_handler']->hasDisplayErrors()) {
276 echo '<div>';
277 $GLOBALS['error_handler']->dispErrors();
278 echo '</div>';
281 </div>
282 <?php
283 if (file_exists(CUSTOM_FOOTER_FILE)) {
284 include CUSTOM_FOOTER_FILE;
287 </body>
288 </html>
289 <?php
290 exit;
291 } // end of the 'PMA_auth()' function
296 * Gets advanced authentication settings
298 * this function DOES NOT check authentication - it just checks/provides
299 * authentication credentials required to connect to the MySQL server
300 * usually with PMA_DBI_connect()
302 * it returns false if something is missing - which usually leads to
303 * PMA_auth() which displays login form
305 * it returns true if all seems ok which usually leads to PMA_auth_set_user()
307 * it directly switches to PMA_auth_fails() if user inactivity timout is reached
309 * @todo AllowArbitraryServer on does not imply that the user wants an
310 * arbitrary server, or? so we should also check if this is filled and
311 * not only if allowed
313 * @return boolean whether we get authentication settings or not
315 * @access public
317 function PMA_auth_check()
319 // Initialization
321 * @global $GLOBALS['pma_auth_server'] the user provided server to connect to
323 $GLOBALS['pma_auth_server'] = '';
325 $GLOBALS['PHP_AUTH_USER'] = $GLOBALS['PHP_AUTH_PW'] = '';
326 $GLOBALS['from_cookie'] = false;
328 // BEGIN Swekey Integration
329 if (! Swekey_auth_check()) {
330 return false;
332 // END Swekey Integration
334 if (defined('PMA_CLEAR_COOKIES')) {
335 foreach ($GLOBALS['cfg']['Servers'] as $key => $val) {
336 $GLOBALS['PMA_Config']->removeCookie('pmaPass-' . $key);
337 $GLOBALS['PMA_Config']->removeCookie('pmaServer-' . $key);
338 $GLOBALS['PMA_Config']->removeCookie('pmaUser-' . $key);
340 return false;
343 if (! empty($_REQUEST['old_usr'])) {
344 // The user wants to be logged out
345 // -> delete his choices that were stored in session
347 // according to the PHP manual we should do this before the destroy:
348 //$_SESSION = array();
349 // but we still need some parts of the session information
350 // in libraries/header_meta_style.inc.php
352 session_destroy();
353 // -> delete password cookie(s)
354 if ($GLOBALS['cfg']['LoginCookieDeleteAll']) {
355 foreach ($GLOBALS['cfg']['Servers'] as $key => $val) {
356 $GLOBALS['PMA_Config']->removeCookie('pmaPass-' . $key);
357 if (isset($_COOKIE['pmaPass-' . $key])) {
358 unset($_COOKIE['pmaPass-' . $key]);
361 } else {
362 $GLOBALS['PMA_Config']->removeCookie('pmaPass-' . $GLOBALS['server']);
363 if (isset($_COOKIE['pmaPass-' . $GLOBALS['server']])) {
364 unset($_COOKIE['pmaPass-' . $GLOBALS['server']]);
369 if (! empty($_REQUEST['pma_username'])) {
370 // The user just logged in
371 $GLOBALS['PHP_AUTH_USER'] = $_REQUEST['pma_username'];
372 $GLOBALS['PHP_AUTH_PW'] = empty($_REQUEST['pma_password']) ? '' : $_REQUEST['pma_password'];
373 if ($GLOBALS['cfg']['AllowArbitraryServer'] && isset($_REQUEST['pma_servername'])) {
374 $GLOBALS['pma_auth_server'] = $_REQUEST['pma_servername'];
376 return true;
379 // At the end, try to set the $GLOBALS['PHP_AUTH_USER']
380 // and $GLOBALS['PHP_AUTH_PW'] variables from cookies
382 // servername
383 if ($GLOBALS['cfg']['AllowArbitraryServer']
384 && ! empty($_COOKIE['pmaServer-' . $GLOBALS['server']])) {
385 $GLOBALS['pma_auth_server'] = $_COOKIE['pmaServer-' . $GLOBALS['server']];
388 // username
389 if (empty($_COOKIE['pmaUser-' . $GLOBALS['server']])) {
390 return false;
393 $GLOBALS['PHP_AUTH_USER'] = PMA_blowfish_decrypt(
394 $_COOKIE['pmaUser-' . $GLOBALS['server']],
395 PMA_get_blowfish_secret());
397 // user was never logged in since session start
398 if (empty($_SESSION['last_access_time'])) {
399 return false;
402 // User inactive too long
403 if ($_SESSION['last_access_time'] < time() - $GLOBALS['cfg']['LoginCookieValidity']) {
404 PMA_cacheUnset('is_create_db_priv', true);
405 PMA_cacheUnset('is_process_priv', true);
406 PMA_cacheUnset('is_reload_priv', true);
407 PMA_cacheUnset('db_to_create', true);
408 PMA_cacheUnset('dbs_where_create_table_allowed', true);
409 $GLOBALS['no_activity'] = true;
410 PMA_auth_fails();
411 exit;
414 // password
415 if (empty($_COOKIE['pmaPass-' . $GLOBALS['server']])) {
416 return false;
419 $GLOBALS['PHP_AUTH_PW'] = PMA_blowfish_decrypt(
420 $_COOKIE['pmaPass-' . $GLOBALS['server']],
421 PMA_get_blowfish_secret());
423 if ($GLOBALS['PHP_AUTH_PW'] == "\xff(blank)") {
424 $GLOBALS['PHP_AUTH_PW'] = '';
427 $GLOBALS['from_cookie'] = true;
429 return true;
430 } // end of the 'PMA_auth_check()' function
434 * Set the user and password after last checkings if required
436 * @return boolean always true
438 * @access public
440 function PMA_auth_set_user()
442 global $cfg;
444 // Ensures valid authentication mode, 'only_db', bookmark database and
445 // table names and relation table name are used
446 if ($cfg['Server']['user'] != $GLOBALS['PHP_AUTH_USER']) {
447 foreach ($cfg['Servers'] as $idx => $current) {
448 if ($current['host'] == $cfg['Server']['host']
449 && $current['port'] == $cfg['Server']['port']
450 && $current['socket'] == $cfg['Server']['socket']
451 && $current['ssl'] == $cfg['Server']['ssl']
452 && $current['connect_type'] == $cfg['Server']['connect_type']
453 && $current['user'] == $GLOBALS['PHP_AUTH_USER']) {
454 $GLOBALS['server'] = $idx;
455 $cfg['Server'] = $current;
456 break;
458 } // end foreach
459 } // end if
461 if ($GLOBALS['cfg']['AllowArbitraryServer']
462 && ! empty($GLOBALS['pma_auth_server'])) {
463 /* Allow to specify 'host port' */
464 $parts = explode(' ', $GLOBALS['pma_auth_server']);
465 if (count($parts) == 2) {
466 $tmp_host = $parts[0];
467 $tmp_port = $parts[1];
468 } else {
469 $tmp_host = $GLOBALS['pma_auth_server'];
470 $tmp_port = '';
472 if ($cfg['Server']['host'] != $GLOBALS['pma_auth_server']) {
473 $cfg['Server']['host'] = $tmp_host;
474 if (!empty($tmp_port)) {
475 $cfg['Server']['port'] = $tmp_port;
478 unset($tmp_host, $tmp_port, $parts);
480 $cfg['Server']['user'] = $GLOBALS['PHP_AUTH_USER'];
481 $cfg['Server']['password'] = $GLOBALS['PHP_AUTH_PW'];
483 $_SESSION['last_access_time'] = time();
485 // Name and password cookies need to be refreshed each time
486 // Duration = one month for username
487 $GLOBALS['PMA_Config']->setCookie('pmaUser-' . $GLOBALS['server'],
488 PMA_blowfish_encrypt($cfg['Server']['user'],
489 PMA_get_blowfish_secret()));
491 // Duration = as configured
492 $GLOBALS['PMA_Config']->setCookie('pmaPass-' . $GLOBALS['server'],
493 PMA_blowfish_encrypt(!empty($cfg['Server']['password']) ? $cfg['Server']['password'] : "\xff(blank)",
494 PMA_get_blowfish_secret()),
495 null,
496 $GLOBALS['cfg']['LoginCookieStore']);
498 // Set server cookies if required (once per session) and, in this case, force
499 // reload to ensure the client accepts cookies
500 if (! $GLOBALS['from_cookie']) {
501 if ($GLOBALS['cfg']['AllowArbitraryServer']) {
502 if (! empty($GLOBALS['pma_auth_server'])) {
503 // Duration = one month for servername
504 $GLOBALS['PMA_Config']->setCookie('pmaServer-' . $GLOBALS['server'], $cfg['Server']['host']);
505 } else {
506 // Delete servername cookie
507 $GLOBALS['PMA_Config']->removeCookie('pmaServer-' . $GLOBALS['server']);
511 // URL where to go:
512 $redirect_url = $cfg['PmaAbsoluteUri'] . 'index.php';
514 // any parameters to pass?
515 $url_params = array();
516 if (strlen($GLOBALS['db'])) {
517 $url_params['db'] = $GLOBALS['db'];
519 if (strlen($GLOBALS['table'])) {
520 $url_params['table'] = $GLOBALS['table'];
522 // any target to pass?
523 if (! empty($GLOBALS['target']) && $GLOBALS['target'] != 'index.php') {
524 $url_params['target'] = $GLOBALS['target'];
528 * whether we come from a fresh cookie login
530 define('PMA_COMING_FROM_COOKIE_LOGIN', true);
533 * Clear user cache.
535 PMA_clearUserCache();
537 PMA_sendHeaderLocation($redirect_url . PMA_generate_common_url($url_params, '&'));
538 exit();
539 } // end if
541 return true;
542 } // end of the 'PMA_auth_set_user()' function
546 * User is not allowed to login to MySQL -> authentication failed
548 * prepares error message and switches to PMA_auth() which display the error
549 * and the login form
551 * this function MUST exit/quit the application,
552 * currently doen by call to PMA_auth()
554 * @access public
556 function PMA_auth_fails()
558 global $conn_error;
560 // Deletes password cookie and displays the login form
561 $GLOBALS['PMA_Config']->removeCookie('pmaPass-' . $GLOBALS['server']);
563 if (! empty($GLOBALS['login_without_password_is_forbidden'])) {
564 $conn_error = __('Login without a password is forbidden by configuration (see AllowNoPassword)');
565 } elseif (! empty($GLOBALS['allowDeny_forbidden'])) {
566 $conn_error = __('Access denied');
567 } elseif (! empty($GLOBALS['no_activity'])) {
568 $conn_error = sprintf(__('No activity within %s seconds; please log in again'), $GLOBALS['cfg']['LoginCookieValidity']);
569 // Remember where we got timeout to return on same place
570 if (PMA_getenv('SCRIPT_NAME')) {
571 $GLOBALS['target'] = basename(PMA_getenv('SCRIPT_NAME'));
572 // avoid "missing parameter: field" on re-entry
573 if ('tbl_alter.php' == $GLOBALS['target']) {
574 $GLOBALS['target'] = 'tbl_structure.php';
577 } elseif (PMA_DBI_getError()) {
578 $conn_error = '#' . $GLOBALS['errno'] . ' ' . __('Cannot log in to the MySQL server');
579 } else {
580 $conn_error = __('Cannot log in to the MySQL server');
583 // needed for PHP-CGI (not need for FastCGI or mod-php)
584 header('Cache-Control: no-store, no-cache, must-revalidate');
585 header('Pragma: no-cache');
587 PMA_auth();
588 } // end of the 'PMA_auth_fails()' function