AuthenticationCookie.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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($_POST['pma_username']) && strlen($_POST['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($_POST['pma_username']);
  301. $this->password = isset($_POST['pma_password']) ? $_POST['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. $serverCookie = $GLOBALS['PMA_Config']->getCookie('pmaUser-' . $GLOBALS['server']);
  332. if (empty($serverCookie)) {
  333. return false;
  334. }
  335. $value = $this->cookieDecrypt(
  336. $serverCookie,
  337. $this->_getEncryptionSecret()
  338. );
  339. if ($value === false) {
  340. return false;
  341. }
  342. $this->user = $value;
  343. // user was never logged in since session start
  344. if (empty($_SESSION['browser_access_time'])) {
  345. return false;
  346. }
  347. // User inactive too long
  348. $last_access_time = time() - $GLOBALS['cfg']['LoginCookieValidity'];
  349. foreach ($_SESSION['browser_access_time'] as $key => $value) {
  350. if ($value < $last_access_time) {
  351. unset($_SESSION['browser_access_time'][$key]);
  352. }
  353. }
  354. // All sessions expired
  355. if (empty($_SESSION['browser_access_time'])) {
  356. Util::cacheUnset('is_create_db_priv');
  357. Util::cacheUnset('is_reload_priv');
  358. Util::cacheUnset('db_to_create');
  359. Util::cacheUnset('dbs_where_create_table_allowed');
  360. Util::cacheUnset('dbs_to_test');
  361. Util::cacheUnset('db_priv');
  362. Util::cacheUnset('col_priv');
  363. Util::cacheUnset('table_priv');
  364. Util::cacheUnset('proc_priv');
  365. $this->showFailure('no-activity');
  366. if (! defined('TESTSUITE')) {
  367. exit;
  368. } else {
  369. return false;
  370. }
  371. }
  372. // check password cookie
  373. $serverCookie = $GLOBALS['PMA_Config']->getCookie('pmaAuth-' . $GLOBALS['server']);
  374. if (empty($serverCookie)) {
  375. return false;
  376. }
  377. $value = $this->cookieDecrypt(
  378. $serverCookie,
  379. $this->_getSessionEncryptionSecret()
  380. );
  381. if ($value === false) {
  382. return false;
  383. }
  384. $auth_data = json_decode($value, true);
  385. if (! is_array($auth_data) || ! isset($auth_data['password'])) {
  386. return false;
  387. }
  388. $this->password = $auth_data['password'];
  389. if ($GLOBALS['cfg']['AllowArbitraryServer'] && ! empty($auth_data['server'])) {
  390. $GLOBALS['pma_auth_server'] = $auth_data['server'];
  391. }
  392. $GLOBALS['from_cookie'] = true;
  393. return true;
  394. }
  395. /**
  396. * Set the user and password after last checkings if required
  397. *
  398. * @return boolean always true
  399. */
  400. public function storeCredentials()
  401. {
  402. global $cfg;
  403. if ($GLOBALS['cfg']['AllowArbitraryServer']
  404. && ! empty($GLOBALS['pma_auth_server'])
  405. ) {
  406. /* Allow to specify 'host port' */
  407. $parts = explode(' ', $GLOBALS['pma_auth_server']);
  408. if (count($parts) == 2) {
  409. $tmp_host = $parts[0];
  410. $tmp_port = $parts[1];
  411. } else {
  412. $tmp_host = $GLOBALS['pma_auth_server'];
  413. $tmp_port = '';
  414. }
  415. if ($cfg['Server']['host'] != $GLOBALS['pma_auth_server']) {
  416. $cfg['Server']['host'] = $tmp_host;
  417. if (! empty($tmp_port)) {
  418. $cfg['Server']['port'] = $tmp_port;
  419. }
  420. }
  421. unset($tmp_host, $tmp_port, $parts);
  422. }
  423. return parent::storeCredentials();
  424. }
  425. /**
  426. * Stores user credentials after successful login.
  427. *
  428. * @return void|bool
  429. */
  430. public function rememberCredentials()
  431. {
  432. // Name and password cookies need to be refreshed each time
  433. // Duration = one month for username
  434. $this->storeUsernameCookie($this->user);
  435. // Duration = as configured
  436. // Do not store password cookie on password change as we will
  437. // set the cookie again after password has been changed
  438. if (! isset($_POST['change_pw'])) {
  439. $this->storePasswordCookie($this->password);
  440. }
  441. // Set server cookies if required (once per session) and, in this case,
  442. // force reload to ensure the client accepts cookies
  443. if (! $GLOBALS['from_cookie']) {
  444. // URL where to go:
  445. $redirect_url = './index.php';
  446. // any parameters to pass?
  447. $url_params = array();
  448. if (strlen($GLOBALS['db']) > 0) {
  449. $url_params['db'] = $GLOBALS['db'];
  450. }
  451. if (strlen($GLOBALS['table']) > 0) {
  452. $url_params['table'] = $GLOBALS['table'];
  453. }
  454. // any target to pass?
  455. if (! empty($GLOBALS['target'])
  456. && $GLOBALS['target'] != 'index.php'
  457. ) {
  458. $url_params['target'] = $GLOBALS['target'];
  459. }
  460. /**
  461. * Clear user cache.
  462. */
  463. Util::clearUserCache();
  464. Response::getInstance()
  465. ->disable();
  466. Core::sendHeaderLocation(
  467. $redirect_url . Url::getCommonRaw($url_params),
  468. true
  469. );
  470. if (! defined('TESTSUITE')) {
  471. exit;
  472. } else {
  473. return false;
  474. }
  475. } // end if
  476. return true;
  477. }
  478. /**
  479. * Stores username in a cookie.
  480. *
  481. * @param string $username User name
  482. *
  483. * @return void
  484. */
  485. public function storeUsernameCookie($username)
  486. {
  487. // Name and password cookies need to be refreshed each time
  488. // Duration = one month for username
  489. $GLOBALS['PMA_Config']->setCookie(
  490. 'pmaUser-' . $GLOBALS['server'],
  491. $this->cookieEncrypt(
  492. $username,
  493. $this->_getEncryptionSecret()
  494. )
  495. );
  496. }
  497. /**
  498. * Stores password in a cookie.
  499. *
  500. * @param string $password Password
  501. *
  502. * @return void
  503. */
  504. public function storePasswordCookie($password)
  505. {
  506. $payload = array('password' => $password);
  507. if ($GLOBALS['cfg']['AllowArbitraryServer'] && ! empty($GLOBALS['pma_auth_server'])) {
  508. $payload['server'] = $GLOBALS['pma_auth_server'];
  509. }
  510. // Duration = as configured
  511. $GLOBALS['PMA_Config']->setCookie(
  512. 'pmaAuth-' . $GLOBALS['server'],
  513. $this->cookieEncrypt(
  514. json_encode($payload),
  515. $this->_getSessionEncryptionSecret()
  516. ),
  517. null,
  518. $GLOBALS['cfg']['LoginCookieStore']
  519. );
  520. }
  521. /**
  522. * User is not allowed to login to MySQL -> authentication failed
  523. *
  524. * prepares error message and switches to showLoginForm() which display the error
  525. * and the login form
  526. *
  527. * this function MUST exit/quit the application,
  528. * currently done by call to showLoginForm()
  529. *
  530. * @param string $failure String describing why authentication has failed
  531. *
  532. * @return void
  533. */
  534. public function showFailure($failure)
  535. {
  536. global $conn_error;
  537. parent::showFailure($failure);
  538. // Deletes password cookie and displays the login form
  539. $GLOBALS['PMA_Config']->removeCookie('pmaAuth-' . $GLOBALS['server']);
  540. $conn_error = $this->getErrorMessage($failure);
  541. $response = Response::getInstance();
  542. // needed for PHP-CGI (not need for FastCGI or mod-php)
  543. $response->header('Cache-Control: no-store, no-cache, must-revalidate');
  544. $response->header('Pragma: no-cache');
  545. $this->showLoginForm();
  546. }
  547. /**
  548. * Returns blowfish secret or generates one if needed.
  549. *
  550. * @return string
  551. */
  552. private function _getEncryptionSecret()
  553. {
  554. if (empty($GLOBALS['cfg']['blowfish_secret'])) {
  555. return $this->_getSessionEncryptionSecret();
  556. }
  557. return $GLOBALS['cfg']['blowfish_secret'];
  558. }
  559. /**
  560. * Returns blowfish secret or generates one if needed.
  561. *
  562. * @return string
  563. */
  564. private function _getSessionEncryptionSecret()
  565. {
  566. if (empty($_SESSION['encryption_key'])) {
  567. if ($this->_use_openssl) {
  568. $_SESSION['encryption_key'] = openssl_random_pseudo_bytes(32);
  569. } else {
  570. $_SESSION['encryption_key'] = Crypt\Random::string(32);
  571. }
  572. }
  573. return $_SESSION['encryption_key'];
  574. }
  575. /**
  576. * Concatenates secret in order to make it 16 bytes log
  577. *
  578. * This doesn't add any security, just ensures the secret
  579. * is long enough by copying it.
  580. *
  581. * @param string $secret Original secret
  582. *
  583. * @return string
  584. */
  585. public function enlargeSecret($secret)
  586. {
  587. while (strlen($secret) < 16) {
  588. $secret .= $secret;
  589. }
  590. return substr($secret, 0, 16);
  591. }
  592. /**
  593. * Derives MAC secret from encryption secret.
  594. *
  595. * @param string $secret the secret
  596. *
  597. * @return string the MAC secret
  598. */
  599. public function getMACSecret($secret)
  600. {
  601. // Grab first part, up to 16 chars
  602. // The MAC and AES secrets can overlap if original secret is short
  603. $length = strlen($secret);
  604. if ($length > 16) {
  605. return substr($secret, 0, 16);
  606. }
  607. return $this->enlargeSecret(
  608. $length == 1 ? $secret : substr($secret, 0, -1)
  609. );
  610. }
  611. /**
  612. * Derives AES secret from encryption secret.
  613. *
  614. * @param string $secret the secret
  615. *
  616. * @return string the AES secret
  617. */
  618. public function getAESSecret($secret)
  619. {
  620. // Grab second part, up to 16 chars
  621. // The MAC and AES secrets can overlap if original secret is short
  622. $length = strlen($secret);
  623. if ($length > 16) {
  624. return substr($secret, -16);
  625. }
  626. return $this->enlargeSecret(
  627. $length == 1 ? $secret : substr($secret, 1)
  628. );
  629. }
  630. /**
  631. * Cleans any SSL errors
  632. *
  633. * This can happen from corrupted cookies, by invalid encryption
  634. * parameters used in older phpMyAdmin versions or by wrong openSSL
  635. * configuration.
  636. *
  637. * In neither case the error is useful to user, but we need to clear
  638. * the error buffer as otherwise the errors would pop up later, for
  639. * example during MySQL SSL setup.
  640. *
  641. * @return void
  642. */
  643. public function cleanSSLErrors()
  644. {
  645. if (function_exists('openssl_error_string')) {
  646. while (($ssl_err = openssl_error_string()) !== false) {
  647. }
  648. }
  649. }
  650. /**
  651. * Encryption using openssl's AES or phpseclib's AES
  652. * (phpseclib uses mcrypt when it is available)
  653. *
  654. * @param string $data original data
  655. * @param string $secret the secret
  656. *
  657. * @return string the encrypted result
  658. */
  659. public function cookieEncrypt($data, $secret)
  660. {
  661. $mac_secret = $this->getMACSecret($secret);
  662. $aes_secret = $this->getAESSecret($secret);
  663. $iv = $this->createIV();
  664. if ($this->_use_openssl) {
  665. $result = openssl_encrypt(
  666. $data,
  667. 'AES-128-CBC',
  668. $aes_secret,
  669. 0,
  670. $iv
  671. );
  672. } else {
  673. $cipher = new Crypt\AES(Crypt\Base::MODE_CBC);
  674. $cipher->setIV($iv);
  675. $cipher->setKey($aes_secret);
  676. $result = base64_encode($cipher->encrypt($data));
  677. }
  678. $this->cleanSSLErrors();
  679. $iv = base64_encode($iv);
  680. return json_encode(
  681. array(
  682. 'iv' => $iv,
  683. 'mac' => hash_hmac('sha1', $iv . $result, $mac_secret),
  684. 'payload' => $result,
  685. )
  686. );
  687. }
  688. /**
  689. * Decryption using openssl's AES or phpseclib's AES
  690. * (phpseclib uses mcrypt when it is available)
  691. *
  692. * @param string $encdata encrypted data
  693. * @param string $secret the secret
  694. *
  695. * @return string|false original data, false on error
  696. */
  697. public function cookieDecrypt($encdata, $secret)
  698. {
  699. $data = json_decode($encdata, true);
  700. if (! is_array($data) || ! isset($data['mac']) || ! isset($data['iv']) || ! isset($data['payload'])
  701. || ! is_string($data['mac']) || ! is_string($data['iv']) || ! is_string($data['payload'])
  702. ) {
  703. return false;
  704. }
  705. $mac_secret = $this->getMACSecret($secret);
  706. $aes_secret = $this->getAESSecret($secret);
  707. $newmac = hash_hmac('sha1', $data['iv'] . $data['payload'], $mac_secret);
  708. if (! hash_equals($data['mac'], $newmac)) {
  709. return false;
  710. }
  711. if ($this->_use_openssl) {
  712. $result = openssl_decrypt(
  713. $data['payload'],
  714. 'AES-128-CBC',
  715. $aes_secret,
  716. 0,
  717. base64_decode($data['iv'])
  718. );
  719. } else {
  720. $cipher = new Crypt\AES(Crypt\Base::MODE_CBC);
  721. $cipher->setIV(base64_decode($data['iv']));
  722. $cipher->setKey($aes_secret);
  723. $result = $cipher->decrypt(base64_decode($data['payload']));
  724. }
  725. $this->cleanSSLErrors();
  726. return $result;
  727. }
  728. /**
  729. * Returns size of IV for encryption.
  730. *
  731. * @return int
  732. */
  733. public function getIVSize()
  734. {
  735. if ($this->_use_openssl) {
  736. return openssl_cipher_iv_length('AES-128-CBC');
  737. }
  738. $cipher = new Crypt\AES(Crypt\Base::MODE_CBC);
  739. return $cipher->block_size;
  740. }
  741. /**
  742. * Initialization
  743. * Store the initialization vector because it will be needed for
  744. * further decryption. I don't think necessary to have one iv
  745. * per server so I don't put the server number in the cookie name.
  746. *
  747. * @return string
  748. */
  749. public function createIV()
  750. {
  751. /* Testsuite shortcut only to allow predictable IV */
  752. if (! is_null($this->_cookie_iv)) {
  753. return $this->_cookie_iv;
  754. }
  755. if ($this->_use_openssl) {
  756. return openssl_random_pseudo_bytes(
  757. $this->getIVSize()
  758. );
  759. }
  760. return Crypt\Random::string(
  761. $this->getIVSize()
  762. );
  763. }
  764. /**
  765. * Sets encryption IV to use
  766. *
  767. * This is for testing only!
  768. *
  769. * @param string $vector The IV
  770. *
  771. * @return void
  772. */
  773. public function setIV($vector)
  774. {
  775. $this->_cookie_iv = $vector;
  776. }
  777. /**
  778. * Callback when user changes password.
  779. *
  780. * @param string $password New password to set
  781. *
  782. * @return void
  783. */
  784. public function handlePasswordChange($password)
  785. {
  786. $this->storePasswordCookie($password);
  787. }
  788. /**
  789. * Perform logout
  790. *
  791. * @return void
  792. */
  793. public function logOut()
  794. {
  795. /** @var Config $PMA_Config */
  796. global $PMA_Config;
  797. // -> delete password cookie(s)
  798. if ($GLOBALS['cfg']['LoginCookieDeleteAll']) {
  799. foreach ($GLOBALS['cfg']['Servers'] as $key => $val) {
  800. $PMA_Config->removeCookie('pmaAuth-' . $key);
  801. if ($PMA_Config->issetCookie('pmaAuth-' . $key)) {
  802. $PMA_Config->removeCookie('pmaAuth-' . $key);
  803. }
  804. }
  805. } else {
  806. $cookieName = 'pmaAuth-' . $GLOBALS['server'];
  807. $PMA_Config->removeCookie($cookieName);
  808. if ($PMA_Config->issetCookie($cookieName)) {
  809. $PMA_Config->removeCookie($cookieName);
  810. }
  811. }
  812. parent::logOut();
  813. }
  814. }