Passed
Push — master ( c1e68f...f0bd78 )
by Sam
01:33 queued 10s
created

Validator::isUnsignedInteger()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 4
nc 3
nop 2
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 3
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Badcow DNS Library.
7
 *
8
 * (c) Samuel Williams <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Badcow\DNS;
15
16
use Badcow\DNS\Rdata\CNAME;
17
use Badcow\DNS\Rdata\NS;
18
use Badcow\DNS\Rdata\SOA;
19
20
class Validator
21
{
22
    const ZONE_OKAY = 0;
23
24
    const ZONE_NO_SOA = 1;
25
26
    const ZONE_TOO_MANY_SOA = 2;
27
28
    const ZONE_NO_NS = 4;
29
30
    const ZONE_NO_CLASS = 8;
31
32
    const ZONE_TOO_MANY_CLASSES = 16;
33
34
    /**
35
     * Validate the string as a valid hostname in accordance with RFC 952 {@link https://tools.ietf.org/html/rfc952}
36
     * and RFC 1123 {@link https://tools.ietf.org/html/rfc1123}.
37
     *
38
     * @param string $name
39
     *
40
     * @return bool
41
     */
42 1
    public static function hostName(string $name): bool
43
    {
44 1
        return self::fullyQualifiedDomainName(rtrim($name, '.').'.');
45
    }
46
47
    /**
48
     * Validate the string is a Fully Qualified Domain Name.
49
     *
50
     * @param string $name
51
     *
52
     * @return bool
53
     */
54 95
    public static function fullyQualifiedDomainName(string $name): bool
55
    {
56 95
        if ('.' === $name) {
57 8
            return true;
58
        }
59
60 87
        return strlen($name) < 254 &&
61 87
            (1 === preg_match('/^(?:(?!-)[a-z0-9\-]{1,63}(?<!-)\.){1,127}$/i', $name));
62
    }
63
64
    /**
65
     * Validate the name for a Resource Record. This is distinct from validating a hostname in that this function
66
     * will permit '@' and wildcards as well as underscores used in SRV records.
67
     *
68
     * @param string $name
69
     *
70
     * @return bool
71
     */
72 36
    public static function resourceRecordName(string $name): bool
73
    {
74 36
        return strlen($name) < 254 &&
75 36
            (1 === preg_match('/(?:^(?:\*\.)?((?!-)[a-z0-9_\-]{1,63}(?<!-)\.?){1,127}$)|^@$|^\*$/i', $name));
76
    }
77
78
    /**
79
     * Validates an IPv4 Address.
80
     *
81
     * @static
82
     *
83
     * @param string $address
84
     *
85
     * @return bool
86
     */
87 58
    public static function ipv4(string $address): bool
88
    {
89 58
        return (bool) filter_var($address, FILTER_VALIDATE_IP, [
90 58
            'flags' => FILTER_FLAG_IPV4,
91
        ]);
92
    }
93
94
    /**
95
     * Validates an IPv6 Address.
96
     *
97
     * @static
98
     *
99
     * @param string $address
100
     *
101
     * @return bool
102
     */
103 57
    public static function ipv6(string $address): bool
104
    {
105 57
        return (bool) filter_var($address, FILTER_VALIDATE_IP, [
106 57
            'flags' => FILTER_FLAG_IPV6,
107
        ]);
108
    }
109
110
    /**
111
     * Validates an IPv4 or IPv6 address.
112
     *
113
     * @static
114
     *
115
     * @param string $address
116
     *
117
     * @return bool
118
     */
119 1
    public static function ipAddress(string $address): bool
120
    {
121 1
        return (bool) filter_var($address, FILTER_VALIDATE_IP);
122
    }
123
124
    /**
125
     * Validates that the zone meets
126
     * RFC-1035 especially that:
127
     *   1) 5.2.1 All RRs in the file should be of the same class.
128
     *   2) 5.2.2 Exactly one SOA RR should be present at the top of the zone.
129
     *   3) There is at least one NS record.
130
     *
131
     * Return values are:
132
     *   - ZONE_NO_SOA
133
     *   - ZONE_TOO_MANY_SOA
134
     *   - ZONE_NO_NS
135
     *   - ZONE_NO_CLASS
136
     *   - ZONE_TOO_MANY_CLASSES
137
     *   - ZONE_OKAY
138
     *
139
     * You SHOULD compare these return values to the defined constants of this
140
     * class rather than against integers directly.
141
     *
142
     * @param Zone $zone
143
     *
144
     * @return int
145
     */
146 4
    public static function zone(Zone $zone): int
147
    {
148 4
        $n_soa = self::countResourceRecords($zone, SOA::TYPE);
149 4
        $n_ns = self::countResourceRecords($zone, NS::TYPE);
150 4
        $n_class = self::countClasses($zone);
151
152 4
        $totalError = 0;
153
154
        $incrementError = function (bool $errorCondition, int $errorOrdinal) use (&$totalError): void {
155 4
            $totalError += $errorCondition ? $errorOrdinal : 0;
156 4
        };
157
158 4
        $incrementError($n_soa < 1, self::ZONE_NO_SOA);
159 4
        $incrementError($n_soa > 1, self::ZONE_TOO_MANY_SOA);
160 4
        $incrementError($n_ns < 1, self::ZONE_NO_NS);
161 4
        $incrementError($n_class < 1, self::ZONE_NO_CLASS);
162 4
        $incrementError($n_class > 1, self::ZONE_TOO_MANY_CLASSES);
163
164 4
        return $totalError;
165
    }
166
167
    /**
168
     * Counts the number of Resource Records of a particular type ($type) in a Zone.
169
     *
170
     * @param Zone   $zone
171
     * @param string $type The ResourceRecord type to be counted. If NULL, then the method will return
172
     *                     the number of records without RData.
173
     *
174
     * @return int the number of records to be counted
175
     */
176 4
    public static function countResourceRecords(Zone $zone, ?string $type = null): int
177
    {
178 4
        $n = 0;
179 4
        foreach ($zone as $rr) {
180 4
            $n += (int) ($type === $rr->getType());
181
        }
182
183 4
        return $n;
184
    }
185
186
    /**
187
     * Validates a reverse IPv4 address. Ensures that all octets are in the range [0-255].
188
     *
189
     * @param string $address
190
     *
191
     * @return bool
192
     */
193 1
    public static function reverseIpv4(string $address): bool
194
    {
195 1
        $pattern = '/^((?:[0-9]+\.){1,4})in\-addr\.arpa\.$/i';
196
197 1
        if (1 !== preg_match($pattern, $address, $matches)) {
198 1
            return false;
199
        }
200
201 1
        $octets = explode('.', $matches[1]);
202 1
        array_pop($octets); //Remove the last decimal from the array
203
204 1
        foreach ($octets as $octet) {
205 1
            if ((int) $octet > 255) {
206 1
                return false;
207
            }
208
        }
209
210 1
        return true;
211
    }
212
213
    /**
214
     * Validates a reverse IPv6 address.
215
     *
216
     * @param string $address
217
     *
218
     * @return bool
219
     */
220 1
    public static function reverseIpv6(string $address): bool
221
    {
222 1
        $pattern = '/^(?:[0-9a-f]\.){1,32}ip6\.arpa\.$/i';
223
224 1
        return 1 === preg_match($pattern, $address);
225
    }
226
227
    /**
228
     * Determine the number of unique non-null classes in a Zone. In a valid zone this MUST be 1.
229
     *
230
     * @param Zone $zone
231
     *
232
     * @return int
233
     */
234 4
    private static function countClasses(Zone $zone): int
235
    {
236 4
        $classes = [];
237
238 4
        foreach ($zone as $rr) {
239 4
            if (null !== $rr->getClass()) {
240 4
                $classes[$rr->getClass()] = null;
241
            }
242
        }
243
244 4
        return count($classes);
245
    }
246
247
    /**
248
     * Ensure $zone does not contain existing CNAME alias corresponding to $newRecord's name.
249
     *
250
     * E.g.
251
     *      www IN CNAME example.com.
252
     *      www IN TXT "This is a violation of DNS specifications."
253
     *
254
     * @see https://tools.ietf.org/html/rfc1034#section-3.6.2
255
     *
256
     * @param Zone           $zone
257
     * @param ResourceRecord $newRecord
258
     *
259
     * @return bool
260
     */
261 1
    public static function noAliasInZone(Zone $zone, ResourceRecord $newRecord): bool
262
    {
263 1
        foreach ($zone as $rr) {
264 1
            if (CNAME::TYPE === $rr->getType()
265 1
                && $newRecord->getName() === $rr->getName()) {
266 1
                return false;
267
            }
268
        }
269
270 1
        return true;
271
    }
272
273
    /**
274
     * Determine if string is a base64 encoded string.
275
     *
276
     * @param string $string A base64 encoded string
277
     *
278
     * @return bool
279
     */
280 21
    public static function isBase64Encoded(string $string): bool
281
    {
282 21
        if (1 !== preg_match('/^[a-zA-Z0-9\/\r\n+ ]*={0,2}$/', $string)) {
283 1
            return false;
284
        }
285
286 21
        if (null === $string = preg_replace('/[^a-zA-Z0-9\/+=]/', '', $string)) {
287
            return false;
288
        }
289
290 21
        if (false === $decoded = base64_decode($string, true)) {
291 1
            return false;
292
        }
293
294 21
        return $string === base64_encode($decoded);
295
    }
296
297
    /**
298
     * Determine if string is a base32 encoded string.
299
     *
300
     * @param string $string
301
     *
302
     * @return bool
303
     */
304 1
    public static function isBase32Encoded(string $string): bool
305
    {
306 1
        return 1 === preg_match('/^[A-Z2-7]+=*$/', $string);
307
    }
308
309
    /**
310
     * Determine if string is a base32hex (extended hex) encoded string.
311
     *
312
     * @param string $string
313
     *
314
     * @return bool
315
     */
316 4
    public static function isBase32HexEncoded(string $string): bool
317
    {
318 4
        return 1 === preg_match('/^[a-zA-Z0-9]+=*$/', $string);
319
    }
320
321
    /**
322
     * Determine if string is a base16 encoded string.
323
     *
324
     * @param string $string
325
     *
326
     * @return bool
327
     */
328 7
    public static function isBase16Encoded(string $string): bool
329
    {
330 7
        return 1 === preg_match('/^[0-9a-f]+$/i', $string);
331
    }
332
333
    /**
334
     * Determine if $integer is an unsigned integer less than 2^$numberOfBits.
335
     *
336
     * @param int $integer      The integer to test
337
     * @param int $numberOfBits The upper limit that the integer can be expressed as an exponent of 2
338
     *
339
     * @return bool
340
     */
341 90
    public static function isUnsignedInteger(int $integer, int $numberOfBits): bool
342
    {
343 90
        $maxBits = PHP_INT_SIZE * 8 - 1;
344
345 90
        if ($numberOfBits > $maxBits) {
346 1
            throw new \RuntimeException(sprintf('Number of bits "%d" exceeds maximum binary exponent of "%d".', $numberOfBits, $maxBits));
347
        }
348
349 90
        return (0 <= $integer) && ($integer < (2 ** $numberOfBits));
350
    }
351
}
352