/
Url.php
264 lines (221 loc) · 8.43 KB
/
Url.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
<?php
namespace fin1te\SafeCurl;
use fin1te\SafeCurl\Exception\InvalidURLException;
use fin1te\SafeCurl\Exception\InvalidURLException\InvalidDomainException;
use fin1te\SafeCurl\Exception\InvalidURLException\InvalidIPException;
use fin1te\SafeCurl\Exception\InvalidURLException\InvalidPortException;
use fin1te\SafeCurl\Exception\InvalidURLException\InvalidSchemeException;
class Url {
/**
* Validates the whole URL
*
* @param $url string
* @param $options fin1te\SafeCurl\Options
*
* @return string
*/
public static function validateUrl($url, Options $options) {
if (trim($url) == '') {
throw new InvalidURLException("Provided URL '$url' cannot be empty");
}
//Split URL into parts first
$parts = parse_url($url);
if (empty($parts)) {
throw new InvalidURLException("Error parsing URL '$url'");
}
if (!array_key_exists('host', $parts)) {
throw new InvalidURLException("Provided URL '$url' doesn't contain a hostname");
}
//First, validate the scheme
if (array_key_exists('scheme', $parts)) {
$parts['scheme'] = self::validateScheme($parts['scheme'], $options);
} else {
//Default to http
$parts['scheme'] = 'http';
}
//Validate the port
if (array_key_exists('port', $parts)) {
$parts['port'] = self::validatePort($parts['port'], $options);
}
//Reolve host to ip(s)
$parts['ips'] = self::resolveHostname($parts['host']);
//Validate the host
$parts['host'] = self::validateHostname($parts['host'], $parts['ips'], $options);
if ($options->getPinDns()) {
//Since we're pinning DNS, we replace the host in the URL
//with an IP, then get cURL to send the Host header
$parts['host'] = $parts['ips'][0];
}
//Rebuild the URL
$cleanUrl = self::buildUrl($parts);
return array('originalUrl' => $url, 'cleanUrl' => $cleanUrl, 'parts' => $parts);
}
/**
* Validates a URL scheme
*
* @param $scheme string
* @param $options fin1te\SafeCurl\Options
*
* @return string
*/
public static function validateScheme($scheme, Options $options) {
//Whitelist always takes precedence over a blacklist
if (!$options->isInList('whitelist', 'scheme', $scheme)) {
throw new InvalidSchemeException("Provided scheme '$scheme' doesn't match whitelisted values: "
. implode(', ', $options->getList('whitelist', 'scheme')));
}
if ($options->isInList('blacklist', 'scheme', $scheme)) {
throw new InvalidSchemeException("Provided scheme '$scheme' matches a blacklisted value");
}
//Existing value is fine
return $scheme;
}
/**
* Validates a port
*
* @param $port int
* @param $options fin1te\SafeCurl\Options
*
* @return int
*/
public static function validatePort($port, Options $options) {
if (!$options->isInList('whitelist', 'port', $port)) {
throw new InvalidPortException("Provided port '$port' doesn't match whitelisted values: "
. implode(', ', $options->getList('whitelist', 'port')));
}
if ($options->isInList('blacklist', 'port', $port)) {
throw new InvalidPortException("Provided port '$port' matches a blacklisted value");
}
//Existing value is fine
return $port;
}
/**
* Validates a URL hostname
*
* @param $hostname string
* @param $options fin1te\SafeCurl\Options
*
* @returns string
*/
public static function validateHostname($hostname, $ips, Options $options) {
//Check the host against the domain lists
if (!$options->isInList('whitelist', 'domain', $hostname)) {
throw new InvalidDomainException("Provided hostname '$hostname' doesn't match whitelisted values: "
. implode(', ', $options->getList('whitelist', 'domain')));
}
if ($options->isInList('blacklist', 'domain', $hostname)) {
throw new InvalidDomainException("Provided hostname '$hostname' matches a blacklisted value");
}
$whitelistedIps = $options->getList('whitelist', 'ip');
if (!empty($whitelistedIps)) {
$valid = false;
foreach ($whitelistedIps as $whitelistedIp) {
foreach ($ips as $ip) {
if (self::cidrMatch($ip, $whitelistedIp)) {
$valid = true;
break 2;
}
}
}
if (!$valid) {
throw new InvalidIpException("Provided hostname '$hostname' resolves to '" . implode(', ', $ips)
. "', which doesn't match whitelisted values: "
. implode(', ', $whitelistedIps));
}
}
$blacklistedIps = $options->getList('blacklist', 'ip');
if (!empty($blacklistedIps)) {
foreach ($blacklistedIps as $blacklistedIp) {
foreach ($ips as $ip) {
if (self::cidrMatch($ip, $blacklistedIp)) {
throw new InvalidIpException("Provided hostname '$hostname' resolves to '" . implode(', ', $ips)
. "', which matches a blacklisted value: " . $blacklistedIp);
}
}
}
}
return $hostname;
}
/**
* Re-build a URL based on an array of parts
*
* @param $parts array
*
* @return string
*/
public static function buildUrl($parts) {
$url = '';
$url .= (!empty($parts['scheme']))
? $parts['scheme'] . '://'
: '';
$url .= (!empty($parts['user']))
? rawurlencode($parts['user'])
: '';
$url .= (!empty($parts['pass']))
? ':' . rawurlencode($parts['pass'])
: '';
//If we have a user or pass, make sure to add an "@"
$url .= (!empty($parts['user']) || !empty($parts['pass']))
? '@'
: '';
$url .= (!empty($parts['host']))
? $parts['host']
: '';
$url .= (!empty($parts['port']))
? ':' . (int) $parts['port']
: '';
$url .= (!empty($parts['path']))
? '/' . rawurlencode(substr($parts['path'], 1))
: '';
//The query string is difficult to encode properly
//We need to ensure no special characters can be
//used to mangle the URL, but URL encoding all of it
//prevents the query string from being parsed properly
if (!empty($parts['query'])) {
$query = rawurlencode($parts['query']);
//Replace encoded &, =, ;, [ and ] to originals
$query = str_replace(array('%26', '%3D', '%3B', '%5B', '%5D'),
array('&', '=', ';', '[', ']'),
$query);
$url .= '?' . $query;
}
$url .= (!empty($parts['fragment']))
? '#' . rawurlencode($parts['fragment'])
: '';
return $url;
}
/**
* Resolves a hostname to its IP(s)
*
* @param $hostname string
*
* @return array
*/
public static function resolveHostname($hostname) {
$ips = @gethostbynamel($hostname);
if (empty($ips)) {
throw new InvalidDomainException("Provided hostname '$hostname' doesn't resolve to an IP address");
}
return $ips;
}
/**
* Checks a passed in IP against a CIDR.
* See http://stackoverflow.com/questions/594112/matching-an-ip-to-a-cidr-mask-in-php5
*
* @param $ip string
* @param $cidr string
*
* @return bool
*/
public static function cidrMatch($ip, $cidr) {
if (strpos($cidr, '/') === false) {
//It doesn't have a prefix, just a straight IP match
return $ip == $cidr;
}
list($subnet, $mask) = explode('/', $cidr);
if ((ip2long($ip) & ~((1 << (32 - $mask)) - 1) ) == ip2long($subnet)) {
return true;
}
return false;
}
}