-
Notifications
You must be signed in to change notification settings - Fork 746
Expand file tree
/
Copy pathSecurity.php
More file actions
120 lines (105 loc) · 2.7 KB
/
Security.php
File metadata and controls
120 lines (105 loc) · 2.7 KB
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
<?php
/**
* Html2Pdf Library - Security
*
* HTML => PDF converter
* distributed under the OSL-3.0 License
*
* @package Html2pdf
* @author Laurent MINGUET <webmaster@html2pdf.fr>
* @copyright 2025 Laurent MINGUET
*/
namespace Spipu\Html2Pdf\Security;
use Spipu\Html2Pdf\Exception\HtmlParsingException;
class Security implements SecurityInterface
{
/**
* @var string[]
*/
protected $allowedSchemes = ['file', 'http', 'https'];
/**
* @var string[]
*/
protected $allowedHosts = [];
/**
* @var bool
*/
private $checkAllowedHosts = true;
/**
* @param string $path
* @return void
* @throws HtmlParsingException
*/
public function checkValidPath(string $path): void
{
$path = trim(strtolower($path));
if (!$this->checkValidPathScheme($path)) {
throw new HtmlParsingException('Unauthorized path scheme');
}
if ($this->checkAllowedHosts && !$this->checkValidPathHost($path)) {
throw new HtmlParsingException('Unauthorized path host on ' . $path . ' => ' . implode('|', $this->allowedHosts));
}
}
/**
* @param string $path
* @return bool
*/
private function checkValidPathScheme(string $path): bool
{
$scheme = parse_url($path, PHP_URL_SCHEME);
if ($scheme === null) {
return true;
}
if (in_array($scheme, $this->allowedSchemes)) {
return true;
}
// for local file on windows
if (strlen($scheme) === 1 && preg_match('/^[a-z]$/i', $scheme)) {
return true;
}
return false;
}
/**
* @param string $path
* @return bool
*/
private function checkValidPathHost(string $path): bool
{
$scheme = parse_url($path, PHP_URL_SCHEME);
$host = parse_url($path, PHP_URL_HOST);
// If it is a local file => no host
if (
$scheme === null
|| $scheme === 'file'
|| (strlen($scheme) === 1 && preg_match('/^[a-z]$/i', $scheme))
) {
return true;
}
return in_array($host, $this->allowedHosts);
}
/**
* @param string $host
* @return void
*/
public function addAllowedHost(string $host): void
{
$host = trim(strtolower($host));
if (!in_array($host, $this->allowedHosts)) {
$this->allowedHosts[] = $host;
}
}
/**
* @return void
*/
public function resetAllowedHosts(): void
{
$this->allowedHosts = [];
}
/**
* @return void
*/
public function disableCheckAllowedHosts(): void
{
$this->checkAllowedHosts = false;
}
}