Passed
Pull Request — master (#69)
by
unknown
05:00
created

Validator   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 325
Duplicated Lines 0 %

Test Coverage

Coverage 98.68%

Importance

Changes 14
Bugs 0 Features 1
Metric Value
eloc 66
c 14
b 0
f 1
dl 0
loc 325
ccs 75
cts 76
cp 0.9868
rs 9.84
wmc 32

17 Methods

Rating   Name   Duplication   Size   Complexity  
A zone() 0 19 2
A ipv4() 0 4 1
A ipAddress() 0 3 1
A reverseIpv6() 0 5 1
A ipv6() 0 4 1
A reverseIpv4() 0 18 4
A countResourceRecords() 0 8 2
A countClasses() 0 11 3
A fullyQualifiedDomainName() 0 8 3
A hostName() 0 3 1
A resourceRecordName() 0 4 2
A isBase32HexEncoded() 0 3 1
A isBase32Encoded() 0 3 1
A isUnsignedInteger() 0 9 3
A noAliasInZone() 0 3 1
A isBase64Encoded() 0 15 4
A isBase16Encoded() 0 3 1
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\NS;
17
use Badcow\DNS\Rdata\SOA;
18
use Badcow\DNS\Validator\AbstractValidator;
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 98
    public static function fullyQualifiedDomainName(string $name): bool
55
    {
56 98
        if ('.' === $name) {
57 8
            return true;
58
        }
59
60 90
        return strlen($name) < 254 &&
61 90
            (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 61
    public static function ipv4(string $address): bool
88
    {
89 61
        return (bool) filter_var($address, FILTER_VALIDATE_IP, [
90 61
            '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 61
    public static function ipv6(string $address): bool
104
    {
105 61
        return (bool) filter_var($address, FILTER_VALIDATE_IP, [
106 61
            '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
     * @deprecated Use \Badcow\DNS\Validator\AbstractValidator instead
262
     */
263 1
    public static function noAliasInZone(Zone $zone, ResourceRecord $newRecord): bool
264
    {
265 1
        return AbstractValidator::noCNAMEinZone($zone, $newRecord);
266
    }
267
268
    /**
269
     * Determine if string is a base64 encoded string.
270
     *
271
     * @param string $string A base64 encoded string
272
     *
273
     * @return bool
274
     */
275 21
    public static function isBase64Encoded(string $string): bool
276
    {
277 21
        if (1 !== preg_match('/^[a-zA-Z0-9\/\r\n+ ]*={0,2}$/', $string)) {
278 1
            return false;
279
        }
280
281 21
        if (null === $string = preg_replace('/[^a-zA-Z0-9\/+=]/', '', $string)) {
282
            return false;
283
        }
284
285 21
        if (false === $decoded = base64_decode($string, true)) {
286 1
            return false;
287
        }
288
289 21
        return $string === base64_encode($decoded);
290
    }
291
292
    /**
293
     * Determine if string is a base32 encoded string.
294
     *
295
     * @param string $string
296
     *
297
     * @return bool
298
     */
299 1
    public static function isBase32Encoded(string $string): bool
300
    {
301 1
        return 1 === preg_match('/^[A-Z2-7]+=*$/', $string);
302
    }
303
304
    /**
305
     * Determine if string is a base32hex (extended hex) encoded string.
306
     *
307
     * @param string $string
308
     *
309
     * @return bool
310
     */
311 4
    public static function isBase32HexEncoded(string $string): bool
312
    {
313 4
        return 1 === preg_match('/^[a-zA-Z0-9]+=*$/', $string);
314
    }
315
316
    /**
317
     * Determine if string is a base16 encoded string.
318
     *
319
     * @param string $string
320
     *
321
     * @return bool
322
     */
323 7
    public static function isBase16Encoded(string $string): bool
324
    {
325 7
        return 1 === preg_match('/^[0-9a-f]+$/i', $string);
326
    }
327
328
    /**
329
     * Determine if $integer is an unsigned integer less than 2^$numberOfBits.
330
     *
331
     * @param int $integer      The integer to test
332
     * @param int $numberOfBits The upper limit that the integer can be expressed as an exponent of 2
333
     *
334
     * @return bool
335
     */
336 91
    public static function isUnsignedInteger(int $integer, int $numberOfBits): bool
337
    {
338 91
        $maxBits = PHP_INT_SIZE * 8 - 1;
339
340 91
        if ($numberOfBits > $maxBits) {
341 1
            throw new \RuntimeException(sprintf('Number of bits "%d" exceeds maximum binary exponent of "%d".', $numberOfBits, $maxBits));
342
        }
343
344 91
        return (0 <= $integer) && ($integer < (2 ** $numberOfBits));
345
    }
346
}
347