Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

623 lines
21KB

  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\validators;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\helpers\Html;
  11. use yii\helpers\Json;
  12. use yii\web\JsExpression;
  13. /**
  14. * The validator checks if the attribute value is a valid IPv4/IPv6 address or subnet.
  15. *
  16. * It also may change attribute's value if normalization of IPv6 expansion is enabled.
  17. *
  18. * The following are examples of validation rules using this validator:
  19. *
  20. * ```php
  21. * ['ip_address', 'ip'], // IPv4 or IPv6 address
  22. * ['ip_address', 'ip', 'ipv6' => false], // IPv4 address (IPv6 is disabled)
  23. * ['ip_address', 'ip', 'subnet' => true], // requires a CIDR prefix (like 10.0.0.1/24) for the IP address
  24. * ['ip_address', 'ip', 'subnet' => null], // CIDR prefix is optional
  25. * ['ip_address', 'ip', 'subnet' => null, 'normalize' => true], // CIDR prefix is optional and will be added when missing
  26. * ['ip_address', 'ip', 'ranges' => ['192.168.0.0/24']], // only IP addresses from the specified subnet are allowed
  27. * ['ip_address', 'ip', 'ranges' => ['!192.168.0.0/24', 'any']], // any IP is allowed except IP in the specified subnet
  28. * ['ip_address', 'ip', 'expandIPv6' => true], // expands IPv6 address to a full notation format
  29. * ```
  30. *
  31. * @property array $ranges The IPv4 or IPv6 ranges that are allowed or forbidden. See [[setRanges()]] for
  32. * detailed description.
  33. *
  34. * @author Dmitry Naumenko <d.naumenko.a@gmail.com>
  35. * @since 2.0.7
  36. */
  37. class IpValidator extends Validator
  38. {
  39. /**
  40. * The length of IPv6 address in bits
  41. */
  42. const IPV6_ADDRESS_LENGTH = 128;
  43. /**
  44. * The length of IPv4 address in bits
  45. */
  46. const IPV4_ADDRESS_LENGTH = 32;
  47. /**
  48. * Negation char. Used to negate [[ranges]] or [[networks]]
  49. * or to negate validating value when [[negation]] is set to `true`
  50. * @see negation
  51. * @see networks
  52. * @see ranges
  53. */
  54. const NEGATION_CHAR = '!';
  55. /**
  56. * @var array The network aliases, that can be used in [[ranges]].
  57. * - key - alias name
  58. * - value - array of strings. String can be an IP range, IP address or another alias. String can be
  59. * negated with [[NEGATION_CHAR]] (independent of `negation` option).
  60. *
  61. * The following aliases are defined by default:
  62. * - `*`: `any`
  63. * - `any`: `0.0.0.0/0, ::/0`
  64. * - `private`: `10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fd00::/8`
  65. * - `multicast`: `224.0.0.0/4, ff00::/8`
  66. * - `linklocal`: `169.254.0.0/16, fe80::/10`
  67. * - `localhost`: `127.0.0.0/8', ::1`
  68. * - `documentation`: `192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 2001:db8::/32`
  69. * - `system`: `multicast, linklocal, localhost, documentation`
  70. *
  71. */
  72. public $networks = [
  73. '*' => ['any'],
  74. 'any' => ['0.0.0.0/0', '::/0'],
  75. 'private' => ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fd00::/8'],
  76. 'multicast' => ['224.0.0.0/4', 'ff00::/8'],
  77. 'linklocal' => ['169.254.0.0/16', 'fe80::/10'],
  78. 'localhost' => ['127.0.0.0/8', '::1'],
  79. 'documentation' => ['192.0.2.0/24', '198.51.100.0/24', '203.0.113.0/24', '2001:db8::/32'],
  80. 'system' => ['multicast', 'linklocal', 'localhost', 'documentation'],
  81. ];
  82. /**
  83. * @var boolean whether the validating value can be an IPv6 address. Defaults to `true`.
  84. */
  85. public $ipv6 = true;
  86. /**
  87. * @var boolean whether the validating value can be an IPv4 address. Defaults to `true`.
  88. */
  89. public $ipv4 = true;
  90. /**
  91. * @var boolean whether the address can be an IP with CIDR subnet, like `192.168.10.0/24`.
  92. * The following values are possible:
  93. *
  94. * - `false` - the address must not have a subnet (default).
  95. * - `true` - specifying a subnet is required.
  96. * - `null` - specifying a subnet is optional.
  97. */
  98. public $subnet = false;
  99. /**
  100. * @var boolean whether to add the CIDR prefix with the smallest length (32 for IPv4 and 128 for IPv6) to an
  101. * address without it. Works only when `subnet` is not `false`. For example:
  102. * - `10.0.1.5` will normalized to `10.0.1.5/32`
  103. * - `2008:db0::1` will be normalized to `2008:db0::1/128`
  104. * Defaults to `false`.
  105. * @see subnet
  106. */
  107. public $normalize = false;
  108. /**
  109. * @var boolean whether address may have a [[NEGATION_CHAR]] character at the beginning.
  110. * Defaults to `false`.
  111. */
  112. public $negation = false;
  113. /**
  114. * @var boolean whether to expand an IPv6 address to the full notation format.
  115. * Defaults to `false`.
  116. */
  117. public $expandIPv6 = false;
  118. /**
  119. * @var string Regexp-pattern to validate IPv4 address
  120. */
  121. public $ipv4Pattern = '/^(?:(?:2(?:[0-4][0-9]|5[0-5])|[0-1]?[0-9]?[0-9])\.){3}(?:(?:2([0-4][0-9]|5[0-5])|[0-1]?[0-9]?[0-9]))$/';
  122. /**
  123. * @var string Regexp-pattern to validate IPv6 address
  124. */
  125. public $ipv6Pattern = '/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/';
  126. /**
  127. * @var string user-defined error message is used when validation fails due to the wrong IP address format.
  128. *
  129. * You may use the following placeholders in the message:
  130. *
  131. * - `{attribute}`: the label of the attribute being validated
  132. * - `{value}`: the value of the attribute being validated
  133. */
  134. public $message;
  135. /**
  136. * @var string user-defined error message is used when validation fails due to the disabled IPv6 validation.
  137. *
  138. * You may use the following placeholders in the message:
  139. *
  140. * - `{attribute}`: the label of the attribute being validated
  141. * - `{value}`: the value of the attribute being validated
  142. *
  143. * @see ipv6
  144. */
  145. public $ipv6NotAllowed;
  146. /**
  147. * @var string user-defined error message is used when validation fails due to the disabled IPv4 validation.
  148. *
  149. * You may use the following placeholders in the message:
  150. *
  151. * - `{attribute}`: the label of the attribute being validated
  152. * - `{value}`: the value of the attribute being validated
  153. *
  154. * @see ipv4
  155. */
  156. public $ipv4NotAllowed;
  157. /**
  158. * @var string user-defined error message is used when validation fails due to the wrong CIDR.
  159. *
  160. * You may use the following placeholders in the message:
  161. *
  162. * - `{attribute}`: the label of the attribute being validated
  163. * - `{value}`: the value of the attribute being validated
  164. * @see subnet
  165. */
  166. public $wrongCidr;
  167. /**
  168. * @var string user-defined error message is used when validation fails due to subnet [[subnet]] set to 'only',
  169. * but the CIDR prefix is not set.
  170. *
  171. * You may use the following placeholders in the message:
  172. *
  173. * - `{attribute}`: the label of the attribute being validated
  174. * - `{value}`: the value of the attribute being validated
  175. *
  176. * @see subnet
  177. */
  178. public $noSubnet;
  179. /**
  180. * @var string user-defined error message is used when validation fails
  181. * due to [[subnet]] is false, but CIDR prefix is present.
  182. *
  183. * You may use the following placeholders in the message:
  184. *
  185. * - `{attribute}`: the label of the attribute being validated
  186. * - `{value}`: the value of the attribute being validated
  187. *
  188. * @see subnet
  189. */
  190. public $hasSubnet;
  191. /**
  192. * @var string user-defined error message is used when validation fails due to IP address
  193. * is not not allowed by [[ranges]] check.
  194. *
  195. * You may use the following placeholders in the message:
  196. *
  197. * - `{attribute}`: the label of the attribute being validated
  198. * - `{value}`: the value of the attribute being validated
  199. *
  200. * @see ranges
  201. */
  202. public $notInRange;
  203. /**
  204. * @var array
  205. */
  206. private $_ranges = [];
  207. /**
  208. * @inheritdoc
  209. */
  210. public function init()
  211. {
  212. parent::init();
  213. if (!$this->ipv4 && !$this->ipv6) {
  214. throw new InvalidConfigException('Both IPv4 and IPv6 checks can not be disabled at the same time');
  215. }
  216. if (!defined('AF_INET6') && $this->ipv6) {
  217. throw new InvalidConfigException('IPv6 validation can not be used. PHP is compiled without IPv6');
  218. }
  219. if ($this->message === null) {
  220. $this->message = Yii::t('yii', '{attribute} must be a valid IP address.');
  221. }
  222. if ($this->ipv6NotAllowed === null) {
  223. $this->ipv6NotAllowed = Yii::t('yii', '{attribute} must not be an IPv6 address.');
  224. }
  225. if ($this->ipv4NotAllowed === null) {
  226. $this->ipv4NotAllowed = Yii::t('yii', '{attribute} must not be an IPv4 address.');
  227. }
  228. if ($this->wrongCidr === null) {
  229. $this->wrongCidr = Yii::t('yii', '{attribute} contains wrong subnet mask.');
  230. }
  231. if ($this->noSubnet === null) {
  232. $this->noSubnet = Yii::t('yii', '{attribute} must be an IP address with specified subnet.');
  233. }
  234. if ($this->hasSubnet === null) {
  235. $this->hasSubnet = Yii::t('yii', '{attribute} must not be a subnet.');
  236. }
  237. if ($this->notInRange === null) {
  238. $this->notInRange = Yii::t('yii', '{attribute} is not in the allowed range.');
  239. }
  240. }
  241. /**
  242. * Set the IPv4 or IPv6 ranges that are allowed or forbidden.
  243. *
  244. * The following preparation tasks are performed:
  245. *
  246. * - Recursively substitutes aliases (described in [[networks]]) with their values.
  247. * - Removes duplicates
  248. *
  249. * @property array the IPv4 or IPv6 ranges that are allowed or forbidden.
  250. * See [[setRanges()]] for detailed description.
  251. * @param array $ranges the IPv4 or IPv6 ranges that are allowed or forbidden.
  252. *
  253. * When the array is empty, or the option not set, all IP addresses are allowed.
  254. *
  255. * Otherwise, the rules are checked sequentially until the first match is found.
  256. * An IP address is forbidden, when it has not matched any of the rules.
  257. *
  258. * Example:
  259. *
  260. * ```php
  261. * [
  262. * 'ranges' => [
  263. * '192.168.10.128'
  264. * '!192.168.10.0/24',
  265. * 'any' // allows any other IP addresses
  266. * ]
  267. * ]
  268. * ```
  269. *
  270. * In this example, access is allowed for all the IPv4 and IPv6 addresses excluding the `192.168.10.0/24` subnet.
  271. * IPv4 address `192.168.10.128` is also allowed, because it is listed before the restriction.
  272. */
  273. public function setRanges($ranges)
  274. {
  275. $this->_ranges = $this->prepareRanges((array) $ranges);
  276. }
  277. /**
  278. * @return array The IPv4 or IPv6 ranges that are allowed or forbidden.
  279. */
  280. public function getRanges()
  281. {
  282. return $this->_ranges;
  283. }
  284. /**
  285. * @inheritdoc
  286. */
  287. protected function validateValue($value)
  288. {
  289. $result = $this->validateSubnet($value);
  290. if (is_array($result)) {
  291. $result[1] = array_merge(['ip' => is_array($value) ? 'array()' : $value], $result[1]);
  292. return $result;
  293. } else {
  294. return null;
  295. }
  296. }
  297. /**
  298. * @inheritdoc
  299. */
  300. public function validateAttribute($model, $attribute)
  301. {
  302. $value = $model->$attribute;
  303. $result = $this->validateSubnet($value);
  304. if (is_array($result)) {
  305. $result[1] = array_merge(['ip' => is_array($value) ? 'array()' : $value], $result[1]);
  306. $this->addError($model, $attribute, $result[0], $result[1]);
  307. } else {
  308. $model->$attribute = $result;
  309. }
  310. }
  311. /**
  312. * Validates an IPv4/IPv6 address or subnet
  313. *
  314. * @param $ip string
  315. * @return string|array
  316. * string - the validation was successful;
  317. * array - an error occurred during the validation.
  318. * Array[0] contains the text of an error, array[1] contains values for the placeholders in the error message
  319. */
  320. private function validateSubnet($ip)
  321. {
  322. if (!is_string($ip)) {
  323. return [$this->message, []];
  324. }
  325. $negation = null;
  326. $cidr = null;
  327. $isCidrDefault = false;
  328. if (preg_match($this->getIpParsePattern(), $ip, $matches)) {
  329. $negation = ($matches[1] !== '') ? $matches[1] : null;
  330. $ip = $matches[2];
  331. $cidr = isset($matches[4]) ? $matches[4] : null;
  332. }
  333. if ($this->subnet === true && $cidr === null) {
  334. return [$this->noSubnet, []];
  335. }
  336. if ($this->subnet === false && $cidr !== null) {
  337. return [$this->hasSubnet, []];
  338. }
  339. if ($this->negation === false && $negation !== null) {
  340. return [$this->message, []];
  341. }
  342. if ($this->getIpVersion($ip) == 6) {
  343. if ($cidr !== null) {
  344. if ($cidr > static::IPV6_ADDRESS_LENGTH || $cidr < 0) {
  345. return [$this->wrongCidr, []];
  346. }
  347. } else {
  348. $isCidrDefault = true;
  349. $cidr = static::IPV6_ADDRESS_LENGTH;
  350. }
  351. if (!$this->ipv6) {
  352. return [$this->ipv6NotAllowed, []];
  353. }
  354. if (!$this->validateIPv6($ip)) {
  355. return [$this->message, []];
  356. }
  357. if ($this->expandIPv6) {
  358. $ip = $this->expandIPv6($ip);
  359. }
  360. } else {
  361. if ($cidr !== null) {
  362. if ($cidr > static::IPV4_ADDRESS_LENGTH || $cidr < 0) {
  363. return [$this->wrongCidr, []];
  364. }
  365. } else {
  366. $isCidrDefault = true;
  367. $cidr = static::IPV4_ADDRESS_LENGTH;
  368. }
  369. if (!$this->ipv4) {
  370. return [$this->ipv4NotAllowed, []];
  371. }
  372. if (!$this->validateIPv4($ip)) {
  373. return [$this->message, []];
  374. }
  375. }
  376. if (!$this->isAllowed($ip, $cidr)) {
  377. return [$this->notInRange, []];
  378. }
  379. $result = $negation . $ip;
  380. if ($this->subnet !== false && (!$isCidrDefault || $isCidrDefault && $this->normalize)) {
  381. $result .= "/$cidr";
  382. }
  383. return $result;
  384. }
  385. /**
  386. * Expands an IPv6 address to it's full notation. For example `2001:db8::1` will be
  387. * expanded to `2001:0db8:0000:0000:0000:0000:0000:0001`
  388. *
  389. * @param string $ip the original IPv6
  390. * @return string the expanded IPv6
  391. */
  392. private function expandIPv6($ip)
  393. {
  394. $hex = unpack('H*hex', inet_pton($ip));
  395. return substr(preg_replace('/([a-f0-9]{4})/i', '$1:', $hex['hex']), 0, -1);
  396. }
  397. /**
  398. * The method checks whether the IP address with specified CIDR is allowed according to the [[ranges]] list.
  399. *
  400. * @param string $ip
  401. * @param integer $cidr
  402. * @return boolean
  403. * @see ranges
  404. */
  405. private function isAllowed($ip, $cidr)
  406. {
  407. if (empty($this->ranges)) {
  408. return true;
  409. }
  410. foreach ($this->ranges as $string) {
  411. list($isNegated, $range) = $this->parseNegatedRange($string);
  412. if ($this->inRange($ip, $cidr, $range)) {
  413. return !$isNegated;
  414. }
  415. }
  416. return false;
  417. }
  418. /**
  419. * Parses IP address/range for the negation with [[NEGATION_CHAR]].
  420. *
  421. * @param $string
  422. * @return array `[0 => boolean, 1 => string]`
  423. * - boolean: whether the string is negated
  424. * - string: the string without negation (when the negation were present)
  425. */
  426. private function parseNegatedRange($string)
  427. {
  428. $isNegated = strpos($string, static::NEGATION_CHAR) === 0;
  429. return [$isNegated, $isNegated ? substr($string, strlen(static::NEGATION_CHAR)) : $string];
  430. }
  431. /**
  432. * Prepares array to fill in [[ranges]]:
  433. * - Recursively substitutes aliases, described in [[networks]] with their values
  434. * - Removes duplicates
  435. *
  436. *
  437. * @param $ranges
  438. * @return array
  439. * @see networks
  440. */
  441. private function prepareRanges($ranges)
  442. {
  443. $result = [];
  444. foreach ($ranges as $string) {
  445. list($isRangeNegated, $range) = $this->parseNegatedRange($string);
  446. if (isset($this->networks[$range])) {
  447. $replacements = $this->prepareRanges($this->networks[$range]);
  448. foreach ($replacements as &$replacement) {
  449. list($isReplacementNegated, $replacement) = $this->parseNegatedRange($replacement);
  450. $result[] = ($isRangeNegated && !$isReplacementNegated ? static::NEGATION_CHAR : '') . $replacement;
  451. }
  452. } else {
  453. $result[] = $string;
  454. }
  455. }
  456. return array_unique($result);
  457. }
  458. /**
  459. * Validates IPv4 address
  460. *
  461. * @param string $value
  462. * @return boolean
  463. */
  464. protected function validateIPv4($value)
  465. {
  466. return preg_match($this->ipv4Pattern, $value) !== 0;
  467. }
  468. /**
  469. * Validates IPv6 address
  470. *
  471. * @param string $value
  472. * @return boolean
  473. */
  474. protected function validateIPv6($value)
  475. {
  476. return preg_match($this->ipv6Pattern, $value) !== 0;
  477. }
  478. /**
  479. * Gets the IP version
  480. *
  481. * @param string $ip
  482. * @return integer
  483. */
  484. private function getIpVersion($ip)
  485. {
  486. return strpos($ip, ':') === false ? 4 : 6;
  487. }
  488. /**
  489. * Used to get the Regexp pattern for initial IP address parsing
  490. * @return string
  491. */
  492. private function getIpParsePattern()
  493. {
  494. return '/^(' . preg_quote(static::NEGATION_CHAR) . '?)(.+?)(\/(\d+))?$/';
  495. }
  496. /**
  497. * Checks whether the IP is in subnet range
  498. *
  499. * @param string $ip an IPv4 or IPv6 address
  500. * @param integer $cidr
  501. * @param string $range subnet in CIDR format e.g. `10.0.0.0/8` or `2001:af::/64`
  502. * @return boolean
  503. */
  504. private function inRange($ip, $cidr, $range)
  505. {
  506. $ipVersion = $this->getIpVersion($ip);
  507. $binIp = $this->ip2bin($ip);
  508. $parts = explode('/', $range);
  509. $net = array_shift($parts);
  510. $range_cidr = array_shift($parts);
  511. $netVersion = $this->getIpVersion($net);
  512. if ($ipVersion !== $netVersion) {
  513. return false;
  514. }
  515. if ($range_cidr === null) {
  516. $range_cidr = $netVersion === 4 ? static::IPV4_ADDRESS_LENGTH : static::IPV6_ADDRESS_LENGTH;
  517. }
  518. $binNet = $this->ip2bin($net);
  519. return substr($binIp, 0, $range_cidr) === substr($binNet, 0, $range_cidr) && $cidr >= $range_cidr;
  520. }
  521. /**
  522. * Converts IP address to bits representation
  523. *
  524. * @param string $ip
  525. * @return string bits as a string
  526. */
  527. private function ip2bin($ip)
  528. {
  529. if ($this->getIpVersion($ip) === 4) {
  530. return str_pad(base_convert(ip2long($ip), 10, 2), static::IPV4_ADDRESS_LENGTH, '0', STR_PAD_LEFT);
  531. } else {
  532. $unpack = unpack('A16', inet_pton($ip));
  533. $binStr = array_shift($unpack);
  534. $bytes = static::IPV6_ADDRESS_LENGTH / 8; // 128 bit / 8 = 16 bytes
  535. $result = '';
  536. while ($bytes-- > 0) {
  537. $result = sprintf('%08b', isset($binStr[$bytes]) ? ord($binStr[$bytes]) : '0') . $result;
  538. }
  539. return $result;
  540. }
  541. }
  542. /**
  543. * @inheritdoc
  544. */
  545. public function clientValidateAttribute($model, $attribute, $view)
  546. {
  547. $messages = [
  548. 'ipv6NotAllowed' => $this->ipv6NotAllowed,
  549. 'ipv4NotAllowed' => $this->ipv4NotAllowed,
  550. 'message' => $this->message,
  551. 'noSubnet' => $this->noSubnet,
  552. 'hasSubnet' => $this->hasSubnet,
  553. ];
  554. foreach ($messages as &$message) {
  555. $message = Yii::$app->getI18n()->format($message, [
  556. 'attribute' => $model->getAttributeLabel($attribute),
  557. ], Yii::$app->language);
  558. }
  559. $options = [
  560. 'ipv4Pattern' => new JsExpression(Html::escapeJsRegularExpression($this->ipv4Pattern)),
  561. 'ipv6Pattern' => new JsExpression(Html::escapeJsRegularExpression($this->ipv6Pattern)),
  562. 'messages' => $messages,
  563. 'ipv4' => (boolean)$this->ipv4,
  564. 'ipv6' => (boolean)$this->ipv6,
  565. 'ipParsePattern' => new JsExpression(Html::escapeJsRegularExpression($this->getIpParsePattern())),
  566. 'negation' => $this->negation,
  567. 'subnet' => $this->subnet,
  568. ];
  569. if ($this->skipOnEmpty) {
  570. $options['skipOnEmpty'] = 1;
  571. }
  572. ValidationAsset::register($view);
  573. return 'yii.validation.ip(value, messages, ' . Json::htmlEncode($options) . ');';
  574. }
  575. }