Validator.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * Form validation for configuration editor
  5. *
  6. * @package PhpMyAdmin
  7. */
  8. declare(strict_types=1);
  9. namespace PhpMyAdmin\Config;
  10. use PhpMyAdmin\Config\ConfigFile;
  11. use PhpMyAdmin\Core;
  12. use PhpMyAdmin\DatabaseInterface;
  13. use PhpMyAdmin\Util;
  14. use function mysql_close;
  15. use function mysql_connect;
  16. use function mysqli_close;
  17. use function mysqli_connect;
  18. /**
  19. * Validation class for various validation functions
  20. *
  21. * Validation function takes two argument: id for which it is called
  22. * and array of fields' values (usually values for entire formset, as defined
  23. * in forms.inc.php).
  24. * The function must always return an array with an error (or error array)
  25. * assigned to a form element (formset name or field path). Even if there are
  26. * no errors, key must be set with an empty value.
  27. *
  28. * Validation functions are assigned in $cfg_db['_validators'] (config.values.php).
  29. *
  30. * @package PhpMyAdmin
  31. */
  32. class Validator
  33. {
  34. /**
  35. * Returns validator list
  36. *
  37. * @param ConfigFile $cf Config file instance
  38. *
  39. * @return array
  40. */
  41. public static function getValidators(ConfigFile $cf)
  42. {
  43. static $validators = null;
  44. if ($validators !== null) {
  45. return $validators;
  46. }
  47. $validators = $cf->getDbEntry('_validators', []);
  48. if ($GLOBALS['PMA_Config']->get('is_setup')) {
  49. return $validators;
  50. }
  51. // not in setup script: load additional validators for user
  52. // preferences we need original config values not overwritten
  53. // by user preferences, creating a new PhpMyAdmin\Config instance is a
  54. // better idea than hacking into its code
  55. $uvs = $cf->getDbEntry('_userValidators', []);
  56. foreach ($uvs as $field => $uvList) {
  57. $uvList = (array) $uvList;
  58. foreach ($uvList as &$uv) {
  59. if (! is_array($uv)) {
  60. continue;
  61. }
  62. for ($i = 1, $nb = count($uv); $i < $nb; $i++) {
  63. if (mb_substr($uv[$i], 0, 6) == 'value:') {
  64. $uv[$i] = Core::arrayRead(
  65. mb_substr($uv[$i], 6),
  66. $GLOBALS['PMA_Config']->base_settings
  67. );
  68. }
  69. }
  70. }
  71. $validators[$field] = isset($validators[$field])
  72. ? array_merge((array) $validators[$field], $uvList)
  73. : $uvList;
  74. }
  75. return $validators;
  76. }
  77. /**
  78. * Runs validation $validator_id on values $values and returns error list.
  79. *
  80. * Return values:
  81. * o array, keys - field path or formset id, values - array of errors
  82. * when $isPostSource is true values is an empty array to allow for error list
  83. * cleanup in HTML document
  84. * o false - when no validators match name(s) given by $validator_id
  85. *
  86. * @param ConfigFile $cf Config file instance
  87. * @param string|array $validatorId ID of validator(s) to run
  88. * @param array $values Values to validate
  89. * @param bool $isPostSource tells whether $values are directly from
  90. * POST request
  91. *
  92. * @return bool|array
  93. */
  94. public static function validate(
  95. ConfigFile $cf,
  96. $validatorId,
  97. array &$values,
  98. $isPostSource
  99. ) {
  100. // find validators
  101. $validatorId = (array) $validatorId;
  102. $validators = static::getValidators($cf);
  103. $vids = [];
  104. foreach ($validatorId as &$vid) {
  105. $vid = $cf->getCanonicalPath($vid);
  106. if (isset($validators[$vid])) {
  107. $vids[] = $vid;
  108. }
  109. }
  110. if (empty($vids)) {
  111. return false;
  112. }
  113. // create argument list with canonical paths and remember path mapping
  114. $arguments = [];
  115. $keyMap = [];
  116. foreach ($values as $k => $v) {
  117. $k2 = $isPostSource ? str_replace('-', '/', $k) : $k;
  118. $k2 = mb_strpos($k2, '/')
  119. ? $cf->getCanonicalPath($k2)
  120. : $k2;
  121. $keyMap[$k2] = $k;
  122. $arguments[$k2] = $v;
  123. }
  124. // validate
  125. $result = [];
  126. foreach ($vids as $vid) {
  127. // call appropriate validation functions
  128. foreach ((array) $validators[$vid] as $validator) {
  129. $vdef = (array) $validator;
  130. $vname = array_shift($vdef);
  131. $vname = 'PhpMyAdmin\Config\Validator::' . $vname;
  132. $args = array_merge([$vid, &$arguments], $vdef);
  133. $r = call_user_func_array($vname, $args);
  134. // merge results
  135. if (! is_array($r)) {
  136. continue;
  137. }
  138. foreach ($r as $key => $errorList) {
  139. // skip empty values if $isPostSource is false
  140. if (! $isPostSource && empty($errorList)) {
  141. continue;
  142. }
  143. if (! isset($result[$key])) {
  144. $result[$key] = [];
  145. }
  146. $result[$key] = array_merge(
  147. $result[$key],
  148. (array) $errorList
  149. );
  150. }
  151. }
  152. }
  153. // restore original paths
  154. $newResult = [];
  155. foreach ($result as $k => $v) {
  156. $k2 = isset($keyMap[$k]) ? $keyMap[$k] : $k;
  157. if (is_array($v)) {
  158. $newResult[$k2] = array_map('htmlspecialchars', $v);
  159. } else {
  160. $newResult[$k2] = htmlspecialchars($v);
  161. }
  162. }
  163. return empty($newResult) ? true : $newResult;
  164. }
  165. /**
  166. * Test database connection
  167. *
  168. * @param string $host host name
  169. * @param string $port tcp port to use
  170. * @param string $socket socket to use
  171. * @param string $user username to use
  172. * @param string $pass password to use
  173. * @param string $errorKey key to use in return array
  174. *
  175. * @return bool|array
  176. */
  177. public static function testDBConnection(
  178. $host,
  179. $port,
  180. $socket,
  181. $user,
  182. $pass = null,
  183. $errorKey = 'Server'
  184. ) {
  185. if ($GLOBALS['cfg']['DBG']['demo']) {
  186. // Connection test disabled on the demo server!
  187. return true;
  188. }
  189. $error = null;
  190. $host = Core::sanitizeMySQLHost($host);
  191. error_clear_last();
  192. if (DatabaseInterface::checkDbExtension('mysqli')) {
  193. $socket = empty($socket) ? null : $socket;
  194. $port = empty($port) ? null : $port;
  195. $extension = 'mysqli';
  196. } else {
  197. $socket = empty($socket) ? null : ':' . ($socket[0] == '/' ? '' : '/') . $socket;
  198. $port = empty($port) ? null : ':' . $port;
  199. $extension = 'mysql';
  200. }
  201. if ($extension == 'mysql') {
  202. $conn = @mysql_connect($host . $port . $socket, $user, $pass);
  203. if (! $conn) {
  204. $error = __('Could not connect to the database server!');
  205. } else {
  206. mysql_close($conn);
  207. }
  208. } else {
  209. $conn = @mysqli_connect($host, $user, $pass, null, $port, $socket);
  210. if (! $conn) {
  211. $error = __('Could not connect to the database server!');
  212. } else {
  213. mysqli_close($conn);
  214. }
  215. }
  216. if ($error !== null) {
  217. $lastError = error_get_last();
  218. if ($lastError !== null) {
  219. $error .= ' - ' . $lastError['message'];
  220. }
  221. }
  222. return $error === null ? true : [$errorKey => $error];
  223. }
  224. /**
  225. * Validate server config
  226. *
  227. * @param string $path path to config, not used
  228. * keep this parameter since the method is invoked using
  229. * reflection along with other similar methods
  230. * @param array $values config values
  231. *
  232. * @return array
  233. */
  234. public static function validateServer($path, array $values)
  235. {
  236. $result = [
  237. 'Server' => '',
  238. 'Servers/1/user' => '',
  239. 'Servers/1/SignonSession' => '',
  240. 'Servers/1/SignonURL' => '',
  241. ];
  242. $error = false;
  243. if (empty($values['Servers/1/auth_type'])) {
  244. $values['Servers/1/auth_type'] = '';
  245. $result['Servers/1/auth_type'] = __('Invalid authentication type!');
  246. $error = true;
  247. }
  248. if ($values['Servers/1/auth_type'] == 'config'
  249. && empty($values['Servers/1/user'])
  250. ) {
  251. $result['Servers/1/user'] = __(
  252. 'Empty username while using [kbd]config[/kbd] authentication method!'
  253. );
  254. $error = true;
  255. }
  256. if ($values['Servers/1/auth_type'] == 'signon'
  257. && empty($values['Servers/1/SignonSession'])
  258. ) {
  259. $result['Servers/1/SignonSession'] = __(
  260. 'Empty signon session name '
  261. . 'while using [kbd]signon[/kbd] authentication method!'
  262. );
  263. $error = true;
  264. }
  265. if ($values['Servers/1/auth_type'] == 'signon'
  266. && empty($values['Servers/1/SignonURL'])
  267. ) {
  268. $result['Servers/1/SignonURL'] = __(
  269. 'Empty signon URL while using [kbd]signon[/kbd] authentication '
  270. . 'method!'
  271. );
  272. $error = true;
  273. }
  274. if (! $error && $values['Servers/1/auth_type'] == 'config') {
  275. $password = '';
  276. if (! empty($values['Servers/1/password'])) {
  277. $password = $values['Servers/1/password'];
  278. }
  279. $test = static::testDBConnection(
  280. empty($values['Servers/1/host']) ? '' : $values['Servers/1/host'],
  281. empty($values['Servers/1/port']) ? '' : $values['Servers/1/port'],
  282. empty($values['Servers/1/socket']) ? '' : $values['Servers/1/socket'],
  283. empty($values['Servers/1/user']) ? '' : $values['Servers/1/user'],
  284. $password,
  285. 'Server'
  286. );
  287. if ($test !== true) {
  288. $result = array_merge($result, $test);
  289. }
  290. }
  291. return $result;
  292. }
  293. /**
  294. * Validate pmadb config
  295. *
  296. * @param string $path path to config, not used
  297. * keep this parameter since the method is invoked using
  298. * reflection along with other similar methods
  299. * @param array $values config values
  300. *
  301. * @return array
  302. */
  303. public static function validatePMAStorage($path, array $values)
  304. {
  305. $result = [
  306. 'Server_pmadb' => '',
  307. 'Servers/1/controluser' => '',
  308. 'Servers/1/controlpass' => '',
  309. ];
  310. $error = false;
  311. if (empty($values['Servers/1/pmadb'])) {
  312. return $result;
  313. }
  314. $result = [];
  315. if (empty($values['Servers/1/controluser'])) {
  316. $result['Servers/1/controluser'] = __(
  317. 'Empty phpMyAdmin control user while using phpMyAdmin configuration '
  318. . 'storage!'
  319. );
  320. $error = true;
  321. }
  322. if (empty($values['Servers/1/controlpass'])) {
  323. $result['Servers/1/controlpass'] = __(
  324. 'Empty phpMyAdmin control user password while using phpMyAdmin '
  325. . 'configuration storage!'
  326. );
  327. $error = true;
  328. }
  329. if (! $error) {
  330. $test = static::testDBConnection(
  331. empty($values['Servers/1/host']) ? '' : $values['Servers/1/host'],
  332. empty($values['Servers/1/port']) ? '' : $values['Servers/1/port'],
  333. empty($values['Servers/1/socket']) ? '' : $values['Servers/1/socket'],
  334. empty($values['Servers/1/controluser']) ? '' : $values['Servers/1/controluser'],
  335. empty($values['Servers/1/controlpass']) ? '' : $values['Servers/1/controlpass'],
  336. 'Server_pmadb'
  337. );
  338. if ($test !== true) {
  339. $result = array_merge($result, $test);
  340. }
  341. }
  342. return $result;
  343. }
  344. /**
  345. * Validates regular expression
  346. *
  347. * @param string $path path to config
  348. * @param array $values config values
  349. *
  350. * @return array
  351. */
  352. public static function validateRegex($path, array $values)
  353. {
  354. $result = [$path => ''];
  355. if (empty($values[$path])) {
  356. return $result;
  357. }
  358. error_clear_last();
  359. $matches = [];
  360. // in libraries/ListDatabase.php _checkHideDatabase(),
  361. // a '/' is used as the delimiter for hide_db
  362. @preg_match('/' . Util::requestString($values[$path]) . '/', '', $matches);
  363. $currentError = error_get_last();
  364. if ($currentError !== null) {
  365. $error = preg_replace('/^preg_match\(\): /', '', $currentError['message']);
  366. return [$path => $error];
  367. }
  368. return $result;
  369. }
  370. /**
  371. * Validates TrustedProxies field
  372. *
  373. * @param string $path path to config
  374. * @param array $values config values
  375. *
  376. * @return array
  377. */
  378. public static function validateTrustedProxies($path, array $values)
  379. {
  380. $result = [$path => []];
  381. if (empty($values[$path])) {
  382. return $result;
  383. }
  384. if (is_array($values[$path]) || is_object($values[$path])) {
  385. // value already processed by FormDisplay::save
  386. $lines = [];
  387. foreach ($values[$path] as $ip => $v) {
  388. $v = Util::requestString($v);
  389. $lines[] = preg_match('/^-\d+$/', $ip)
  390. ? $v
  391. : $ip . ': ' . $v;
  392. }
  393. } else {
  394. // AJAX validation
  395. $lines = explode("\n", $values[$path]);
  396. }
  397. foreach ($lines as $line) {
  398. $line = trim($line);
  399. $matches = [];
  400. // we catch anything that may (or may not) be an IP
  401. if (! preg_match("/^(.+):(?:[ ]?)\\w+$/", $line, $matches)) {
  402. $result[$path][] = __('Incorrect value:') . ' '
  403. . htmlspecialchars($line);
  404. continue;
  405. }
  406. // now let's check whether we really have an IP address
  407. if (filter_var($matches[1], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false
  408. && filter_var($matches[1], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false
  409. ) {
  410. $ip = htmlspecialchars(trim($matches[1]));
  411. $result[$path][] = sprintf(__('Incorrect IP address: %s'), $ip);
  412. continue;
  413. }
  414. }
  415. return $result;
  416. }
  417. /**
  418. * Tests integer value
  419. *
  420. * @param string $path path to config
  421. * @param array $values config values
  422. * @param bool $allowNegative allow negative values
  423. * @param bool $allowZero allow zero
  424. * @param int $maxValue max allowed value
  425. * @param string $errorString error message string
  426. *
  427. * @return string empty string if test is successful
  428. */
  429. public static function validateNumber(
  430. $path,
  431. array $values,
  432. $allowNegative,
  433. $allowZero,
  434. $maxValue,
  435. $errorString
  436. ) {
  437. if (empty($values[$path])) {
  438. return '';
  439. }
  440. $value = Util::requestString($values[$path]);
  441. if (intval($value) != $value
  442. || (! $allowNegative && $value < 0)
  443. || (! $allowZero && $value == 0)
  444. || $value > $maxValue
  445. ) {
  446. return $errorString;
  447. }
  448. return '';
  449. }
  450. /**
  451. * Validates port number
  452. *
  453. * @param string $path path to config
  454. * @param array $values config values
  455. *
  456. * @return array
  457. */
  458. public static function validatePortNumber($path, array $values)
  459. {
  460. return [
  461. $path => static::validateNumber(
  462. $path,
  463. $values,
  464. false,
  465. false,
  466. 65535,
  467. __('Not a valid port number!')
  468. ),
  469. ];
  470. }
  471. /**
  472. * Validates positive number
  473. *
  474. * @param string $path path to config
  475. * @param array $values config values
  476. *
  477. * @return array
  478. */
  479. public static function validatePositiveNumber($path, array $values)
  480. {
  481. return [
  482. $path => static::validateNumber(
  483. $path,
  484. $values,
  485. false,
  486. false,
  487. PHP_INT_MAX,
  488. __('Not a positive number!')
  489. ),
  490. ];
  491. }
  492. /**
  493. * Validates non-negative number
  494. *
  495. * @param string $path path to config
  496. * @param array $values config values
  497. *
  498. * @return array
  499. */
  500. public static function validateNonNegativeNumber($path, array $values)
  501. {
  502. return [
  503. $path => static::validateNumber(
  504. $path,
  505. $values,
  506. false,
  507. true,
  508. PHP_INT_MAX,
  509. __('Not a non-negative number!')
  510. ),
  511. ];
  512. }
  513. /**
  514. * Validates value according to given regular expression
  515. * Pattern and modifiers must be a valid for PCRE <b>and</b> JavaScript RegExp
  516. *
  517. * @param string $path path to config
  518. * @param array $values config values
  519. * @param string $regex regular expression to match
  520. *
  521. * @return array|string
  522. */
  523. public static function validateByRegex($path, array $values, $regex)
  524. {
  525. if (! isset($values[$path])) {
  526. return '';
  527. }
  528. $result = preg_match($regex, Util::requestString($values[$path]));
  529. return [$path => $result ? '' : __('Incorrect value!')];
  530. }
  531. /**
  532. * Validates upper bound for numeric inputs
  533. *
  534. * @param string $path path to config
  535. * @param array $values config values
  536. * @param int $maxValue maximal allowed value
  537. *
  538. * @return array
  539. */
  540. public static function validateUpperBound($path, array $values, $maxValue)
  541. {
  542. $result = $values[$path] <= $maxValue;
  543. return [
  544. $path => $result ? '' : sprintf(
  545. __('Value must be less than or equal to %s!'),
  546. $maxValue
  547. ),
  548. ];
  549. }
  550. }