AuthenticationCookie.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * Cookie Authentication plugin for phpMyAdmin
  5. *
  6. * @package PhpMyAdmin-Authentication
  7. * @subpackage Cookie
  8. */
  9. namespace PhpMyAdmin\Plugins\Auth;
  10. use PhpMyAdmin\Config;
  11. use PhpMyAdmin\Core;
  12. use PhpMyAdmin\LanguageManager;
  13. use PhpMyAdmin\Message;
  14. use PhpMyAdmin\Plugins\AuthenticationPlugin;
  15. use PhpMyAdmin\Response;
  16. use PhpMyAdmin\Server\Select;
  17. use PhpMyAdmin\Session;
  18. use PhpMyAdmin\Template;
  19. use PhpMyAdmin\Util;
  20. use PhpMyAdmin\Url;
  21. use phpseclib\Crypt;
  22. use ReCaptcha;
  23. require_once './libraries/hash.lib.php';
  24. /**
  25. * Remember where to redirect the user
  26. * in case of an expired session.
  27. */
  28. if (! empty($_REQUEST['target'])) {
  29. $GLOBALS['target'] = $_REQUEST['target'];
  30. } elseif (Core::getenv('SCRIPT_NAME')) {
  31. $GLOBALS['target'] = basename(Core::getenv('SCRIPT_NAME'));
  32. }
  33. /**
  34. * Handles the cookie authentication method
  35. *
  36. * @package PhpMyAdmin-Authentication
  37. */
  38. class AuthenticationCookie extends AuthenticationPlugin
  39. {
  40. /**
  41. * IV for encryption
  42. */
  43. private $_cookie_iv = null;
  44. /**
  45. * Whether to use OpenSSL directly
  46. */
  47. private $_use_openssl;
  48. /**
  49. * Constructor
  50. */
  51. public function __construct()
  52. {
  53. $this->_use_openssl = ! class_exists('phpseclib\Crypt\Random');
  54. }
  55. /**
  56. * Forces (not)using of openSSL
  57. *
  58. * @param boolean $use The flag
  59. *
  60. * @return void
  61. */
  62. public function setUseOpenSSL($use)
  63. {
  64. $this->_use_openssl = $use;
  65. }
  66. /**
  67. * Displays authentication form
  68. *
  69. * this function MUST exit/quit the application
  70. *
  71. * @global string $conn_error the last connection error
  72. *
  73. * @return boolean|void
  74. */
  75. public function showLoginForm()
  76. {
  77. global $conn_error;
  78. $response = Response::getInstance();
  79. if ($response->loginPage()) {
  80. if (defined('TESTSUITE')) {
  81. return true;
  82. } else {
  83. exit;
  84. }
  85. }
  86. // No recall if blowfish secret is not configured as it would produce
  87. // garbage
  88. if ($GLOBALS['cfg']['LoginCookieRecall']
  89. && ! empty($GLOBALS['cfg']['blowfish_secret'])
  90. ) {
  91. $default_user = $this->user;
  92. $default_server = $GLOBALS['pma_auth_server'];
  93. $autocomplete = '';
  94. } else {
  95. $default_user = '';
  96. $default_server = '';
  97. // skip the IE autocomplete feature.
  98. $autocomplete = ' autocomplete="off"';
  99. }
  100. echo Template::get('login/header')->render(['theme' => $GLOBALS['PMA_Theme']]);
  101. if ($GLOBALS['cfg']['DBG']['demo']) {
  102. echo '<fieldset>';
  103. echo '<legend>' , __('phpMyAdmin Demo Server') , '</legend>';
  104. printf(
  105. __(
  106. 'You are using the demo server. You can do anything here, but '
  107. . 'please do not change root, debian-sys-maint and pma users. '
  108. . 'More information is available at %s.'
  109. ),
  110. '<a href="url.php?url=https://demo.phpmyadmin.net/" target="_blank" rel="noopener noreferrer">demo.phpmyadmin.net</a>'
  111. );
  112. echo '</fieldset>';
  113. }
  114. // Show error message
  115. if (! empty($conn_error)) {
  116. Message::rawError($conn_error)->display();
  117. } elseif (isset($_GET['session_expired'])
  118. && intval($_GET['session_expired']) == 1
  119. ) {
  120. Message::rawError(
  121. __('Your session has expired. Please log in again.')
  122. )->display();
  123. }
  124. // Displays the languages form
  125. $language_manager = LanguageManager::getInstance();
  126. if (empty($GLOBALS['cfg']['Lang']) && $language_manager->hasChoice()) {
  127. echo "<div class='hide js-show'>";
  128. // use fieldset, don't show doc link
  129. echo $language_manager->getSelectorDisplay(true, false);
  130. echo '</div>';
  131. }
  132. echo '
  133. <br />
  134. <!-- Login form -->
  135. <form method="post" id="login_form" action="index.php" name="login_form"' , $autocomplete ,
  136. ' class="disableAjax login hide js-show">
  137. <fieldset>
  138. <legend>';
  139. echo '<input type="hidden" name="set_session" value="', htmlspecialchars(session_id()), '" />';
  140. echo __('Log in');
  141. echo Util::showDocu('index');
  142. echo '</legend>';
  143. if ($GLOBALS['cfg']['AllowArbitraryServer']) {
  144. echo '
  145. <div class="item">
  146. <label for="input_servername" title="';
  147. echo __(
  148. 'You can enter hostname/IP address and port separated by space.'
  149. );
  150. echo '">';
  151. echo __('Server:');
  152. echo '</label>
  153. <input type="text" name="pma_servername" id="input_servername"';
  154. echo ' value="';
  155. echo htmlspecialchars($default_server);
  156. echo '" size="24" class="textfield" title="';
  157. echo __(
  158. 'You can enter hostname/IP address and port separated by space.'
  159. ); echo '" />
  160. </div>';
  161. }
  162. echo '<div class="item">
  163. <label for="input_username">' , __('Username:') , '</label>
  164. <input type="text" name="pma_username" id="input_username" '
  165. , 'value="' , htmlspecialchars($default_user) , '" size="24"'
  166. , ' class="textfield"/>
  167. </div>
  168. <div class="item">
  169. <label for="input_password">' , __('Password:') , '</label>
  170. <input type="password" name="pma_password" id="input_password"'
  171. , ' value="" size="24" class="textfield" />
  172. </div>';
  173. if (count($GLOBALS['cfg']['Servers']) > 1) {
  174. echo '<div class="item">
  175. <label for="select_server">' . __('Server Choice:') . '</label>
  176. <select name="server" id="select_server"';
  177. if ($GLOBALS['cfg']['AllowArbitraryServer']) {
  178. echo ' onchange="document.forms[\'login_form\'].'
  179. , 'elements[\'pma_servername\'].value = \'\'" ';
  180. }
  181. echo '>';
  182. echo Select::render(false, false);
  183. echo '</select></div>';
  184. } else {
  185. echo ' <input type="hidden" name="server" value="'
  186. , $GLOBALS['server'] , '" />';
  187. } // end if (server choice)
  188. echo '</fieldset><fieldset class="tblFooters">';
  189. // binds input field with invisible reCaptcha if enabled
  190. if (empty($GLOBALS['cfg']['CaptchaLoginPrivateKey'])
  191. && empty($GLOBALS['cfg']['CaptchaLoginPublicKey'])
  192. ) {
  193. echo '<input value="' , __('Go') , '" type="submit" id="input_go" />';
  194. }
  195. else {
  196. echo '<script src="https://www.google.com/recaptcha/api.js?hl='
  197. , $GLOBALS['lang'] , '" async defer></script>';
  198. echo '<input class="g-recaptcha" data-sitekey="'
  199. , htmlspecialchars($GLOBALS['cfg']['CaptchaLoginPublicKey']),'"'
  200. .' data-callback="recaptchaCallback" value="' , __('Go') , '" type="submit" id="input_go" />';
  201. }
  202. $_form_params = array();
  203. if (! empty($GLOBALS['target'])) {
  204. $_form_params['target'] = $GLOBALS['target'];
  205. }
  206. if (strlen($GLOBALS['db'])) {
  207. $_form_params['db'] = $GLOBALS['db'];
  208. }
  209. if (strlen($GLOBALS['table'])) {
  210. $_form_params['table'] = $GLOBALS['table'];
  211. }
  212. // do not generate a "server" hidden field as we want the "server"
  213. // drop-down to have priority
  214. echo Url::getHiddenInputs($_form_params, '', 0, 'server');
  215. echo '</fieldset>
  216. </form>';
  217. if ($GLOBALS['error_handler']->hasDisplayErrors()) {
  218. echo '<div id="pma_errors">';
  219. $GLOBALS['error_handler']->dispErrors();
  220. echo '</div>';
  221. }
  222. echo Template::get('login/footer')->render();
  223. echo Config::renderFooter();
  224. if (! defined('TESTSUITE')) {
  225. exit;
  226. } else {
  227. return true;
  228. }
  229. }
  230. /**
  231. * Gets authentication credentials
  232. *
  233. * this function DOES NOT check authentication - it just checks/provides
  234. * authentication credentials required to connect to the MySQL server
  235. * usually with $GLOBALS['dbi']->connect()
  236. *
  237. * it returns false if something is missing - which usually leads to
  238. * showLoginForm() which displays login form
  239. *
  240. * it returns true if all seems ok which usually leads to auth_set_user()
  241. *
  242. * it directly switches to showFailure() if user inactivity timeout is reached
  243. *
  244. * @return boolean whether we get authentication settings or not
  245. */
  246. public function readCredentials()
  247. {
  248. global $conn_error;
  249. // Initialization
  250. /**
  251. * @global $GLOBALS['pma_auth_server'] the user provided server to
  252. * connect to
  253. */
  254. $GLOBALS['pma_auth_server'] = '';
  255. $this->user = $this->password = '';
  256. $GLOBALS['from_cookie'] = false;
  257. if (isset($_REQUEST['pma_username']) && strlen($_REQUEST['pma_username']) > 0) {
  258. // Verify Captcha if it is required.
  259. if (! empty($GLOBALS['cfg']['CaptchaLoginPrivateKey'])
  260. && ! empty($GLOBALS['cfg']['CaptchaLoginPublicKey'])
  261. ) {
  262. if (! empty($_POST["g-recaptcha-response"])) {
  263. if (function_exists('curl_init')) {
  264. $reCaptcha = new ReCaptcha\ReCaptcha(
  265. $GLOBALS['cfg']['CaptchaLoginPrivateKey'],
  266. new ReCaptcha\RequestMethod\CurlPost()
  267. );
  268. } elseif (ini_get('allow_url_fopen')) {
  269. $reCaptcha = new ReCaptcha\ReCaptcha(
  270. $GLOBALS['cfg']['CaptchaLoginPrivateKey'],
  271. new ReCaptcha\RequestMethod\Post()
  272. );
  273. } else {
  274. $reCaptcha = new ReCaptcha\ReCaptcha(
  275. $GLOBALS['cfg']['CaptchaLoginPrivateKey'],
  276. new ReCaptcha\RequestMethod\SocketPost()
  277. );
  278. }
  279. // verify captcha status.
  280. $resp = $reCaptcha->verify(
  281. $_POST["g-recaptcha-response"],
  282. Core::getIp()
  283. );
  284. // Check if the captcha entered is valid, if not stop the login.
  285. if ($resp == null || ! $resp->isSuccess()) {
  286. $codes = $resp->getErrorCodes();
  287. if (in_array('invalid-json', $codes)) {
  288. $conn_error = __('Failed to connect to the reCAPTCHA service!');
  289. } else {
  290. $conn_error = __('Entered captcha is wrong, try again!');
  291. }
  292. return false;
  293. }
  294. } else {
  295. $conn_error = __('Missing reCAPTCHA verification, maybe it has been blocked by adblock?');
  296. return false;
  297. }
  298. }
  299. // The user just logged in
  300. $this->user = Core::sanitizeMySQLUser($_REQUEST['pma_username']);
  301. $this->password = isset($_REQUEST['pma_password']) ? $_REQUEST['pma_password'] : '';
  302. if ($GLOBALS['cfg']['AllowArbitraryServer']
  303. && isset($_REQUEST['pma_servername'])
  304. ) {
  305. if ($GLOBALS['cfg']['ArbitraryServerRegexp']) {
  306. $parts = explode(' ', $_REQUEST['pma_servername']);
  307. if (count($parts) == 2) {
  308. $tmp_host = $parts[0];
  309. } else {
  310. $tmp_host = $_REQUEST['pma_servername'];
  311. }
  312. $match = preg_match(
  313. $GLOBALS['cfg']['ArbitraryServerRegexp'], $tmp_host
  314. );
  315. if (! $match) {
  316. $conn_error = __(
  317. 'You are not allowed to log in to this MySQL server!'
  318. );
  319. return false;
  320. }
  321. }
  322. $GLOBALS['pma_auth_server'] = Core::sanitizeMySQLHost($_REQUEST['pma_servername']);
  323. }
  324. /* Secure current session on login to avoid session fixation */
  325. Session::secure();
  326. return true;
  327. }
  328. // At the end, try to set the $this->user
  329. // and $this->password variables from cookies
  330. // check cookies
  331. if (empty($_COOKIE['pmaUser-' . $GLOBALS['server']])) {
  332. return false;
  333. }
  334. $value = $this->cookieDecrypt(
  335. $_COOKIE['pmaUser-' . $GLOBALS['server']],
  336. $this->_getEncryptionSecret()
  337. );
  338. if ($value === false) {
  339. return false;
  340. }
  341. $this->user = $value;
  342. // user was never logged in since session start
  343. if (empty($_SESSION['browser_access_time'])) {
  344. return false;
  345. }
  346. // User inactive too long
  347. $last_access_time = time() - $GLOBALS['cfg']['LoginCookieValidity'];
  348. foreach ($_SESSION['browser_access_time'] as $key => $value) {
  349. if ($value < $last_access_time) {
  350. unset($_SESSION['browser_access_time'][$key]);
  351. }
  352. }
  353. // All sessions expired
  354. if (empty($_SESSION['browser_access_time'])) {
  355. Util::cacheUnset('is_create_db_priv');
  356. Util::cacheUnset('is_reload_priv');
  357. Util::cacheUnset('db_to_create');
  358. Util::cacheUnset('dbs_where_create_table_allowed');
  359. Util::cacheUnset('dbs_to_test');
  360. Util::cacheUnset('db_priv');
  361. Util::cacheUnset('col_priv');
  362. Util::cacheUnset('table_priv');
  363. Util::cacheUnset('proc_priv');
  364. $this->showFailure('no-activity');
  365. if (! defined('TESTSUITE')) {
  366. exit;
  367. } else {
  368. return false;
  369. }
  370. }
  371. // check password cookie
  372. if (empty($_COOKIE['pmaAuth-' . $GLOBALS['server']])) {
  373. return false;
  374. }
  375. $value = $this->cookieDecrypt(
  376. $_COOKIE['pmaAuth-' . $GLOBALS['server']],
  377. $this->_getSessionEncryptionSecret()
  378. );
  379. if ($value === false) {
  380. return false;
  381. }
  382. $auth_data = json_decode($value, true);
  383. if (! is_array($auth_data) || ! isset($auth_data['password'])) {
  384. return false;
  385. }
  386. $this->password = $auth_data['password'];
  387. if ($GLOBALS['cfg']['AllowArbitraryServer'] && ! empty($auth_data['server'])) {
  388. $GLOBALS['pma_auth_server'] = $auth_data['server'];
  389. }
  390. $GLOBALS['from_cookie'] = true;
  391. return true;
  392. }
  393. /**
  394. * Set the user and password after last checkings if required
  395. *
  396. * @return boolean always true
  397. */
  398. public function storeCredentials()
  399. {
  400. global $cfg;
  401. if ($GLOBALS['cfg']['AllowArbitraryServer']
  402. && ! empty($GLOBALS['pma_auth_server'])
  403. ) {
  404. /* Allow to specify 'host port' */
  405. $parts = explode(' ', $GLOBALS['pma_auth_server']);
  406. if (count($parts) == 2) {
  407. $tmp_host = $parts[0];
  408. $tmp_port = $parts[1];
  409. } else {
  410. $tmp_host = $GLOBALS['pma_auth_server'];
  411. $tmp_port = '';
  412. }
  413. if ($cfg['Server']['host'] != $GLOBALS['pma_auth_server']) {
  414. $cfg['Server']['host'] = $tmp_host;
  415. if (! empty($tmp_port)) {
  416. $cfg['Server']['port'] = $tmp_port;
  417. }
  418. }
  419. unset($tmp_host, $tmp_port, $parts);
  420. }
  421. return parent::storeCredentials();
  422. }
  423. /**
  424. * Stores user credentials after successful login.
  425. *
  426. * @return void|bool
  427. */
  428. public function rememberCredentials()
  429. {
  430. // Name and password cookies need to be refreshed each time
  431. // Duration = one month for username
  432. $this->storeUsernameCookie($this->user);
  433. // Duration = as configured
  434. // Do not store password cookie on password change as we will
  435. // set the cookie again after password has been changed
  436. if (! isset($_POST['change_pw'])) {
  437. $this->storePasswordCookie($this->password);
  438. }
  439. // Set server cookies if required (once per session) and, in this case,
  440. // force reload to ensure the client accepts cookies
  441. if (! $GLOBALS['from_cookie']) {
  442. // URL where to go:
  443. $redirect_url = './index.php';
  444. // any parameters to pass?
  445. $url_params = array();
  446. if (strlen($GLOBALS['db']) > 0) {
  447. $url_params['db'] = $GLOBALS['db'];
  448. }
  449. if (strlen($GLOBALS['table']) > 0) {
  450. $url_params['table'] = $GLOBALS['table'];
  451. }
  452. // any target to pass?
  453. if (! empty($GLOBALS['target'])
  454. && $GLOBALS['target'] != 'index.php'
  455. ) {
  456. $url_params['target'] = $GLOBALS['target'];
  457. }
  458. /**
  459. * Clear user cache.
  460. */
  461. Util::clearUserCache();
  462. Response::getInstance()
  463. ->disable();
  464. Core::sendHeaderLocation(
  465. $redirect_url . Url::getCommonRaw($url_params),
  466. true
  467. );
  468. if (! defined('TESTSUITE')) {
  469. exit;
  470. } else {
  471. return false;
  472. }
  473. } // end if
  474. return true;
  475. }
  476. /**
  477. * Stores username in a cookie.
  478. *
  479. * @param string $username User name
  480. *
  481. * @return void
  482. */
  483. public function storeUsernameCookie($username)
  484. {
  485. // Name and password cookies need to be refreshed each time
  486. // Duration = one month for username
  487. $GLOBALS['PMA_Config']->setCookie(
  488. 'pmaUser-' . $GLOBALS['server'],
  489. $this->cookieEncrypt(
  490. $username,
  491. $this->_getEncryptionSecret()
  492. )
  493. );
  494. }
  495. /**
  496. * Stores password in a cookie.
  497. *
  498. * @param string $password Password
  499. *
  500. * @return void
  501. */
  502. public function storePasswordCookie($password)
  503. {
  504. $payload = array('password' => $password);
  505. if ($GLOBALS['cfg']['AllowArbitraryServer'] && ! empty($GLOBALS['pma_auth_server'])) {
  506. $payload['server'] = $GLOBALS['pma_auth_server'];
  507. }
  508. // Duration = as configured
  509. $GLOBALS['PMA_Config']->setCookie(
  510. 'pmaAuth-' . $GLOBALS['server'],
  511. $this->cookieEncrypt(
  512. json_encode($payload),
  513. $this->_getSessionEncryptionSecret()
  514. ),
  515. null,
  516. $GLOBALS['cfg']['LoginCookieStore']
  517. );
  518. }
  519. /**
  520. * User is not allowed to login to MySQL -> authentication failed
  521. *
  522. * prepares error message and switches to showLoginForm() which display the error
  523. * and the login form
  524. *
  525. * this function MUST exit/quit the application,
  526. * currently done by call to showLoginForm()
  527. *
  528. * @param string $failure String describing why authentication has failed
  529. *
  530. * @return void
  531. */
  532. public function showFailure($failure)
  533. {
  534. global $conn_error;
  535. parent::showFailure($failure);
  536. // Deletes password cookie and displays the login form
  537. $GLOBALS['PMA_Config']->removeCookie('pmaAuth-' . $GLOBALS['server']);
  538. $conn_error = $this->getErrorMessage($failure);
  539. $response = Response::getInstance();
  540. // needed for PHP-CGI (not need for FastCGI or mod-php)
  541. $response->header('Cache-Control: no-store, no-cache, must-revalidate');
  542. $response->header('Pragma: no-cache');
  543. $this->showLoginForm();
  544. }
  545. /**
  546. * Returns blowfish secret or generates one if needed.
  547. *
  548. * @return string
  549. */
  550. private function _getEncryptionSecret()
  551. {
  552. if (empty($GLOBALS['cfg']['blowfish_secret'])) {
  553. return $this->_getSessionEncryptionSecret();
  554. }
  555. return $GLOBALS['cfg']['blowfish_secret'];
  556. }
  557. /**
  558. * Returns blowfish secret or generates one if needed.
  559. *
  560. * @return string
  561. */
  562. private function _getSessionEncryptionSecret()
  563. {
  564. if (empty($_SESSION['encryption_key'])) {
  565. if ($this->_use_openssl) {
  566. $_SESSION['encryption_key'] = openssl_random_pseudo_bytes(32);
  567. } else {
  568. $_SESSION['encryption_key'] = Crypt\Random::string(32);
  569. }
  570. }
  571. return $_SESSION['encryption_key'];
  572. }
  573. /**
  574. * Concatenates secret in order to make it 16 bytes log
  575. *
  576. * This doesn't add any security, just ensures the secret
  577. * is long enough by copying it.
  578. *
  579. * @param string $secret Original secret
  580. *
  581. * @return string
  582. */
  583. public function enlargeSecret($secret)
  584. {
  585. while (strlen($secret) < 16) {
  586. $secret .= $secret;
  587. }
  588. return substr($secret, 0, 16);
  589. }
  590. /**
  591. * Derives MAC secret from encryption secret.
  592. *
  593. * @param string $secret the secret
  594. *
  595. * @return string the MAC secret
  596. */
  597. public function getMACSecret($secret)
  598. {
  599. // Grab first part, up to 16 chars
  600. // The MAC and AES secrets can overlap if original secret is short
  601. $length = strlen($secret);
  602. if ($length > 16) {
  603. return substr($secret, 0, 16);
  604. }
  605. return $this->enlargeSecret(
  606. $length == 1 ? $secret : substr($secret, 0, -1)
  607. );
  608. }
  609. /**
  610. * Derives AES secret from encryption secret.
  611. *
  612. * @param string $secret the secret
  613. *
  614. * @return string the AES secret
  615. */
  616. public function getAESSecret($secret)
  617. {
  618. // Grab second part, up to 16 chars
  619. // The MAC and AES secrets can overlap if original secret is short
  620. $length = strlen($secret);
  621. if ($length > 16) {
  622. return substr($secret, -16);
  623. }
  624. return $this->enlargeSecret(
  625. $length == 1 ? $secret : substr($secret, 1)
  626. );
  627. }
  628. /**
  629. * Cleans any SSL errors
  630. *
  631. * This can happen from corrupted cookies, by invalid encryption
  632. * parameters used in older phpMyAdmin versions or by wrong openSSL
  633. * configuration.
  634. *
  635. * In neither case the error is useful to user, but we need to clear
  636. * the error buffer as otherwise the errors would pop up later, for
  637. * example during MySQL SSL setup.
  638. *
  639. * @return void
  640. */
  641. public function cleanSSLErrors()
  642. {
  643. if (function_exists('openssl_error_string')) {
  644. while (($ssl_err = openssl_error_string()) !== false) {
  645. }
  646. }
  647. }
  648. /**
  649. * Encryption using openssl's AES or phpseclib's AES
  650. * (phpseclib uses mcrypt when it is available)
  651. *
  652. * @param string $data original data
  653. * @param string $secret the secret
  654. *
  655. * @return string the encrypted result
  656. */
  657. public function cookieEncrypt($data, $secret)
  658. {
  659. $mac_secret = $this->getMACSecret($secret);
  660. $aes_secret = $this->getAESSecret($secret);
  661. $iv = $this->createIV();
  662. if ($this->_use_openssl) {
  663. $result = openssl_encrypt(
  664. $data,
  665. 'AES-128-CBC',
  666. $aes_secret,
  667. 0,
  668. $iv
  669. );
  670. } else {
  671. $cipher = new Crypt\AES(Crypt\Base::MODE_CBC);
  672. $cipher->setIV($iv);
  673. $cipher->setKey($aes_secret);
  674. $result = base64_encode($cipher->encrypt($data));
  675. }
  676. $this->cleanSSLErrors();
  677. $iv = base64_encode($iv);
  678. return json_encode(
  679. array(
  680. 'iv' => $iv,
  681. 'mac' => hash_hmac('sha1', $iv . $result, $mac_secret),
  682. 'payload' => $result,
  683. )
  684. );
  685. }
  686. /**
  687. * Decryption using openssl's AES or phpseclib's AES
  688. * (phpseclib uses mcrypt when it is available)
  689. *
  690. * @param string $encdata encrypted data
  691. * @param string $secret the secret
  692. *
  693. * @return string|false original data, false on error
  694. */
  695. public function cookieDecrypt($encdata, $secret)
  696. {
  697. $data = json_decode($encdata, true);
  698. if (! is_array($data) || ! isset($data['mac']) || ! isset($data['iv']) || ! isset($data['payload'])
  699. || ! is_string($data['mac']) || ! is_string($data['iv']) || ! is_string($data['payload'])
  700. ) {
  701. return false;
  702. }
  703. $mac_secret = $this->getMACSecret($secret);
  704. $aes_secret = $this->getAESSecret($secret);
  705. $newmac = hash_hmac('sha1', $data['iv'] . $data['payload'], $mac_secret);
  706. if (! hash_equals($data['mac'], $newmac)) {
  707. return false;
  708. }
  709. if ($this->_use_openssl) {
  710. $result = openssl_decrypt(
  711. $data['payload'],
  712. 'AES-128-CBC',
  713. $aes_secret,
  714. 0,
  715. base64_decode($data['iv'])
  716. );
  717. } else {
  718. $cipher = new Crypt\AES(Crypt\Base::MODE_CBC);
  719. $cipher->setIV(base64_decode($data['iv']));
  720. $cipher->setKey($aes_secret);
  721. $result = $cipher->decrypt(base64_decode($data['payload']));
  722. }
  723. $this->cleanSSLErrors();
  724. return $result;
  725. }
  726. /**
  727. * Returns size of IV for encryption.
  728. *
  729. * @return int
  730. */
  731. public function getIVSize()
  732. {
  733. if ($this->_use_openssl) {
  734. return openssl_cipher_iv_length('AES-128-CBC');
  735. }
  736. $cipher = new Crypt\AES(Crypt\Base::MODE_CBC);
  737. return $cipher->block_size;
  738. }
  739. /**
  740. * Initialization
  741. * Store the initialization vector because it will be needed for
  742. * further decryption. I don't think necessary to have one iv
  743. * per server so I don't put the server number in the cookie name.
  744. *
  745. * @return string
  746. */
  747. public function createIV()
  748. {
  749. /* Testsuite shortcut only to allow predictable IV */
  750. if (! is_null($this->_cookie_iv)) {
  751. return $this->_cookie_iv;
  752. }
  753. if ($this->_use_openssl) {
  754. return openssl_random_pseudo_bytes(
  755. $this->getIVSize()
  756. );
  757. }
  758. return Crypt\Random::string(
  759. $this->getIVSize()
  760. );
  761. }
  762. /**
  763. * Sets encryption IV to use
  764. *
  765. * This is for testing only!
  766. *
  767. * @param string $vector The IV
  768. *
  769. * @return void
  770. */
  771. public function setIV($vector)
  772. {
  773. $this->_cookie_iv = $vector;
  774. }
  775. /**
  776. * Callback when user changes password.
  777. *
  778. * @param string $password New password to set
  779. *
  780. * @return void
  781. */
  782. public function handlePasswordChange($password)
  783. {
  784. $this->storePasswordCookie($password);
  785. }
  786. /**
  787. * Perform logout
  788. *
  789. * @return void
  790. */
  791. public function logOut()
  792. {
  793. // -> delete password cookie(s)
  794. if ($GLOBALS['cfg']['LoginCookieDeleteAll']) {
  795. foreach ($GLOBALS['cfg']['Servers'] as $key => $val) {
  796. $GLOBALS['PMA_Config']->removeCookie('pmaAuth-' . $key);
  797. if (isset($_COOKIE['pmaAuth-' . $key])) {
  798. unset($_COOKIE['pmaAuth-' . $key]);
  799. }
  800. }
  801. } else {
  802. $GLOBALS['PMA_Config']->removeCookie(
  803. 'pmaAuth-' . $GLOBALS['server']
  804. );
  805. if (isset($_COOKIE['pmaAuth-' . $GLOBALS['server']])) {
  806. unset($_COOKIE['pmaAuth-' . $GLOBALS['server']]);
  807. }
  808. }
  809. parent::logOut();
  810. }
  811. }