PageRenderTime 43ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/classes/files/curl_security_helper.php

https://github.com/mackensen/moodle
PHP | 294 lines | 130 code | 27 blank | 137 comment | 42 complexity | 4152ffbd5e426fb8ea9e037ce81771ac MD5 | raw file
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Contains a class providing functions used to check the allowed/blocked host/ports for curl.
  18. *
  19. * @package core
  20. * @copyright 2016 Jake Dallimore
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. * @author Jake Dallimore <jrhdallimore@gmail.com>
  23. */
  24. namespace core\files;
  25. use core\ip_utils;
  26. defined('MOODLE_INTERNAL') || exit();
  27. /**
  28. * Host and port checking for curl.
  29. *
  30. * This class provides a means to check URL/host/port against the system-level cURL security entries.
  31. * It does not provide a means to add URLs, hosts or ports to the allowed/blocked lists; this is configured manually
  32. * via the site admin section of Moodle (See: 'Site admin' > 'Security' > 'HTTP Security').
  33. *
  34. * This class is currently used by the 'curl' wrapper class in lib/filelib.php.
  35. * Depends on:
  36. * core\ip_utils (several functions)
  37. * moodlelib (clean_param)
  38. *
  39. * @package core
  40. * @copyright 2016 Jake Dallimore
  41. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  42. * @author Jake Dallimore <jrhdallimore@gmail.com>
  43. */
  44. class curl_security_helper extends curl_security_helper_base {
  45. /**
  46. * @var array of supported transport schemes and their respective default ports.
  47. */
  48. protected $transportschemes = [
  49. 'http' => 80,
  50. 'https' => 443
  51. ];
  52. /**
  53. * Checks whether the given URL is blocked by checking its address and port number against the allow/block lists.
  54. * The behaviour of this function can be classified as strict, as it returns true for URLs which are invalid or
  55. * could not be parsed, as well as those valid URLs which were found in the blocklist.
  56. *
  57. * @param string $urlstring the URL to check.
  58. * @param int $notused There used to be an optional parameter $maxredirects for a short while here, not used any more.
  59. * @return bool true if the URL is blocked or invalid and false if the URL is not blocked.
  60. */
  61. public function url_is_blocked($urlstring, $notused = null) {
  62. if ($notused !== null) {
  63. debugging('The $maxredirects parameter of curl_security_helper::url_is_blocked() has been dropped!', DEBUG_DEVELOPER);
  64. }
  65. // If no config data is present, then all hosts/ports are allowed.
  66. if (!$this->is_enabled()) {
  67. return false;
  68. }
  69. // Try to parse the URL to get the 'host' and 'port' components.
  70. try {
  71. $url = new \moodle_url($urlstring);
  72. $parsed['scheme'] = $url->get_scheme();
  73. $parsed['host'] = $url->get_host();
  74. $parsed['port'] = $url->get_port();
  75. } catch (\moodle_exception $e) {
  76. // Moodle exception is thrown if the $urlstring is invalid. Treat as blocked.
  77. return true;
  78. }
  79. // The port will be empty unless explicitly set in the $url (uncommon), so try to infer it from the supported schemes.
  80. if (!$parsed['port'] && $parsed['scheme'] && isset($this->transportschemes[$parsed['scheme']])) {
  81. $parsed['port'] = $this->transportschemes[$parsed['scheme']];
  82. }
  83. if ($parsed['port'] && $parsed['host']) {
  84. // Check the host and port against the allow/block entries.
  85. return $this->host_is_blocked($parsed['host']) || $this->port_is_blocked($parsed['port']);
  86. }
  87. return true;
  88. }
  89. /**
  90. * Returns a string message describing a blocked URL. E.g. 'This URL is blocked'.
  91. *
  92. * @return string the string error.
  93. */
  94. public function get_blocked_url_string() {
  95. return get_string('curlsecurityurlblocked', 'admin');
  96. }
  97. /**
  98. * Checks whether the host portion of a url is blocked.
  99. * The host portion may be a FQDN, IPv4 address or a IPv6 address wrapped in square brackets, as per standard URL notation.
  100. * E.g.
  101. * images.example.com
  102. * 127.0.0.1
  103. * [0.0.0.0.0.0.0.1]
  104. * The method logic is as follows:
  105. * 1. Check the host component against the list of IPv4/IPv6 addresses and ranges.
  106. * - This will perform a DNS forward lookup if required.
  107. * 2. Check the host component against the list of domain names and wildcard domain names.
  108. * - This will perform a DNS reverse lookup if required.
  109. *
  110. * The behaviour of this function can be classified as strict, as it returns true for hosts which are invalid or
  111. * could not be parsed, as well as those valid URLs which were found in the blocklist.
  112. *
  113. * @param string $host the host component of the URL to check against the blocklist.
  114. * @return bool true if the host is both valid and blocked, false otherwise.
  115. */
  116. protected function host_is_blocked($host) {
  117. if (!$this->is_enabled() || empty($host) || !is_string($host)) {
  118. return false;
  119. }
  120. // Fix for square brackets in the 'host' portion of the URL (only occurs if an IPv6 address is specified).
  121. $host = str_replace(array('[', ']'), '', $host); // RFC3986, section 3.2.2.
  122. $blockedhosts = $this->get_blocked_hosts_by_category();
  123. if (ip_utils::is_ip_address($host)) {
  124. if ($this->address_explicitly_blocked($host)) {
  125. return true;
  126. }
  127. // Only perform a reverse lookup if there is a point to it (i.e. we have rules to check against).
  128. if ($blockedhosts['domain'] || $blockedhosts['domainwildcard']) {
  129. // DNS reverse lookup - supports both IPv4 and IPv6 address formats.
  130. $hostname = gethostbyaddr($host);
  131. if ($hostname !== $host && $this->host_explicitly_blocked($hostname)) {
  132. return true;
  133. }
  134. }
  135. } else if (ip_utils::is_domain_name($host)) {
  136. if ($this->host_explicitly_blocked($host)) {
  137. return true;
  138. }
  139. // Only perform a forward lookup if there are IP rules to check against.
  140. if ($blockedhosts['ipv4'] || $blockedhosts['ipv6']) {
  141. // DNS forward lookup - returns a list of only IPv4 addresses!
  142. $hostips = $this->get_host_list_by_name($host);
  143. // If we don't get a valid record, bail (so cURL is never called).
  144. if (!$hostips) {
  145. return true;
  146. }
  147. // If any of the returned IPs are in the blocklist, block the request.
  148. foreach ($hostips as $hostip) {
  149. if ($this->address_explicitly_blocked($hostip)) {
  150. return true;
  151. }
  152. }
  153. }
  154. } else {
  155. // Was not something we consider to be a valid IP or domain name, block it.
  156. return true;
  157. }
  158. return false;
  159. }
  160. /**
  161. * Retrieve all hosts for a domain name.
  162. *
  163. * @param string $param
  164. * @return array An array of IPs associated with the host name.
  165. */
  166. protected function get_host_list_by_name($host) {
  167. return ($hostips = gethostbynamel($host)) ? $hostips : [];
  168. }
  169. /**
  170. * Checks whether the given port is blocked, as determined by its absence on the ports allowlist.
  171. * Ports are assumed to be blocked unless found in the allowlist.
  172. *
  173. * @param integer|string $port the port to check against the ports allowlist.
  174. * @return bool true if the port is blocked, false otherwise.
  175. */
  176. protected function port_is_blocked($port) {
  177. $portnum = intval($port);
  178. // Intentionally block port 0 and below and check the int cast was valid.
  179. if (empty($port) || (string)$portnum !== (string)$port || $port < 0) {
  180. return true;
  181. }
  182. $allowedports = $this->get_allowed_ports();
  183. return !empty($allowedports) && !in_array($portnum, $allowedports);
  184. }
  185. /**
  186. * Convenience method to check whether we have any entries in the host blocklist or ports allowlist admin settings.
  187. * If no entries are found at all, the assumption is that the blocklist is disabled entirely.
  188. *
  189. * @return bool true if one or more entries exist, false otherwise.
  190. */
  191. public function is_enabled() {
  192. return (!empty($this->get_allowed_ports()) || !empty($this->get_blocked_hosts()));
  193. }
  194. /**
  195. * Checks whether the input address is blocked by at any of the IPv4 or IPv6 address rules.
  196. *
  197. * @param string $addr the ip address to check.
  198. * @return bool true if the address is covered by an entry in the blocklist, false otherwise.
  199. */
  200. protected function address_explicitly_blocked($addr) {
  201. $blockedhosts = $this->get_blocked_hosts_by_category();
  202. $iphostsblocked = array_merge($blockedhosts['ipv4'], $blockedhosts['ipv6']);
  203. return address_in_subnet($addr, implode(',', $iphostsblocked));
  204. }
  205. /**
  206. * Checks whether the input hostname is blocked by any of the domain/wildcard rules.
  207. *
  208. * @param string $host the hostname to check
  209. * @return bool true if the host is covered by an entry in the blocklist, false otherwise.
  210. */
  211. protected function host_explicitly_blocked($host) {
  212. $blockedhosts = $this->get_blocked_hosts_by_category();
  213. $domainhostsblocked = array_merge($blockedhosts['domain'], $blockedhosts['domainwildcard']);
  214. return ip_utils::is_domain_in_allowed_list($host, $domainhostsblocked);
  215. }
  216. /**
  217. * Helper to get all entries from the admin setting, as an array, sorted by classification.
  218. * Classifications include 'ipv4', 'ipv6', 'domain', 'domainwildcard'.
  219. *
  220. * @return array of host/domain/ip entries from the 'curlsecurityblockedhosts' config.
  221. */
  222. protected function get_blocked_hosts_by_category() {
  223. // For each of the admin setting entries, check and place in the correct section of the config array.
  224. $config = ['ipv6' => [], 'ipv4' => [], 'domain' => [], 'domainwildcard' => []];
  225. $entries = $this->get_blocked_hosts();
  226. foreach ($entries as $entry) {
  227. if (ip_utils::is_ipv6_address($entry) || ip_utils::is_ipv6_range($entry)) {
  228. $config['ipv6'][] = $entry;
  229. } else if (ip_utils::is_ipv4_address($entry) || ip_utils::is_ipv4_range($entry)) {
  230. $config['ipv4'][] = $entry;
  231. } else if (ip_utils::is_domain_name($entry)) {
  232. $config['domain'][] = $entry;
  233. } else if (ip_utils::is_domain_matching_pattern($entry)) {
  234. $config['domainwildcard'][] = $entry;
  235. }
  236. }
  237. return $config;
  238. }
  239. /**
  240. * Helper that returns the allowed ports, as defined in the 'curlsecurityallowedport' setting.
  241. *
  242. * @return array the array of allowed ports.
  243. */
  244. protected function get_allowed_ports() {
  245. global $CFG;
  246. if (!isset($CFG->curlsecurityallowedport)) {
  247. return [];
  248. }
  249. return array_filter(array_map('trim', explode("\n", $CFG->curlsecurityallowedport)), function($entry) {
  250. return !empty($entry);
  251. });
  252. }
  253. /**
  254. * Helper that returns the blocked hosts, as defined in the 'curlsecurityblockedhosts' setting.
  255. *
  256. * @return array the array of blocked host entries.
  257. */
  258. protected function get_blocked_hosts() {
  259. global $CFG;
  260. if (!isset($CFG->curlsecurityblockedhosts)) {
  261. return [];
  262. }
  263. return array_filter(array_map('trim', explode("\n", $CFG->curlsecurityblockedhosts)), function($entry) {
  264. return !empty($entry);
  265. });
  266. }
  267. }