Debian Codegraph @

lib/3rdParty/composer/spomky-labs/pki-framework/src/X501/DN/DNParser.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace SpomkyLabs\Pki\X501\DN;
6
7 use function mb_strlen;
8 use SpomkyLabs\Pki\ASN1\Element;
9 use SpomkyLabs\Pki\ASN1\Exception\DecodeException;
10 use SpomkyLabs\Pki\ASN1\Feature\ElementBase;
11 use function sprintf;
12 use UnexpectedValueException;
13
14 /**
15 * Distinguished Name parsing conforming to RFC 2253 and RFC 1779.
16 *
17 * @see https://tools.ietf.org/html/rfc1779
18 * @see https://tools.ietf.org/html/rfc2253
19 */
20 final class DNParser
21 {
22 /**
23 * RFC 2253 special characters.
24 *
25 * @var string
26 */
27 final public const SPECIAL_CHARS = ',=+<>#;';
28
29 /**
30 * DN string length.
31 */
32 private readonly int $_len;
33
34 /**
35 * @param string $_dn Distinguised name
36 */
37 private function __construct(
38 private readonly string $_dn
39 ) {
40 $this->_len = mb_strlen($_dn, '8bit');
41 }
42
43 /**
44 * Parse distinguished name string to name-components.
45 *
46 * @return array<array<string>>
47 */
48 public static function parseString(string $dn): array
49 {
50 $parser = new self($dn);
51 return $parser->parse();
52 }
53
54 /**
55 * Escape a AttributeValue string conforming to RFC 2253.
56 *
57 * @see https://tools.ietf.org/html/rfc2253#section-2.4
58 */
59 public static function escapeString(string $str): string
60 {
61 // one of the characters ",", "+", """, "\", "<", ">" or ";"
62 $str = preg_replace('/([,\+"\\\<\>;])/u', '\\\\$1', $str);
63 // a space character occurring at the end of the string
64 $str = preg_replace('/( )$/u', '\\\\$1', (string) $str);
65 // a space or "#" character occurring at the beginning of the string
66 $str = preg_replace('/^([ #])/u', '\\\\$1', (string) $str);
67 // implementation specific special characters
68 $str = preg_replace_callback(
69 '/([\pC])/u',
70 function ($m) {
71 $octets = mb_str_split(bin2hex($m[1]), 2, '8bit');
72 return implode('', array_map(static fn ($octet) => '\\' . mb_strtoupper($octet, '8bit'), $octets));
73 },
74 (string) $str
75 );
76 return $str;
77 }
78
79 /**
80 * Parse DN to name-components.
81 *
82 * @return array<array<string>>
83 */
84 private function parse(): array
85 {
86 $offset = 0;
87 $name = $this->_parseName($offset);
88 if ($offset < $this->_len) {
89 $remains = mb_substr($this->_dn, $offset, null, '8bit');
90 throw new UnexpectedValueException(sprintf(
91 'Parser finished before the end of string, remaining: %s',
92 $remains
93 ));
94 }
95 return $name;
96 }
97
98 /**
99 * Parse 'name'.
100 *
101 * name-component *("," name-component)
102 *
103 * @return array<array<string>> Array of name-components
104 */
105 private function _parseName(int &$offset): array
106 {
107 $idx = $offset;
108 $names = [];
109 while ($idx < $this->_len) {
110 $names[] = $this->_parseNameComponent($idx);
111 if ($idx >= $this->_len) {
112 break;
113 }
114 $this->_skipWs($idx);
115 if ($this->_dn[$idx] !== ',' && $this->_dn[$idx] !== ';') {
116 break;
117 }
118 ++$idx;
119 $this->_skipWs($idx);
120 }
121 $offset = $idx;
122 return array_reverse($names);
123 }
124
125 /**
126 * Parse 'name-component'.
127 *
128 * attributeTypeAndValue *("+" attributeTypeAndValue)
129 *
130 * @return array<array<string, string|ElementBase>> Array of [type, value] tuples
131 */
132 private function _parseNameComponent(int &$offset): array
133 {
134 $idx = $offset;
135 $tvpairs = [];
136 while ($idx < $this->_len) {
137 $tvpairs[] = $this->_parseAttrTypeAndValue($idx);
138 $this->_skipWs($idx);
139 if ($idx >= $this->_len || $this->_dn[$idx] !== '+') {
140 break;
141 }
142 ++$idx;
143 $this->_skipWs($idx);
144 }
145 $offset = $idx;
146 return $tvpairs;
147 }
148
149 /**
150 * Parse 'attributeTypeAndValue'.
151 *
152 * attributeType "=" attributeValue
153 *
154 * @return array<string, string|ElementBase> A tuple of [type, value]. Value may be either a string or
155 * an Element, if it's encoded as hexstring.
156 */
157 private function _parseAttrTypeAndValue(int &$offset): array
158 {
159 $idx = $offset;
160 $type = $this->_parseAttrType($idx);
161 $this->_skipWs($idx);
162 if ($idx >= $this->_len || $this->_dn[$idx++] !== '=') {
163 throw new UnexpectedValueException('Invalid type and value pair.');
164 }
165 $this->_skipWs($idx);
166 // hexstring
167 if ($idx < $this->_len && $this->_dn[$idx] === '#') {
168 ++$idx;
169 $data = $this->_parseAttrHexValue($idx);
170 try {
171 $value = Element::fromDER($data);
172 } catch (DecodeException $e) {
173 throw new UnexpectedValueException('Invalid DER encoding from hexstring.', 0, $e);
174 }
175 } else {
176 $value = $this->_parseAttrStringValue($idx);
177 }
178 $offset = $idx;
179 return [$type, $value];
180 }
181
182 /**
183 * Parse 'attributeType'.
184 *
185 * (ALPHA 1*keychar) / oid
186 */
187 private function _parseAttrType(int &$offset): string
188 {
189 $idx = $offset;
190 // dotted OID
191 $type = $this->_regexMatch('/^(?:oid\.)?([0-9]+(?:\.[0-9]+)*)/i', $idx);
192 if ($type === null) {
193 // name
194 $type = $this->_regexMatch('/^[a-z][a-z0-9\-]*/i', $idx);
195 if ($type === null) {
196 throw new UnexpectedValueException('Invalid attribute type.');
197 }
198 }
199 $offset = $idx;
200 return $type;
201 }
202
203 /**
204 * Parse 'attributeValue' of string type.
205 */
206 private function _parseAttrStringValue(int &$offset): string
207 {
208 $idx = $offset;
209 if ($idx >= $this->_len) {
210 return '';
211 }
212 if ($this->_dn[$idx] === '"') { // quoted string
213 $val = $this->_parseQuotedAttrString($idx);
214 } else { // string
215 $val = $this->_parseAttrString($idx);
216 }
217 $offset = $idx;
218 return $val;
219 }
220
221 /**
222 * Parse plain 'attributeValue' string.
223 */
224 private function _parseAttrString(int &$offset): string
225 {
226 $idx = $offset;
227 $val = '';
228 $wsidx = null;
229 while ($idx < $this->_len) {
230 $c = $this->_dn[$idx];
231 // pair (escape sequence)
232 if ($c === '\\') {
233 ++$idx;
234 $val .= $this->_parsePairAfterSlash($idx);
235 $wsidx = null;
236 continue;
237 }
238 if ($c === '"') {
239 throw new UnexpectedValueException('Unexpected quotation.');
240 }
241 if (mb_strpos(self::SPECIAL_CHARS, $c, 0, '8bit') !== false) {
242 break;
243 }
244 // keep track of the first consecutive whitespace
245 if ($c === ' ') {
246 if ($wsidx === null) {
247 $wsidx = $idx;
248 }
249 } else {
250 $wsidx = null;
251 }
252 // stringchar
253 $val .= $c;
254 ++$idx;
255 }
256 // if there was non-escaped whitespace in the end of the value
257 if ($wsidx !== null) {
258 $val = mb_substr($val, 0, -($idx - $wsidx), '8bit');
259 }
260 $offset = $idx;
261 return $val;
262 }
263
264 /**
265 * Parse quoted 'attributeValue' string.
266 *
267 * @param int $offset Offset to starting quote
268 */
269 private function _parseQuotedAttrString(int &$offset): string
270 {
271 $idx = $offset + 1;
272 $val = '';
273 while ($idx < $this->_len) {
274 $c = $this->_dn[$idx];
275 if ($c === '\\') { // pair
276 ++$idx;
277 $val .= $this->_parsePairAfterSlash($idx);
278 continue;
279 }
280 if ($c === '"') {
281 ++$idx;
282 break;
283 }
284 $val .= $c;
285 ++$idx;
286 }
287 $offset = $idx;
288 return $val;
289 }
290
291 /**
292 * Parse 'attributeValue' of binary type.
293 */
294 private function _parseAttrHexValue(int &$offset): string
295 {
296 $idx = $offset;
297 $hexstr = $this->_regexMatch('/^(?:[0-9a-f]{2})+/i', $idx);
298 if ($hexstr === null) {
299 throw new UnexpectedValueException('Invalid hexstring.');
300 }
301 $data = hex2bin($hexstr);
302 $offset = $idx;
303 return $data;
304 }
305
306 /**
307 * Parse 'pair' after leading slash.
308 */
309 private function _parsePairAfterSlash(int &$offset): string
310 {
311 $idx = $offset;
312 if ($idx >= $this->_len) {
313 throw new UnexpectedValueException('Unexpected end of escape sequence.');
314 }
315 $c = $this->_dn[$idx++];
316 // special | \ | " | SPACE
317 if (mb_strpos(self::SPECIAL_CHARS . '\\" ', $c, 0, '8bit') !== false) {
318 $val = $c;
319 } else { // hexpair
320 if ($idx >= $this->_len) {
321 throw new UnexpectedValueException('Unexpected end of hexpair.');
322 }
323 $val = @hex2bin($c . $this->_dn[$idx++]);
324 if ($val === false) {
325 throw new UnexpectedValueException('Invalid hexpair.');
326 }
327 }
328 $offset = $idx;
329 return $val;
330 }
331
332 /**
333 * Match DN to pattern and extract the last capture group.
334 *
335 * Updates offset to fully matched pattern.
336 *
337 * @return null|string Null if pattern doesn't match
338 */
339 private function _regexMatch(string $pattern, int &$offset): ?string
340 {
341 $idx = $offset;
342 if (preg_match($pattern, mb_substr($this->_dn, $idx, null, '8bit'), $match) !== 1) {
343 return null;
344 }
345 $idx += mb_strlen($match[0], '8bit');
346 $offset = $idx;
347 return end($match);
348 }
349
350 /**
351 * Skip consecutive spaces.
352 */
353 private function _skipWs(int &$offset): void
354 {
355 $idx = $offset;
356 while ($idx < $this->_len) {
357 if ($this->_dn[$idx] !== ' ') {
358 break;
359 }
360 ++$idx;
361 }
362 $offset = $idx;
363 }
364 }